summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
Diffstat (limited to 'tools')
-rw-r--r--tools/gfx-unit-test/buffer-barrier-test.cpp298
-rw-r--r--tools/gfx-unit-test/clear-texture-test.cpp141
-rw-r--r--tools/gfx-unit-test/compute-smoke.cpp202
-rw-r--r--tools/gfx-unit-test/compute-trivial.cpp169
-rw-r--r--tools/gfx-unit-test/copy-texture-tests.cpp1642
-rw-r--r--tools/gfx-unit-test/create-buffer-from-handle.cpp178
-rw-r--r--tools/gfx-unit-test/existing-device-handle-test.cpp254
-rw-r--r--tools/gfx-unit-test/format-unit-tests.cpp2524
-rw-r--r--tools/gfx-unit-test/get-buffer-resource-handle-test.cpp159
-rw-r--r--tools/gfx-unit-test/get-cmd-buffer-handle-test.cpp154
-rw-r--r--tools/gfx-unit-test/get-cmd-queue-handle-test.cpp125
-rw-r--r--tools/gfx-unit-test/get-supported-resource-states-test.cpp325
-rw-r--r--tools/gfx-unit-test/get-texture-resource-handle-test.cpp146
-rw-r--r--tools/gfx-unit-test/gfx-test-texture-util.cpp418
-rw-r--r--tools/gfx-unit-test/gfx-test-texture-util.h332
-rw-r--r--tools/gfx-unit-test/gfx-test-util.cpp618
-rw-r--r--tools/gfx-unit-test/gfx-test-util.h252
-rw-r--r--tools/gfx-unit-test/instanced-draw-tests.cpp990
-rw-r--r--tools/gfx-unit-test/link-time-constant.cpp285
-rw-r--r--tools/gfx-unit-test/link-time-default.cpp340
-rw-r--r--tools/gfx-unit-test/link-time-options.cpp274
-rw-r--r--tools/gfx-unit-test/link-time-type.cpp269
-rw-r--r--tools/gfx-unit-test/mutable-shader-object.cpp247
-rw-r--r--tools/gfx-unit-test/nested-parameter-block.cpp284
-rw-r--r--tools/gfx-unit-test/precompiled-module-2.cpp361
-rw-r--r--tools/gfx-unit-test/precompiled-module-cache.cpp336
-rw-r--r--tools/gfx-unit-test/precompiled-module.cpp273
-rw-r--r--tools/gfx-unit-test/ray-tracing-tests.cpp910
-rw-r--r--tools/gfx-unit-test/resolve-resource-tests.cpp619
-rw-r--r--tools/gfx-unit-test/root-mutable-shader-object.cpp208
-rw-r--r--tools/gfx-unit-test/root-shader-parameter.cpp244
-rw-r--r--tools/gfx-unit-test/sampler-array.cpp261
-rw-r--r--tools/gfx-unit-test/shader-cache-tests.cpp1857
-rw-r--r--tools/gfx-unit-test/shared-buffers-tests.cpp222
-rw-r--r--tools/gfx-unit-test/shared-textures-tests.cpp440
-rw-r--r--tools/gfx-unit-test/swap-chain-resize-test.cpp427
-rw-r--r--tools/gfx-unit-test/texture-types-tests.cpp1143
-rw-r--r--tools/gfx-unit-test/uint16-structured-buffer.cpp161
-rw-r--r--tools/gfx-util/shader-cursor.cpp41
-rw-r--r--tools/gfx-util/shader-cursor.h24
-rw-r--r--tools/gfx/apple/cocoa-util.h10
-rw-r--r--tools/gfx/command-encoder-com-forward.h301
-rw-r--r--tools/gfx/command-writer.h25
-rw-r--r--tools/gfx/cpu/cpu-base.h45
-rw-r--r--tools/gfx/cpu/cpu-buffer.cpp2
-rw-r--r--tools/gfx/cpu/cpu-buffer.h5
-rw-r--r--tools/gfx/cpu/cpu-device.cpp493
-rw-r--r--tools/gfx/cpu/cpu-device.h22
-rw-r--r--tools/gfx/cpu/cpu-helper-functions.cpp1
-rw-r--r--tools/gfx/cpu/cpu-helper-functions.h1
-rw-r--r--tools/gfx/cpu/cpu-pipeline-state.cpp22
-rw-r--r--tools/gfx/cpu/cpu-query.cpp4
-rw-r--r--tools/gfx/cpu/cpu-query.h4
-rw-r--r--tools/gfx/cpu/cpu-resource-views.cpp36
-rw-r--r--tools/gfx/cpu/cpu-resource-views.h28
-rw-r--r--tools/gfx/cpu/cpu-shader-object-layout.cpp64
-rw-r--r--tools/gfx/cpu/cpu-shader-object-layout.h20
-rw-r--r--tools/gfx/cpu/cpu-shader-object.cpp72
-rw-r--r--tools/gfx/cpu/cpu-shader-object.h28
-rw-r--r--tools/gfx/cpu/cpu-shader-program.h5
-rw-r--r--tools/gfx/cpu/cpu-texture.cpp48
-rw-r--r--tools/gfx/cpu/cpu-texture.h35
-rw-r--r--tools/gfx/cuda/cuda-base.h76
-rw-r--r--tools/gfx/cuda/cuda-buffer.cpp5
-rw-r--r--tools/gfx/cuda/cuda-buffer.h8
-rw-r--r--tools/gfx/cuda/cuda-command-buffer.cpp6
-rw-r--r--tools/gfx/cuda/cuda-command-buffer.h13
-rw-r--r--tools/gfx/cuda/cuda-command-encoder.cpp26
-rw-r--r--tools/gfx/cuda/cuda-command-encoder.h30
-rw-r--r--tools/gfx/cuda/cuda-command-queue.cpp29
-rw-r--r--tools/gfx/cuda/cuda-command-queue.h18
-rw-r--r--tools/gfx/cuda/cuda-device.cpp257
-rw-r--r--tools/gfx/cuda/cuda-device.h44
-rw-r--r--tools/gfx/cuda/cuda-helper-functions.cpp12
-rw-r--r--tools/gfx/cuda/cuda-helper-functions.h100
-rw-r--r--tools/gfx/cuda/cuda-query.cpp4
-rw-r--r--tools/gfx/cuda/cuda-query.h4
-rw-r--r--tools/gfx/cuda/cuda-resource-views.h1
-rw-r--r--tools/gfx/cuda/cuda-shader-object-layout.cpp51
-rw-r--r--tools/gfx/cuda/cuda-shader-object-layout.h5
-rw-r--r--tools/gfx/cuda/cuda-shader-object.cpp37
-rw-r--r--tools/gfx/cuda/cuda-shader-object.h31
-rw-r--r--tools/gfx/cuda/cuda-shader-program.h1
-rw-r--r--tools/gfx/cuda/cuda-texture.h7
-rw-r--r--tools/gfx/d3d/d3d-swapchain.h38
-rw-r--r--tools/gfx/d3d/d3d-util.cpp789
-rw-r--r--tools/gfx/d3d/d3d-util.h101
-rw-r--r--tools/gfx/d3d11/d3d11-base.h61
-rw-r--r--tools/gfx/d3d11/d3d11-buffer.cpp2
-rw-r--r--tools/gfx/d3d11/d3d11-buffer.h6
-rw-r--r--tools/gfx/d3d11/d3d11-device.cpp979
-rw-r--r--tools/gfx/d3d11/d3d11-device.h52
-rw-r--r--tools/gfx/d3d11/d3d11-helper-functions.cpp494
-rw-r--r--tools/gfx/d3d11/d3d11-helper-functions.h467
-rw-r--r--tools/gfx/d3d11/d3d11-pipeline-state.h12
-rw-r--r--tools/gfx/d3d11/d3d11-query.cpp21
-rw-r--r--tools/gfx/d3d11/d3d11-query.h23
-rw-r--r--tools/gfx/d3d11/d3d11-resource-views.h8
-rw-r--r--tools/gfx/d3d11/d3d11-scopeNVAPI.h5
-rw-r--r--tools/gfx/d3d11/d3d11-shader-object-layout.cpp60
-rw-r--r--tools/gfx/d3d11/d3d11-shader-object-layout.h107
-rw-r--r--tools/gfx/d3d11/d3d11-shader-object.cpp80
-rw-r--r--tools/gfx/d3d11/d3d11-shader-object.h115
-rw-r--r--tools/gfx/d3d11/d3d11-shader-program.cpp1
-rw-r--r--tools/gfx/d3d11/d3d11-swap-chain.cpp5
-rw-r--r--tools/gfx/d3d11/d3d11-texture.h1
-rw-r--r--tools/gfx/d3d11/d3d11-vertex-layout.h4
-rw-r--r--tools/gfx/d3d12/d3d12-base.h73
-rw-r--r--tools/gfx/d3d12/d3d12-buffer.cpp12
-rw-r--r--tools/gfx/d3d12/d3d12-buffer.h7
-rw-r--r--tools/gfx/d3d12/d3d12-command-buffer.cpp13
-rw-r--r--tools/gfx/d3d12/d3d12-command-buffer.h27
-rw-r--r--tools/gfx/d3d12/d3d12-command-encoder.cpp418
-rw-r--r--tools/gfx/d3d12/d3d12-command-encoder.h73
-rw-r--r--tools/gfx/d3d12/d3d12-command-queue.cpp19
-rw-r--r--tools/gfx/d3d12/d3d12-command-queue.h10
-rw-r--r--tools/gfx/d3d12/d3d12-descriptor-heap.cpp26
-rw-r--r--tools/gfx/d3d12/d3d12-descriptor-heap.h182
-rw-r--r--tools/gfx/d3d12/d3d12-device.cpp772
-rw-r--r--tools/gfx/d3d12/d3d12-device.h74
-rw-r--r--tools/gfx/d3d12/d3d12-fence.cpp6
-rw-r--r--tools/gfx/d3d12/d3d12-fence.h2
-rw-r--r--tools/gfx/d3d12/d3d12-helper-functions.cpp390
-rw-r--r--tools/gfx/d3d12/d3d12-helper-functions.h14
-rw-r--r--tools/gfx/d3d12/d3d12-pipeline-state-stream.h432
-rw-r--r--tools/gfx/d3d12/d3d12-pipeline-state.cpp129
-rw-r--r--tools/gfx/d3d12/d3d12-pipeline-state.h3
-rw-r--r--tools/gfx/d3d12/d3d12-posix-synchapi.cpp136
-rw-r--r--tools/gfx/d3d12/d3d12-posix-synchapi.h24
-rw-r--r--tools/gfx/d3d12/d3d12-query.cpp18
-rw-r--r--tools/gfx/d3d12/d3d12-query.h8
-rw-r--r--tools/gfx/d3d12/d3d12-resource-views.cpp177
-rw-r--r--tools/gfx/d3d12/d3d12-resource-views.h10
-rw-r--r--tools/gfx/d3d12/d3d12-resource.cpp123
-rw-r--r--tools/gfx/d3d12/d3d12-resource.h176
-rw-r--r--tools/gfx/d3d12/d3d12-sal-defs.h128
-rw-r--r--tools/gfx/d3d12/d3d12-sampler.cpp5
-rw-r--r--tools/gfx/d3d12/d3d12-shader-object-layout.cpp288
-rw-r--r--tools/gfx/d3d12/d3d12-shader-object-layout.h30
-rw-r--r--tools/gfx/d3d12/d3d12-shader-object.cpp226
-rw-r--r--tools/gfx/d3d12/d3d12-shader-object.h29
-rw-r--r--tools/gfx/d3d12/d3d12-shader-program.cpp3
-rw-r--r--tools/gfx/d3d12/d3d12-shader-program.h3
-rw-r--r--tools/gfx/d3d12/d3d12-shader-table.cpp10
-rw-r--r--tools/gfx/d3d12/d3d12-submitter.cpp22
-rw-r--r--tools/gfx/d3d12/d3d12-submitter.h25
-rw-r--r--tools/gfx/d3d12/d3d12-swap-chain.cpp16
-rw-r--r--tools/gfx/d3d12/d3d12-texture.cpp12
-rw-r--r--tools/gfx/d3d12/d3d12-texture.h2
-rw-r--r--tools/gfx/d3d12/d3d12-transient-heap.cpp10
-rw-r--r--tools/gfx/d3d12/d3d12-transient-heap.h10
-rw-r--r--tools/gfx/debug-layer/debug-base.h104
-rw-r--r--tools/gfx/debug-layer/debug-buffer.h5
-rw-r--r--tools/gfx/debug-layer/debug-command-buffer.cpp33
-rw-r--r--tools/gfx/debug-layer/debug-command-buffer.h9
-rw-r--r--tools/gfx/debug-layer/debug-command-encoder.cpp114
-rw-r--r--tools/gfx/debug-layer/debug-command-encoder.h82
-rw-r--r--tools/gfx/debug-layer/debug-command-queue.cpp22
-rw-r--r--tools/gfx/debug-layer/debug-command-queue.h11
-rw-r--r--tools/gfx/debug-layer/debug-device.cpp111
-rw-r--r--tools/gfx/debug-layer/debug-device.h56
-rw-r--r--tools/gfx/debug-layer/debug-fence.cpp5
-rw-r--r--tools/gfx/debug-layer/debug-fence.h4
-rw-r--r--tools/gfx/debug-layer/debug-framebuffer.h3
-rw-r--r--tools/gfx/debug-layer/debug-helper-functions.cpp39
-rw-r--r--tools/gfx/debug-layer/debug-helper-functions.h33
-rw-r--r--tools/gfx/debug-layer/debug-query.h3
-rw-r--r--tools/gfx/debug-layer/debug-resource-views.h5
-rw-r--r--tools/gfx/debug-layer/debug-sampler-state.h2
-rw-r--r--tools/gfx/debug-layer/debug-shader-object.cpp13
-rw-r--r--tools/gfx/debug-layer/debug-shader-object.h22
-rw-r--r--tools/gfx/debug-layer/debug-shader-program.h4
-rw-r--r--tools/gfx/debug-layer/debug-swap-chain.cpp3
-rw-r--r--tools/gfx/debug-layer/debug-swap-chain.h2
-rw-r--r--tools/gfx/debug-layer/debug-texture.cpp5
-rw-r--r--tools/gfx/debug-layer/debug-texture.h3
-rw-r--r--tools/gfx/debug-layer/debug-transient-heap.cpp6
-rw-r--r--tools/gfx/debug-layer/debug-transient-heap.h9
-rw-r--r--tools/gfx/flag-combiner.cpp3
-rw-r--r--tools/gfx/flag-combiner.h38
-rw-r--r--tools/gfx/immediate-renderer-base.cpp187
-rw-r--r--tools/gfx/immediate-renderer-base.h34
-rw-r--r--tools/gfx/metal/metal-api.cpp2
-rw-r--r--tools/gfx/metal/metal-base.h70
-rw-r--r--tools/gfx/metal/metal-buffer.cpp8
-rw-r--r--tools/gfx/metal/metal-buffer.h6
-rw-r--r--tools/gfx/metal/metal-command-buffer.cpp16
-rw-r--r--tools/gfx/metal/metal-command-buffer.h17
-rw-r--r--tools/gfx/metal/metal-command-encoder.cpp163
-rw-r--r--tools/gfx/metal/metal-command-encoder.h83
-rw-r--r--tools/gfx/metal/metal-command-queue.cpp33
-rw-r--r--tools/gfx/metal/metal-command-queue.h10
-rw-r--r--tools/gfx/metal/metal-device.cpp231
-rw-r--r--tools/gfx/metal/metal-device.h67
-rw-r--r--tools/gfx/metal/metal-fence.cpp5
-rw-r--r--tools/gfx/metal/metal-fence.h7
-rw-r--r--tools/gfx/metal/metal-framebuffer.cpp12
-rw-r--r--tools/gfx/metal/metal-helper-functions.cpp1
-rw-r--r--tools/gfx/metal/metal-pipeline-state.cpp134
-rw-r--r--tools/gfx/metal/metal-query.cpp15
-rw-r--r--tools/gfx/metal/metal-query.h3
-rw-r--r--tools/gfx/metal/metal-render-pass.cpp44
-rw-r--r--tools/gfx/metal/metal-render-pass.h4
-rw-r--r--tools/gfx/metal/metal-resource-views.cpp17
-rw-r--r--tools/gfx/metal/metal-resource-views.h12
-rw-r--r--tools/gfx/metal/metal-sampler.cpp10
-rw-r--r--tools/gfx/metal/metal-sampler.h2
-rw-r--r--tools/gfx/metal/metal-shader-object-layout.cpp58
-rw-r--r--tools/gfx/metal/metal-shader-object-layout.h30
-rw-r--r--tools/gfx/metal/metal-shader-object.cpp196
-rw-r--r--tools/gfx/metal/metal-shader-object.h55
-rw-r--r--tools/gfx/metal/metal-shader-program.cpp17
-rw-r--r--tools/gfx/metal/metal-shader-program.h4
-rw-r--r--tools/gfx/metal/metal-swap-chain.cpp18
-rw-r--r--tools/gfx/metal/metal-swap-chain.h6
-rw-r--r--tools/gfx/metal/metal-texture.cpp9
-rw-r--r--tools/gfx/metal/metal-texture.h3
-rw-r--r--tools/gfx/metal/metal-transient-heap.cpp4
-rw-r--r--tools/gfx/metal/metal-transient-heap.h2
-rw-r--r--tools/gfx/metal/metal-util.cpp541
-rw-r--r--tools/gfx/metal/metal-util.h23
-rw-r--r--tools/gfx/metal/metal-vertex-layout.cpp18
-rw-r--r--tools/gfx/metal/metal-vertex-layout.h3
-rw-r--r--tools/gfx/mutable-shader-object.h668
-rw-r--r--tools/gfx/nvapi/nvapi-include.h27
-rw-r--r--tools/gfx/nvapi/nvapi-util.cpp9
-rw-r--r--tools/gfx/nvapi/nvapi-util.h11
-rw-r--r--tools/gfx/open-gl/render-gl.cpp868
-rw-r--r--tools/gfx/open-gl/render-gl.h5
-rw-r--r--tools/gfx/render.cpp172
-rw-r--r--tools/gfx/renderer-shared.cpp372
-rw-r--r--tools/gfx/renderer-shared.h402
-rw-r--r--tools/gfx/resource-desc-utils.cpp26
-rw-r--r--tools/gfx/resource-desc-utils.h22
-rw-r--r--tools/gfx/simple-render-pass-layout.h10
-rw-r--r--tools/gfx/simple-transient-resource-heap.h7
-rw-r--r--tools/gfx/slang-context.h108
-rw-r--r--tools/gfx/transient-resource-heap-base.h21
-rw-r--r--tools/gfx/vulkan/vk-api.cpp30
-rw-r--r--tools/gfx/vulkan/vk-api.h95
-rw-r--r--tools/gfx/vulkan/vk-base.h70
-rw-r--r--tools/gfx/vulkan/vk-buffer.cpp24
-rw-r--r--tools/gfx/vulkan/vk-buffer.h7
-rw-r--r--tools/gfx/vulkan/vk-command-buffer.cpp13
-rw-r--r--tools/gfx/vulkan/vk-command-buffer.h10
-rw-r--r--tools/gfx/vulkan/vk-command-encoder.cpp242
-rw-r--r--tools/gfx/vulkan/vk-command-encoder.h89
-rw-r--r--tools/gfx/vulkan/vk-command-queue.cpp26
-rw-r--r--tools/gfx/vulkan/vk-command-queue.h8
-rw-r--r--tools/gfx/vulkan/vk-descriptor-allocator.cpp11
-rw-r--r--tools/gfx/vulkan/vk-descriptor-allocator.h2
-rw-r--r--tools/gfx/vulkan/vk-device-queue.cpp19
-rw-r--r--tools/gfx/vulkan/vk-device-queue.h50
-rw-r--r--tools/gfx/vulkan/vk-device.cpp698
-rw-r--r--tools/gfx/vulkan/vk-device.h64
-rw-r--r--tools/gfx/vulkan/vk-fence.cpp32
-rw-r--r--tools/gfx/vulkan/vk-fence.h2
-rw-r--r--tools/gfx/vulkan/vk-framebuffer.cpp17
-rw-r--r--tools/gfx/vulkan/vk-helper-functions.cpp264
-rw-r--r--tools/gfx/vulkan/vk-helper-functions.h37
-rw-r--r--tools/gfx/vulkan/vk-module.cpp13
-rw-r--r--tools/gfx/vulkan/vk-module.h40
-rw-r--r--tools/gfx/vulkan/vk-pipeline-dump-layer.cpp280
-rw-r--r--tools/gfx/vulkan/vk-pipeline-dump-layer.h8
-rw-r--r--tools/gfx/vulkan/vk-pipeline-state.cpp89
-rw-r--r--tools/gfx/vulkan/vk-pipeline-state.h3
-rw-r--r--tools/gfx/vulkan/vk-query.cpp17
-rw-r--r--tools/gfx/vulkan/vk-query.h7
-rw-r--r--tools/gfx/vulkan/vk-render-pass.cpp10
-rw-r--r--tools/gfx/vulkan/vk-render-pass.h4
-rw-r--r--tools/gfx/vulkan/vk-resource-views.cpp10
-rw-r--r--tools/gfx/vulkan/vk-resource-views.h9
-rw-r--r--tools/gfx/vulkan/vk-sampler.cpp3
-rw-r--r--tools/gfx/vulkan/vk-shader-object-layout.cpp104
-rw-r--r--tools/gfx/vulkan/vk-shader-object-layout.h12
-rw-r--r--tools/gfx/vulkan/vk-shader-object.cpp72
-rw-r--r--tools/gfx/vulkan/vk-shader-object.h30
-rw-r--r--tools/gfx/vulkan/vk-shader-program.cpp13
-rw-r--r--tools/gfx/vulkan/vk-shader-program.h3
-rw-r--r--tools/gfx/vulkan/vk-shader-table.cpp16
-rw-r--r--tools/gfx/vulkan/vk-swap-chain.cpp61
-rw-r--r--tools/gfx/vulkan/vk-swap-chain.h6
-rw-r--r--tools/gfx/vulkan/vk-texture.cpp6
-rw-r--r--tools/gfx/vulkan/vk-texture.h2
-rw-r--r--tools/gfx/vulkan/vk-transient-heap.cpp16
-rw-r--r--tools/gfx/vulkan/vk-transient-heap.h2
-rw-r--r--tools/gfx/vulkan/vk-util.cpp624
-rw-r--r--tools/gfx/vulkan/vk-util.h76
-rw-r--r--tools/platform/gui.cpp91
-rw-r--r--tools/platform/gui.h15
-rw-r--r--tools/platform/linux/x11-key-code.cpp380
-rw-r--r--tools/platform/linux/x11-window.cpp223
-rw-r--r--tools/platform/model.cpp231
-rw-r--r--tools/platform/model.h33
-rw-r--r--tools/platform/performance-counter.h5
-rw-r--r--tools/platform/placeholder/placeholder-window.cpp17
-rw-r--r--tools/platform/platform-api.h24
-rw-r--r--tools/platform/vector-math.h7
-rw-r--r--tools/platform/window.h75
-rw-r--r--tools/platform/windows/win-window.cpp42
-rw-r--r--tools/render-test/diagnostic-defs.h14
-rw-r--r--tools/render-test/diagnostics.cpp13
-rw-r--r--tools/render-test/diagnostics.h10
-rw-r--r--tools/render-test/options.cpp97
-rw-r--r--tools/render-test/options.h36
-rw-r--r--tools/render-test/png-serialize-util.cpp7
-rw-r--r--tools/render-test/png-serialize-util.h12
-rw-r--r--tools/render-test/render-test-main.cpp584
-rw-r--r--tools/render-test/shader-input-layout.cpp2396
-rw-r--r--tools/render-test/shader-input-layout.h75
-rw-r--r--tools/render-test/shader-renderer-util.cpp47
-rw-r--r--tools/render-test/shader-renderer-util.h18
-rw-r--r--tools/render-test/slang-support.cpp225
-rw-r--r--tools/render-test/slang-support.h66
-rw-r--r--tools/slang-capability-generator/capability-generator-main.cpp432
-rw-r--r--tools/slang-capability-generator/slang-capability-diagnostic-defs.h47
-rw-r--r--tools/slang-cpp-extractor/cpp-extractor-main.cpp118
-rw-r--r--tools/slang-cpp-extractor/diagnostic-defs.h30
-rw-r--r--tools/slang-cpp-extractor/diagnostics.cpp8
-rw-r--r--tools/slang-cpp-extractor/diagnostics.h10
-rw-r--r--tools/slang-cpp-extractor/file-util.cpp37
-rw-r--r--tools/slang-cpp-extractor/file-util.h23
-rw-r--r--tools/slang-cpp-extractor/identifier-lookup.cpp110
-rw-r--r--tools/slang-cpp-extractor/identifier-lookup.h57
-rw-r--r--tools/slang-cpp-extractor/macro-writer.cpp93
-rw-r--r--tools/slang-cpp-extractor/macro-writer.h26
-rw-r--r--tools/slang-cpp-extractor/node-tree.cpp53
-rw-r--r--tools/slang-cpp-extractor/node-tree.h56
-rw-r--r--tools/slang-cpp-extractor/node.cpp45
-rw-r--r--tools/slang-cpp-extractor/node.h236
-rw-r--r--tools/slang-cpp-extractor/options.cpp18
-rw-r--r--tools/slang-cpp-extractor/options.h42
-rw-r--r--tools/slang-cpp-extractor/parser.cpp399
-rw-r--r--tools/slang-cpp-extractor/parser.h45
-rw-r--r--tools/slang-cpp-extractor/unit-test.cpp98
-rw-r--r--tools/slang-cpp-extractor/unit-test.h5
-rw-r--r--tools/slang-embed/slang-embed.cpp78
-rw-r--r--tools/slang-generate/main.cpp289
-rw-r--r--tools/slang-lookup-generator/lookup-generator-main.cpp30
-rw-r--r--tools/slang-profile/slang-profile-main.cpp7
-rw-r--r--tools/slang-reflection-test/slang-reflection-test-main.cpp480
-rw-r--r--tools/slang-replay/main.cpp32
-rw-r--r--tools/slang-spirv-embed-generator/spirv-embed-generator-main.cpp215
-rw-r--r--tools/slang-test/directory-util.cpp13
-rw-r--r--tools/slang-test/directory-util.h46
-rw-r--r--tools/slang-test/filecheck.h32
-rw-r--r--tools/slang-test/options.cpp30
-rw-r--r--tools/slang-test/options.h54
-rw-r--r--tools/slang-test/parse-diagnostic-util.cpp171
-rw-r--r--tools/slang-test/parse-diagnostic-util.h116
-rw-r--r--tools/slang-test/slang-test-main.cpp1390
-rw-r--r--tools/slang-test/slangc-tool.cpp20
-rw-r--r--tools/slang-test/slangc-tool.h10
-rw-r--r--tools/slang-test/test-context.cpp41
-rw-r--r--tools/slang-test/test-context.h59
-rw-r--r--tools/slang-test/test-reporter.cpp260
-rw-r--r--tools/slang-test/test-reporter.h90
-rw-r--r--tools/slang-unit-test/unit-test-byte-encode.cpp45
-rw-r--r--tools/slang-unit-test/unit-test-com-host-callable.cpp134
-rw-r--r--tools/slang-unit-test/unit-test-command-line-args.cpp50
-rw-r--r--tools/slang-unit-test/unit-test-compression.cpp24
-rw-r--r--tools/slang-unit-test/unit-test-crypto.cpp44
-rw-r--r--tools/slang-unit-test/unit-test-decl-tree-reflection.cpp162
-rw-r--r--tools/slang-unit-test/unit-test-default-matrix-layout.cpp32
-rw-r--r--tools/slang-unit-test/unit-test-fcpw-compile.cpp21
-rw-r--r--tools/slang-unit-test/unit-test-file-system.cpp880
-rw-r--r--tools/slang-unit-test/unit-test-find-check-entrypoint.cpp32
-rw-r--r--tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp30
-rw-r--r--tools/slang-unit-test/unit-test-find-type-by-name.cpp16
-rw-r--r--tools/slang-unit-test/unit-test-free-list.cpp11
-rw-r--r--tools/slang-unit-test/unit-test-function-reflection.cpp53
-rw-r--r--tools/slang-unit-test/unit-test-generic-interface-conformance.cpp45
-rw-r--r--tools/slang-unit-test/unit-test-get-target-code.cpp16
-rw-r--r--tools/slang-unit-test/unit-test-image-format-reflection.cpp30
-rw-r--r--tools/slang-unit-test/unit-test-io.cpp5
-rw-r--r--tools/slang-unit-test/unit-test-json-native.cpp36
-rw-r--r--tools/slang-unit-test/unit-test-json.cpp95
-rw-r--r--tools/slang-unit-test/unit-test-lock-file.cpp11
-rw-r--r--tools/slang-unit-test/unit-test-memory-arena.cpp47
-rw-r--r--tools/slang-unit-test/unit-test-offset-container.cpp17
-rw-r--r--tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp30
-rw-r--r--tools/slang-unit-test/unit-test-path.cpp8
-rw-r--r--tools/slang-unit-test/unit-test-persistent-cache.cpp145
-rw-r--r--tools/slang-unit-test/unit-test-process.cpp22
-rw-r--r--tools/slang-unit-test/unit-test-record-replay.cpp86
-rw-r--r--tools/slang-unit-test/unit-test-riff.cpp47
-rw-r--r--tools/slang-unit-test/unit-test-rtti.cpp32
-rw-r--r--tools/slang-unit-test/unit-test-short-list.cpp31
-rw-r--r--tools/slang-unit-test/unit-test-source-map.cpp32
-rw-r--r--tools/slang-unit-test/unit-test-string-escape.cpp115
-rw-r--r--tools/slang-unit-test/unit-test-string.cpp83
-rw-r--r--tools/slang-unit-test/unit-test-translation-unit-import.cpp35
-rw-r--r--tools/slangd/main.cpp6
-rw-r--r--tools/test-process/test-process-main.cpp31
-rw-r--r--tools/test-server/test-server-diagnostic-defs.h6
-rw-r--r--tools/test-server/test-server-diagnostics.cpp8
-rw-r--r--tools/test-server/test-server-diagnostics.h15
-rw-r--r--tools/test-server/test-server-main.cpp154
-rw-r--r--tools/unit-test/slang-unit-test.cpp22
-rw-r--r--tools/unit-test/slang-unit-test.h58
-rw-r--r--tools/vk-pipeline-create/main.cpp46
401 files changed, 26669 insertions, 23169 deletions
diff --git a/tools/gfx-unit-test/buffer-barrier-test.cpp b/tools/gfx-unit-test/buffer-barrier-test.cpp
index 007a0d180..80723d2e4 100644
--- a/tools/gfx-unit-test/buffer-barrier-test.cpp
+++ b/tools/gfx-unit-test/buffer-barrier-test.cpp
@@ -1,159 +1,179 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- struct Shader
- {
- ComPtr<IShaderProgram> program;
- slang::ProgramLayout* reflection = nullptr;
- ComputePipelineStateDesc pipelineDesc = {};
- ComPtr<gfx::IPipelineState> pipelineState;
- };
+struct Shader
+{
+ ComPtr<IShaderProgram> program;
+ slang::ProgramLayout* reflection = nullptr;
+ ComputePipelineStateDesc pipelineDesc = {};
+ ComPtr<gfx::IPipelineState> pipelineState;
+};
- struct Buffer
- {
- IBufferResource::Desc desc;
- ComPtr<IBufferResource> buffer;
- ComPtr<IResourceView> view;
- };
+struct Buffer
+{
+ IBufferResource::Desc desc;
+ ComPtr<IBufferResource> buffer;
+ ComPtr<IResourceView> view;
+};
+
+void createFloatBuffer(
+ IDevice* device,
+ Buffer& outBuffer,
+ bool unorderedAccess,
+ float* initialData,
+ size_t elementCount)
+{
+ outBuffer = {};
+ IBufferResource::Desc& bufferDesc = outBuffer.desc;
+ bufferDesc.sizeInBytes = elementCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.defaultState =
+ unorderedAccess ? ResourceState::UnorderedAccess : ResourceState::ShaderResource;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ if (unorderedAccess)
+ bufferDesc.allowedStates.add(ResourceState::UnorderedAccess);
+
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, outBuffer.buffer.writeRef()));
+
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = unorderedAccess ? IResourceView::Type::UnorderedAccess
+ : IResourceView::Type::ShaderResource;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(outBuffer.buffer, nullptr, viewDesc, outBuffer.view.writeRef()));
+}
- void createFloatBuffer(IDevice* device, Buffer& outBuffer, bool unorderedAccess, float* initialData, size_t elementCount)
+void barrierTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ Shader programA;
+ Shader programB;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ programA.program,
+ "buffer-barrier-test",
+ "computeA",
+ programA.reflection));
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ programB.program,
+ "buffer-barrier-test",
+ "computeB",
+ programB.reflection));
+ programA.pipelineDesc.program = programA.program.get();
+ programB.pipelineDesc.program = programB.program.get();
+ GFX_CHECK_CALL_ABORT(device->createComputePipelineState(
+ programA.pipelineDesc,
+ programA.pipelineState.writeRef()));
+ GFX_CHECK_CALL_ABORT(device->createComputePipelineState(
+ programB.pipelineDesc,
+ programB.pipelineState.writeRef()));
+
+ float initialData[] = {1.0f, 2.0f, 3.0f, 4.0f};
+ Buffer inputBuffer;
+ createFloatBuffer(device, inputBuffer, false, initialData, 4);
+
+ Buffer intermediateBuffer;
+ createFloatBuffer(device, intermediateBuffer, true, nullptr, 4);
+
+ Buffer outputBuffer;
+ createFloatBuffer(device, outputBuffer, true, nullptr, 4);
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- outBuffer = {};
- IBufferResource::Desc& bufferDesc = outBuffer.desc;
- bufferDesc.sizeInBytes = elementCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.defaultState = unorderedAccess ? ResourceState::UnorderedAccess : ResourceState::ShaderResource;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- if (unorderedAccess) bufferDesc.allowedStates.add(ResourceState::UnorderedAccess);
-
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- outBuffer.buffer.writeRef()));
-
- IResourceView::Desc viewDesc = {};
- viewDesc.type = unorderedAccess ? IResourceView::Type::UnorderedAccess : IResourceView::Type::ShaderResource;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(device->createBufferView(
- outBuffer.buffer, nullptr, viewDesc, outBuffer.view.writeRef()));
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+ auto resourceEncoder = commandBuffer->encodeResourceCommands();
+
+ // Write inputBuffer data to intermediateBuffer
+ auto rootObjectA = encoder->bindPipeline(programA.pipelineState);
+ ShaderCursor entryPointCursorA(rootObjectA->getEntryPoint(0));
+ entryPointCursorA.getPath("inBuffer").setResource(inputBuffer.view);
+ entryPointCursorA.getPath("outBuffer").setResource(intermediateBuffer.view);
+
+ encoder->dispatchCompute(1, 1, 1);
+
+ // Insert barrier to ensure writes to intermediateBuffer are complete before the next shader
+ // starts executing
+ auto bufferPtr = intermediateBuffer.buffer.get();
+ resourceEncoder->bufferBarrier(
+ 1,
+ &bufferPtr,
+ ResourceState::UnorderedAccess,
+ ResourceState::ShaderResource);
+ resourceEncoder->endEncoding();
+
+ // Write intermediateBuffer to outputBuffer
+ auto rootObjectB = encoder->bindPipeline(programB.pipelineState);
+ ShaderCursor entryPointCursorB(rootObjectB->getEntryPoint(0));
+ entryPointCursorB.getPath("inBuffer").setResource(intermediateBuffer.view);
+ entryPointCursorB.getPath("outBuffer").setResource(outputBuffer.view);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- void barrierTestImpl(IDevice* device, UnitTestContext* context)
+ compareComputeResult(
+ device,
+ outputBuffer.buffer,
+ Slang::makeArray<float>(11.0f, 12.0f, 13.0f, 14.0f));
+}
+
+void barrierTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+{
+ if ((api & context->enabledApis) == 0)
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- Shader programA;
- Shader programB;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, programA.program, "buffer-barrier-test", "computeA", programA.reflection));
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, programB.program, "buffer-barrier-test", "computeB", programB.reflection));
- programA.pipelineDesc.program = programA.program.get();
- programB.pipelineDesc.program = programB.program.get();
- GFX_CHECK_CALL_ABORT(device->createComputePipelineState(programA.pipelineDesc, programA.pipelineState.writeRef()));
- GFX_CHECK_CALL_ABORT(device->createComputePipelineState(programB.pipelineDesc, programB.pipelineState.writeRef()));
-
- float initialData[] = { 1.0f, 2.0f, 3.0f, 4.0f };
- Buffer inputBuffer;
- createFloatBuffer(device, inputBuffer, false, initialData, 4);
-
- Buffer intermediateBuffer;
- createFloatBuffer(device, intermediateBuffer, true, nullptr, 4);
-
- Buffer outputBuffer;
- createFloatBuffer(device, outputBuffer, true, nullptr, 4);
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
- auto resourceEncoder = commandBuffer->encodeResourceCommands();
-
- // Write inputBuffer data to intermediateBuffer
- auto rootObjectA = encoder->bindPipeline(programA.pipelineState);
- ShaderCursor entryPointCursorA(rootObjectA->getEntryPoint(0));
- entryPointCursorA.getPath("inBuffer").setResource(inputBuffer.view);
- entryPointCursorA.getPath("outBuffer").setResource(intermediateBuffer.view);
-
- encoder->dispatchCompute(1, 1, 1);
-
- // Insert barrier to ensure writes to intermediateBuffer are complete before the next shader starts executing
- auto bufferPtr = intermediateBuffer.buffer.get();
- resourceEncoder->bufferBarrier(1, &bufferPtr, ResourceState::UnorderedAccess, ResourceState::ShaderResource);
- resourceEncoder->endEncoding();
-
- // Write intermediateBuffer to outputBuffer
- auto rootObjectB = encoder->bindPipeline(programB.pipelineState);
- ShaderCursor entryPointCursorB(rootObjectB->getEntryPoint(0));
- entryPointCursorB.getPath("inBuffer").setResource(intermediateBuffer.view);
- entryPointCursorB.getPath("outBuffer").setResource(outputBuffer.view);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- outputBuffer.buffer,
- Slang::makeArray<float>(11.0f, 12.0f, 13.0f, 14.0f));
+ SLANG_IGNORE_TEST
}
-
- void barrierTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+ Slang::ComPtr<IDevice> device;
+ IDevice::Desc deviceDesc = {};
+ switch (api)
{
- if ((api & context->enabledApis) == 0)
- {
- SLANG_IGNORE_TEST
- }
- Slang::ComPtr<IDevice> device;
- IDevice::Desc deviceDesc = {};
- switch (api)
- {
- case Slang::RenderApiFlag::D3D12:
- deviceDesc.deviceType = gfx::DeviceType::DirectX12;
- break;
- case Slang::RenderApiFlag::Vulkan:
- deviceDesc.deviceType = gfx::DeviceType::Vulkan;
- break;
- default:
- SLANG_IGNORE_TEST
- }
- deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
- const char* searchPaths[] = { "", "../../tools/gfx-unit-test", "tools/gfx-unit-test" };
- deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
- deviceDesc.slang.searchPaths = searchPaths;
- auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
- if (SLANG_FAILED(createDeviceResult))
- {
- SLANG_IGNORE_TEST
- }
-
- barrierTestImpl(device, context);
+ case Slang::RenderApiFlag::D3D12: deviceDesc.deviceType = gfx::DeviceType::DirectX12; break;
+ case Slang::RenderApiFlag::Vulkan: deviceDesc.deviceType = gfx::DeviceType::Vulkan; break;
+ default: SLANG_IGNORE_TEST
}
-
- SLANG_UNIT_TEST(bufferBarrierVulkan)
+ deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
+ const char* searchPaths[] = {"", "../../tools/gfx-unit-test", "tools/gfx-unit-test"};
+ deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
+ deviceDesc.slang.searchPaths = searchPaths;
+ auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
+ if (SLANG_FAILED(createDeviceResult))
{
- barrierTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ SLANG_IGNORE_TEST
}
+ barrierTestImpl(device, context);
}
+
+SLANG_UNIT_TEST(bufferBarrierVulkan)
+{
+ barrierTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/clear-texture-test.cpp b/tools/gfx-unit-test/clear-texture-test.cpp
index 4ad82f313..ed9d12f0d 100644
--- a/tools/gfx-unit-test/clear-texture-test.cpp
+++ b/tools/gfx-unit-test/clear-texture-test.cpp
@@ -1,89 +1,92 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
using namespace gfx;
namespace gfx_test
{
- void clearTextureTestImpl(IDevice* device, UnitTestContext* context)
- {
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+void clearTextureTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
- ITextureResource::Desc srcTexDesc = {};
- srcTexDesc.type = IResource::Type::Texture2D;
- srcTexDesc.numMipLevels = 1;
- srcTexDesc.arraySize = 1;
- srcTexDesc.size.width = 4;
- srcTexDesc.size.height = 4;
- srcTexDesc.size.depth = 1;
- srcTexDesc.defaultState = ResourceState::RenderTarget;
- srcTexDesc.allowedStates = ResourceStateSet(
- ResourceState::RenderTarget,
- ResourceState::CopySource,
- ResourceState::CopyDestination);
- srcTexDesc.format = Format::R32G32B32A32_FLOAT;
+ ITextureResource::Desc srcTexDesc = {};
+ srcTexDesc.type = IResource::Type::Texture2D;
+ srcTexDesc.numMipLevels = 1;
+ srcTexDesc.arraySize = 1;
+ srcTexDesc.size.width = 4;
+ srcTexDesc.size.height = 4;
+ srcTexDesc.size.depth = 1;
+ srcTexDesc.defaultState = ResourceState::RenderTarget;
+ srcTexDesc.allowedStates = ResourceStateSet(
+ ResourceState::RenderTarget,
+ ResourceState::CopySource,
+ ResourceState::CopyDestination);
+ srcTexDesc.format = Format::R32G32B32A32_FLOAT;
- Slang::ComPtr<ITextureResource> srcTexture;
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- srcTexDesc, nullptr, srcTexture.writeRef()));
+ Slang::ComPtr<ITextureResource> srcTexture;
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(srcTexDesc, nullptr, srcTexture.writeRef()));
- Slang::ComPtr<IResourceView> rtv;
- IResourceView::Desc rtvDesc = {};
- rtvDesc.type = IResourceView::Type::RenderTarget;
- rtvDesc.format = Format::R32G32B32A32_FLOAT;
- rtvDesc.renderTarget.shape = IResource::Type::Texture2D;
- rtvDesc.subresourceRange.layerCount = 1;
- rtvDesc.subresourceRange.mipLevelCount = 1;
- rtv = device->createTextureView(srcTexture, rtvDesc);
+ Slang::ComPtr<IResourceView> rtv;
+ IResourceView::Desc rtvDesc = {};
+ rtvDesc.type = IResourceView::Type::RenderTarget;
+ rtvDesc.format = Format::R32G32B32A32_FLOAT;
+ rtvDesc.renderTarget.shape = IResource::Type::Texture2D;
+ rtvDesc.subresourceRange.layerCount = 1;
+ rtvDesc.subresourceRange.mipLevelCount = 1;
+ rtv = device->createTextureView(srcTexture, rtvDesc);
- {
- ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
- auto queue = device->createCommandQueue(queueDesc);
+ {
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto resourceEncoder = commandBuffer->encodeResourceCommands();
- ClearValue clearValue = {};
- clearValue.color.floatValues[0] = 0.5f;
- clearValue.color.floatValues[1] = 1.0f;
- clearValue.color.floatValues[2] = 0.2f;
- clearValue.color.floatValues[3] = 0.1f;
- resourceEncoder->clearResourceView(rtv, &clearValue, ClearResourceViewFlags::FloatClearValues);
- resourceEncoder->textureBarrier(
- srcTexture, ResourceState::RenderTarget, ResourceState::CopySource);
- resourceEncoder->endEncoding();
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto resourceEncoder = commandBuffer->encodeResourceCommands();
+ ClearValue clearValue = {};
+ clearValue.color.floatValues[0] = 0.5f;
+ clearValue.color.floatValues[1] = 1.0f;
+ clearValue.color.floatValues[2] = 0.2f;
+ clearValue.color.floatValues[3] = 0.1f;
+ resourceEncoder->clearResourceView(
+ rtv,
+ &clearValue,
+ ClearResourceViewFlags::FloatClearValues);
+ resourceEncoder->textureBarrier(
+ srcTexture,
+ ResourceState::RenderTarget,
+ ResourceState::CopySource);
+ resourceEncoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
+ queue->waitOnHost();
- Slang::ComPtr<ISlangBlob> blob;
- size_t rowPitch, pixelSize;
- device->readTextureResource(
- srcTexture,
- ResourceState::CopySource,
- blob.writeRef(),
- &rowPitch,
- &pixelSize);
- float* data = (float*)blob->getBufferPointer();
- for (int i = 0; i < 4; i++)
- {
- SLANG_CHECK(data[i] == clearValue.color.floatValues[i]);
- }
+ Slang::ComPtr<ISlangBlob> blob;
+ size_t rowPitch, pixelSize;
+ device->readTextureResource(
+ srcTexture,
+ ResourceState::CopySource,
+ blob.writeRef(),
+ &rowPitch,
+ &pixelSize);
+ float* data = (float*)blob->getBufferPointer();
+ for (int i = 0; i < 4; i++)
+ {
+ SLANG_CHECK(data[i] == clearValue.color.floatValues[i]);
}
}
+}
- SLANG_UNIT_TEST(clearTextureTestVulkan)
- {
- runTestImpl(clearTextureTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(clearTextureTestVulkan)
+{
+ runTestImpl(clearTextureTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/compute-smoke.cpp b/tools/gfx-unit-test/compute-smoke.cpp
index 5e14a2e00..da8357591 100644
--- a/tools/gfx-unit-test/compute-smoke.cpp
+++ b/tools/gfx-unit-test/compute-smoke.cpp
@@ -1,115 +1,115 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void computeSmokeTestImpl(IDevice* device, UnitTestContext* context)
+void computeSmokeTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(
+ loadComputeProgram(device, shaderProgram, "compute-smoke", "computeMain", slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 1.0f, 2.0f, 3.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "compute-smoke", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 1.0f, 2.0f, 3.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- slang::TypeReflection* addTransformerType =
- slangReflection->findTypeByName("AddTransformer");
-
- // Now we can use this type to create a shader object that can be bound to the root object.
- ComPtr<IShaderObject> transformer;
- GFX_CHECK_CALL_ABORT(device->createShaderObject(
- addTransformerType, ShaderObjectContainerType::None, transformer.writeRef()));
- // Set the `c` field of the `AddTransformer`.
- float c = 1.0f;
- ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
-
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- // Bind the previously created transformer object to root object.
- entryPointCursor.getPath("transformer").setObject(transformer);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(11.0f, 12.0f, 13.0f, 14.0f));
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ slang::TypeReflection* addTransformerType =
+ slangReflection->findTypeByName("AddTransformer");
+
+ // Now we can use this type to create a shader object that can be bound to the root object.
+ ComPtr<IShaderObject> transformer;
+ GFX_CHECK_CALL_ABORT(device->createShaderObject(
+ addTransformerType,
+ ShaderObjectContainerType::None,
+ transformer.writeRef()));
+ // Set the `c` field of the `AddTransformer`.
+ float c = 1.0f;
+ ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
+
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ // Bind the previously created transformer object to root object.
+ entryPointCursor.getPath("transformer").setObject(transformer);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(computeSmokeD3D12)
- {
- runTestImpl(computeSmokeTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ compareComputeResult(
+ device,
+ numbersBuffer,
+ Slang::makeArray<float>(11.0f, 12.0f, 13.0f, 14.0f));
+}
- SLANG_UNIT_TEST(computeSmokeD3D11)
- {
- runTestImpl(computeSmokeTestImpl, unitTestContext, Slang::RenderApiFlag::D3D11);
- }
+SLANG_UNIT_TEST(computeSmokeD3D12)
+{
+ runTestImpl(computeSmokeTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
- SLANG_UNIT_TEST(computeSmokeVulkan)
- {
- runTestImpl(computeSmokeTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(computeSmokeD3D11)
+{
+ runTestImpl(computeSmokeTestImpl, unitTestContext, Slang::RenderApiFlag::D3D11);
+}
+SLANG_UNIT_TEST(computeSmokeVulkan)
+{
+ runTestImpl(computeSmokeTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/compute-trivial.cpp b/tools/gfx-unit-test/compute-trivial.cpp
index 5674dd1a7..341593d04 100644
--- a/tools/gfx-unit-test/compute-trivial.cpp
+++ b/tools/gfx-unit-test/compute-trivial.cpp
@@ -1,99 +1,98 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void computeTrivialTestImpl(IDevice* device, UnitTestContext* context)
+void computeTrivialTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "compute-trivial",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 1.0f, 2.0f, 3.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "compute-trivial", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 1.0f, 2.0f, 3.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- // Bind buffer view to the entry point.
- ShaderCursor(rootObject).getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(1.0f, 2.0f, 3.0f, 4.0f));
- }
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- SLANG_UNIT_TEST(computeTrivialD3D12)
- {
- runTestImpl(computeTrivialTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- SLANG_UNIT_TEST(computeTrivialD3D11)
- {
- runTestImpl(computeTrivialTestImpl, unitTestContext, Slang::RenderApiFlag::D3D11);
- }
+ auto rootObject = encoder->bindPipeline(pipelineState);
- SLANG_UNIT_TEST(computeTrivialVulkan)
- {
- runTestImpl(computeTrivialTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ // Bind buffer view to the entry point.
+ ShaderCursor(rootObject).getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(1.0f, 2.0f, 3.0f, 4.0f));
+}
+
+SLANG_UNIT_TEST(computeTrivialD3D12)
+{
+ runTestImpl(computeTrivialTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(computeTrivialD3D11)
+{
+ runTestImpl(computeTrivialTestImpl, unitTestContext, Slang::RenderApiFlag::D3D11);
+}
+
+SLANG_UNIT_TEST(computeTrivialVulkan)
+{
+ runTestImpl(computeTrivialTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/copy-texture-tests.cpp b/tools/gfx-unit-test/copy-texture-tests.cpp
index 68ca193ae..babe0bcf1 100644
--- a/tools/gfx-unit-test/copy-texture-tests.cpp
+++ b/tools/gfx-unit-test/copy-texture-tests.cpp
@@ -1,10 +1,9 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
-#include "gfx-test-util.h"
#include "gfx-test-texture-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "gfx-test-util.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
@@ -15,810 +14,943 @@ using namespace gfx;
namespace gfx_test
{
- struct TextureToTextureCopyInfo
- {
- SubresourceRange srcSubresource;
- SubresourceRange dstSubresource;
- ITextureResource::Extents extent;
- ITextureResource::Offset3D srcOffset;
- ITextureResource::Offset3D dstOffset;
- };
-
- struct TextureToBufferCopyInfo
- {
- SubresourceRange srcSubresource;
- ITextureResource::Extents extent;
- ITextureResource::Offset3D textureOffset;
- Offset bufferOffset;
- Offset bufferSize;
- };
-
- struct BaseCopyTextureTest
+struct TextureToTextureCopyInfo
+{
+ SubresourceRange srcSubresource;
+ SubresourceRange dstSubresource;
+ ITextureResource::Extents extent;
+ ITextureResource::Offset3D srcOffset;
+ ITextureResource::Offset3D dstOffset;
+};
+
+struct TextureToBufferCopyInfo
+{
+ SubresourceRange srcSubresource;
+ ITextureResource::Extents extent;
+ ITextureResource::Offset3D textureOffset;
+ Offset bufferOffset;
+ Offset bufferSize;
+};
+
+struct BaseCopyTextureTest
+{
+ IDevice* device;
+ UnitTestContext* context;
+
+ Size alignedRowStride;
+
+ RefPtr<TextureInfo> srcTextureInfo;
+ RefPtr<TextureInfo> dstTextureInfo;
+ TextureToTextureCopyInfo texCopyInfo;
+ TextureToBufferCopyInfo bufferCopyInfo;
+
+ ComPtr<ITextureResource> srcTexture;
+ ComPtr<ITextureResource> dstTexture;
+ ComPtr<IBufferResource> resultsBuffer;
+
+ RefPtr<ValidationTextureFormatBase> validationFormat;
+
+ void init(
+ IDevice* device,
+ UnitTestContext* context,
+ Format format,
+ RefPtr<ValidationTextureFormatBase> validationFormat,
+ ITextureResource::Type type)
{
- IDevice* device;
- UnitTestContext* context;
-
- Size alignedRowStride;
-
- RefPtr<TextureInfo> srcTextureInfo;
- RefPtr<TextureInfo> dstTextureInfo;
- TextureToTextureCopyInfo texCopyInfo;
- TextureToBufferCopyInfo bufferCopyInfo;
-
- ComPtr<ITextureResource> srcTexture;
- ComPtr<ITextureResource> dstTexture;
- ComPtr<IBufferResource> resultsBuffer;
-
- RefPtr<ValidationTextureFormatBase> validationFormat;
-
- void init(
- IDevice* device,
- UnitTestContext* context,
- Format format,
- RefPtr<ValidationTextureFormatBase> validationFormat,
- ITextureResource::Type type)
- {
- this->device = device;
- this->context = context;
- this->validationFormat = validationFormat;
+ this->device = device;
+ this->context = context;
+ this->validationFormat = validationFormat;
- this->srcTextureInfo = new TextureInfo();
- this->srcTextureInfo->format = format;
- this->srcTextureInfo->textureType = type;
+ this->srcTextureInfo = new TextureInfo();
+ this->srcTextureInfo->format = format;
+ this->srcTextureInfo->textureType = type;
- this->dstTextureInfo = new TextureInfo();
- this->dstTextureInfo->format = format;
- this->dstTextureInfo->textureType = type;
- }
+ this->dstTextureInfo = new TextureInfo();
+ this->dstTextureInfo->format = format;
+ this->dstTextureInfo->textureType = type;
+ }
- void createRequiredResources()
+ void createRequiredResources()
+ {
+ ITextureResource::Desc srcTexDesc = {};
+ srcTexDesc.type = srcTextureInfo->textureType;
+ srcTexDesc.numMipLevels = srcTextureInfo->mipLevelCount;
+ srcTexDesc.arraySize = srcTextureInfo->arrayLayerCount;
+ srcTexDesc.size = srcTextureInfo->extents;
+ srcTexDesc.defaultState = ResourceState::ShaderResource;
+ srcTexDesc.allowedStates =
+ ResourceStateSet(ResourceState::ShaderResource, ResourceState::CopySource);
+ if (srcTextureInfo->format == Format::D32_FLOAT ||
+ srcTextureInfo->format == Format::D16_UNORM)
{
- ITextureResource::Desc srcTexDesc = {};
- srcTexDesc.type = srcTextureInfo->textureType;
- srcTexDesc.numMipLevels = srcTextureInfo->mipLevelCount;
- srcTexDesc.arraySize = srcTextureInfo->arrayLayerCount;
- srcTexDesc.size = srcTextureInfo->extents;
- srcTexDesc.defaultState = ResourceState::ShaderResource;
- srcTexDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::CopySource);
- if (srcTextureInfo->format == Format::D32_FLOAT || srcTextureInfo->format == Format::D16_UNORM)
- {
- srcTexDesc.allowedStates.add(ResourceState::DepthWrite);
- srcTexDesc.allowedStates.add(ResourceState::DepthRead);
- }
- srcTexDesc.format = srcTextureInfo->format;
-
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- srcTexDesc,
- srcTextureInfo->subresourceDatas.getBuffer(),
- srcTexture.writeRef()));
-
- ITextureResource::Desc dstTexDesc = {};
- dstTexDesc.type = dstTextureInfo->textureType;
- dstTexDesc.numMipLevels = dstTextureInfo->mipLevelCount;
- dstTexDesc.arraySize = dstTextureInfo->arrayLayerCount;
- dstTexDesc.size = dstTextureInfo->extents;
- dstTexDesc.defaultState = ResourceState::CopyDestination;
- dstTexDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- if (dstTextureInfo->format == Format::D32_FLOAT || dstTextureInfo->format == Format::D16_UNORM)
- {
- dstTexDesc.allowedStates.add(ResourceState::DepthWrite);
- dstTexDesc.allowedStates.add(ResourceState::DepthRead);
- }
- dstTexDesc.format = dstTextureInfo->format;
-
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- dstTexDesc,
- dstTextureInfo->subresourceDatas.getBuffer(),
- dstTexture.writeRef()));
-
- auto bufferCopyExtents = bufferCopyInfo.extent;
- auto texelSize = getTexelSize(dstTextureInfo->format);
- size_t alignment;
- device->getTextureRowAlignment(&alignment);
- alignedRowStride = (bufferCopyExtents.width * texelSize + alignment - 1) & ~(alignment - 1);
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = bufferCopyExtents.height * bufferCopyExtents.depth * alignedRowStride;
- bufferDesc.format = Format::Unknown;
- bufferDesc.elementSize = 0;
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::CopyDestination;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- nullptr,
- resultsBuffer.writeRef()));
-
- bufferCopyInfo.bufferSize = bufferDesc.sizeInBytes;
+ srcTexDesc.allowedStates.add(ResourceState::DepthWrite);
+ srcTexDesc.allowedStates.add(ResourceState::DepthRead);
}
-
- void submitGPUWork()
+ srcTexDesc.format = srcTextureInfo->format;
+
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(
+ srcTexDesc,
+ srcTextureInfo->subresourceDatas.getBuffer(),
+ srcTexture.writeRef()));
+
+ ITextureResource::Desc dstTexDesc = {};
+ dstTexDesc.type = dstTextureInfo->textureType;
+ dstTexDesc.numMipLevels = dstTextureInfo->mipLevelCount;
+ dstTexDesc.arraySize = dstTextureInfo->arrayLayerCount;
+ dstTexDesc.size = dstTextureInfo->extents;
+ dstTexDesc.defaultState = ResourceState::CopyDestination;
+ dstTexDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ if (dstTextureInfo->format == Format::D32_FLOAT ||
+ dstTextureInfo->format == Format::D16_UNORM)
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeResourceCommands();
-
- encoder->textureSubresourceBarrier(srcTexture, texCopyInfo.srcSubresource, ResourceState::ShaderResource, ResourceState::CopySource);
- encoder->copyTexture(
- dstTexture,
- ResourceState::CopyDestination,
- texCopyInfo.dstSubresource,
- texCopyInfo.dstOffset,
- srcTexture,
- ResourceState::CopySource,
- texCopyInfo.srcSubresource,
- texCopyInfo.srcOffset,
- texCopyInfo.extent);
-
- encoder->textureSubresourceBarrier(dstTexture, bufferCopyInfo.srcSubresource, ResourceState::CopyDestination, ResourceState::CopySource);
- encoder->copyTextureToBuffer(
- resultsBuffer,
- bufferCopyInfo.bufferOffset,
- bufferCopyInfo.bufferSize,
- alignedRowStride,
- dstTexture,
- ResourceState::CopySource,
- bufferCopyInfo.srcSubresource,
- bufferCopyInfo.textureOffset,
- bufferCopyInfo.extent);
-
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
+ dstTexDesc.allowedStates.add(ResourceState::DepthWrite);
+ dstTexDesc.allowedStates.add(ResourceState::DepthRead);
}
+ dstTexDesc.format = dstTextureInfo->format;
+
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(
+ dstTexDesc,
+ dstTextureInfo->subresourceDatas.getBuffer(),
+ dstTexture.writeRef()));
+
+ auto bufferCopyExtents = bufferCopyInfo.extent;
+ auto texelSize = getTexelSize(dstTextureInfo->format);
+ size_t alignment;
+ device->getTextureRowAlignment(&alignment);
+ alignedRowStride = (bufferCopyExtents.width * texelSize + alignment - 1) & ~(alignment - 1);
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes =
+ bufferCopyExtents.height * bufferCopyExtents.depth * alignedRowStride;
+ bufferDesc.format = Format::Unknown;
+ bufferDesc.elementSize = 0;
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::CopyDestination;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, nullptr, resultsBuffer.writeRef()));
+
+ bufferCopyInfo.bufferSize = bufferDesc.sizeInBytes;
+ }
- bool isWithinCopyBounds(GfxIndex x, GfxIndex y, GfxIndex z)
- {
- auto copyExtents = texCopyInfo.extent;
- auto copyOffset = texCopyInfo.dstOffset;
-
- auto xLowerBound = copyOffset.x;
- auto xUpperBound = copyOffset.x + copyExtents.width;
- auto yLowerBound = copyOffset.y;
- auto yUpperBound = copyOffset.y + copyExtents.height;
- auto zLowerBound = copyOffset.z;
- auto zUpperBound = copyOffset.z + copyExtents.depth;
-
- if (x < xLowerBound || x >= xUpperBound || y < yLowerBound || y >= yUpperBound || z < zLowerBound || z >= zUpperBound)
- return false;
- else
- return true;
- }
+ void submitGPUWork()
+ {
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeResourceCommands();
+
+ encoder->textureSubresourceBarrier(
+ srcTexture,
+ texCopyInfo.srcSubresource,
+ ResourceState::ShaderResource,
+ ResourceState::CopySource);
+ encoder->copyTexture(
+ dstTexture,
+ ResourceState::CopyDestination,
+ texCopyInfo.dstSubresource,
+ texCopyInfo.dstOffset,
+ srcTexture,
+ ResourceState::CopySource,
+ texCopyInfo.srcSubresource,
+ texCopyInfo.srcOffset,
+ texCopyInfo.extent);
+
+ encoder->textureSubresourceBarrier(
+ dstTexture,
+ bufferCopyInfo.srcSubresource,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ encoder->copyTextureToBuffer(
+ resultsBuffer,
+ bufferCopyInfo.bufferOffset,
+ bufferCopyInfo.bufferSize,
+ alignedRowStride,
+ dstTexture,
+ ResourceState::CopySource,
+ bufferCopyInfo.srcSubresource,
+ bufferCopyInfo.textureOffset,
+ bufferCopyInfo.extent);
+
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- void validateTestResults(
- ValidationTextureData actual,
- ValidationTextureData expectedCopied,
- ValidationTextureData expectedOriginal)
- {
- auto actualExtents = actual.extents;
- auto copyExtent = texCopyInfo.extent;
- auto srcTexOffset = texCopyInfo.srcOffset;
- auto dstTexOffset = texCopyInfo.dstOffset;
+ bool isWithinCopyBounds(GfxIndex x, GfxIndex y, GfxIndex z)
+ {
+ auto copyExtents = texCopyInfo.extent;
+ auto copyOffset = texCopyInfo.dstOffset;
+
+ auto xLowerBound = copyOffset.x;
+ auto xUpperBound = copyOffset.x + copyExtents.width;
+ auto yLowerBound = copyOffset.y;
+ auto yUpperBound = copyOffset.y + copyExtents.height;
+ auto zLowerBound = copyOffset.z;
+ auto zUpperBound = copyOffset.z + copyExtents.depth;
+
+ if (x < xLowerBound || x >= xUpperBound || y < yLowerBound || y >= yUpperBound ||
+ z < zLowerBound || z >= zUpperBound)
+ return false;
+ else
+ return true;
+ }
+
+ void validateTestResults(
+ ValidationTextureData actual,
+ ValidationTextureData expectedCopied,
+ ValidationTextureData expectedOriginal)
+ {
+ auto actualExtents = actual.extents;
+ auto copyExtent = texCopyInfo.extent;
+ auto srcTexOffset = texCopyInfo.srcOffset;
+ auto dstTexOffset = texCopyInfo.dstOffset;
- for (GfxIndex x = 0; x < actualExtents.width; ++x)
+ for (GfxIndex x = 0; x < actualExtents.width; ++x)
+ {
+ for (GfxIndex y = 0; y < actualExtents.height; ++y)
{
- for (GfxIndex y = 0; y < actualExtents.height; ++y)
+ for (GfxIndex z = 0; z < actualExtents.depth; ++z)
{
- for (GfxIndex z = 0; z < actualExtents.depth; ++z)
+ auto actualBlock = actual.getBlockAt(x, y, z);
+ if (isWithinCopyBounds(x, y, z))
+ {
+ // Block is located within the bounds of the source texture
+ auto xSource = x + srcTexOffset.x - dstTexOffset.x;
+ auto ySource = y + srcTexOffset.y - dstTexOffset.y;
+ auto zSource = z + srcTexOffset.z - dstTexOffset.z;
+ auto expectedBlock = expectedCopied.getBlockAt(xSource, ySource, zSource);
+ validationFormat->validateBlocksEqual(actualBlock, expectedBlock);
+ }
+ else
{
- auto actualBlock = actual.getBlockAt(x, y, z);
- if (isWithinCopyBounds(x, y, z))
- {
- // Block is located within the bounds of the source texture
- auto xSource = x + srcTexOffset.x - dstTexOffset.x;
- auto ySource = y + srcTexOffset.y - dstTexOffset.y;
- auto zSource = z + srcTexOffset.z - dstTexOffset.z;
- auto expectedBlock = expectedCopied.getBlockAt(xSource, ySource, zSource);
- validationFormat->validateBlocksEqual(actualBlock, expectedBlock);
- }
- else
- {
- // Block is located outside the bounds of the source texture and should be compared
- // against known expected values for the destination texture.
- auto expectedBlock = expectedOriginal.getBlockAt(x, y, z);
- validationFormat->validateBlocksEqual(actualBlock, expectedBlock);
- }
+ // Block is located outside the bounds of the source texture and should be
+ // compared against known expected values for the destination texture.
+ auto expectedBlock = expectedOriginal.getBlockAt(x, y, z);
+ validationFormat->validateBlocksEqual(actualBlock, expectedBlock);
}
}
}
}
+ }
- void checkTestResults(ITextureResource::Extents srcMipExtent, const void* expectedCopiedData, const void* expectedOriginalData)
+ void checkTestResults(
+ ITextureResource::Extents srcMipExtent,
+ const void* expectedCopiedData,
+ const void* expectedOriginalData)
+ {
+ ComPtr<ISlangBlob> resultBlob;
+ GFX_CHECK_CALL_ABORT(device->readBufferResource(
+ resultsBuffer,
+ 0,
+ bufferCopyInfo.bufferSize,
+ resultBlob.writeRef()));
+ auto results = resultBlob->getBufferPointer();
+
+ ValidationTextureData actual;
+ actual.extents = bufferCopyInfo.extent;
+ actual.textureData = results;
+ actual.strides.x = getTexelSize(dstTextureInfo->format);
+ actual.strides.y = alignedRowStride;
+ actual.strides.z = actual.extents.height * actual.strides.y;
+
+ ValidationTextureData expectedCopied;
+ expectedCopied.extents = srcMipExtent;
+ expectedCopied.textureData = expectedCopiedData;
+ expectedCopied.strides.x = getTexelSize(srcTextureInfo->format);
+ expectedCopied.strides.y = expectedCopied.extents.width * expectedCopied.strides.x;
+ expectedCopied.strides.z = expectedCopied.extents.height * expectedCopied.strides.y;
+
+ ValidationTextureData expectedOriginal;
+ if (expectedOriginalData)
{
- ComPtr<ISlangBlob> resultBlob;
- GFX_CHECK_CALL_ABORT(device->readBufferResource(resultsBuffer, 0, bufferCopyInfo.bufferSize, resultBlob.writeRef()));
- auto results = resultBlob->getBufferPointer();
-
- ValidationTextureData actual;
- actual.extents = bufferCopyInfo.extent;
- actual.textureData = results;
- actual.strides.x = getTexelSize(dstTextureInfo->format);
- actual.strides.y = alignedRowStride;
- actual.strides.z = actual.extents.height * actual.strides.y;
-
- ValidationTextureData expectedCopied;
- expectedCopied.extents = srcMipExtent;
- expectedCopied.textureData = expectedCopiedData;
- expectedCopied.strides.x = getTexelSize(srcTextureInfo->format);
- expectedCopied.strides.y = expectedCopied.extents.width * expectedCopied.strides.x;
- expectedCopied.strides.z = expectedCopied.extents.height * expectedCopied.strides.y;
-
- ValidationTextureData expectedOriginal;
- if (expectedOriginalData)
- {
- expectedOriginal.extents = bufferCopyInfo.extent;
- expectedOriginal.textureData = expectedOriginalData;
- expectedOriginal.strides.x = getTexelSize(dstTextureInfo->format);
- expectedOriginal.strides.y = expectedOriginal.extents.width * expectedOriginal.strides.x;
- expectedOriginal.strides.z = expectedOriginal.extents.height * expectedOriginal.strides.y;
- }
-
- validateTestResults(actual, expectedCopied, expectedOriginal);
+ expectedOriginal.extents = bufferCopyInfo.extent;
+ expectedOriginal.textureData = expectedOriginalData;
+ expectedOriginal.strides.x = getTexelSize(dstTextureInfo->format);
+ expectedOriginal.strides.y =
+ expectedOriginal.extents.width * expectedOriginal.strides.x;
+ expectedOriginal.strides.z =
+ expectedOriginal.extents.height * expectedOriginal.strides.y;
}
- };
- struct SimpleCopyTexture : BaseCopyTextureTest
+ validateTestResults(actual, expectedCopied, expectedOriginal);
+ }
+};
+
+struct SimpleCopyTexture : BaseCopyTextureTest
+{
+ void run()
{
- void run()
- {
- auto textureType = srcTextureInfo->textureType;
- auto format = srcTextureInfo->format;
-
- srcTextureInfo->extents.width = 4;
- srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
- srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- srcTextureInfo->mipLevelCount = 1;
- srcTextureInfo->arrayLayerCount = 1;
-
- dstTextureInfo = srcTextureInfo;
-
- generateTextureData(srcTextureInfo, validationFormat);
-
- SubresourceRange srcSubresource = {};
- srcSubresource.aspectMask = getTextureAspect(format);
- srcSubresource.mipLevel = 0;
- srcSubresource.mipLevelCount = 1;
- srcSubresource.baseArrayLayer = 0;
- srcSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = getTextureAspect(format);
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- texCopyInfo.srcSubresource = srcSubresource;
- texCopyInfo.dstSubresource = dstSubresource;
- texCopyInfo.extent = srcTextureInfo->extents;
- texCopyInfo.srcOffset = { 0, 0, 0 };
- texCopyInfo.dstOffset = { 0, 0, 0 };
-
- bufferCopyInfo.srcSubresource = dstSubresource;
- bufferCopyInfo.extent = dstTextureInfo->extents;
- bufferCopyInfo.textureOffset = { 0, 0, 0 };
- bufferCopyInfo.bufferOffset = 0;
-
- createRequiredResources();
- submitGPUWork();
-
- auto subresourceIndex = getSubresourceIndex(srcSubresource.mipLevel, srcTextureInfo->mipLevelCount, srcSubresource.baseArrayLayer);
- auto expectedData = srcTextureInfo->subresourceDatas[subresourceIndex];
- checkTestResults(srcTextureInfo->extents, expectedData.data, nullptr);
- }
- };
+ auto textureType = srcTextureInfo->textureType;
+ auto format = srcTextureInfo->format;
+
+ srcTextureInfo->extents.width = 4;
+ srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
+ srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ srcTextureInfo->mipLevelCount = 1;
+ srcTextureInfo->arrayLayerCount = 1;
+
+ dstTextureInfo = srcTextureInfo;
+
+ generateTextureData(srcTextureInfo, validationFormat);
+
+ SubresourceRange srcSubresource = {};
+ srcSubresource.aspectMask = getTextureAspect(format);
+ srcSubresource.mipLevel = 0;
+ srcSubresource.mipLevelCount = 1;
+ srcSubresource.baseArrayLayer = 0;
+ srcSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = getTextureAspect(format);
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ texCopyInfo.srcSubresource = srcSubresource;
+ texCopyInfo.dstSubresource = dstSubresource;
+ texCopyInfo.extent = srcTextureInfo->extents;
+ texCopyInfo.srcOffset = {0, 0, 0};
+ texCopyInfo.dstOffset = {0, 0, 0};
+
+ bufferCopyInfo.srcSubresource = dstSubresource;
+ bufferCopyInfo.extent = dstTextureInfo->extents;
+ bufferCopyInfo.textureOffset = {0, 0, 0};
+ bufferCopyInfo.bufferOffset = 0;
+
+ createRequiredResources();
+ submitGPUWork();
+
+ auto subresourceIndex = getSubresourceIndex(
+ srcSubresource.mipLevel,
+ srcTextureInfo->mipLevelCount,
+ srcSubresource.baseArrayLayer);
+ auto expectedData = srcTextureInfo->subresourceDatas[subresourceIndex];
+ checkTestResults(srcTextureInfo->extents, expectedData.data, nullptr);
+ }
+};
- struct CopyTextureSection : BaseCopyTextureTest
+struct CopyTextureSection : BaseCopyTextureTest
+{
+ void run()
{
- void run()
- {
- auto textureType = srcTextureInfo->textureType;
- auto format = srcTextureInfo->format;
-
- srcTextureInfo->extents.width = 4;
- srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
- srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- srcTextureInfo->mipLevelCount = 2;
- srcTextureInfo->arrayLayerCount = (textureType == ITextureResource::Type::Texture3D) ? 1 : 2;
-
- dstTextureInfo = srcTextureInfo;
-
- generateTextureData(srcTextureInfo, validationFormat);
-
- SubresourceRange srcSubresource = {};
- srcSubresource.aspectMask = getTextureAspect(format);
- srcSubresource.mipLevel = 0;
- srcSubresource.mipLevelCount = 1;
- srcSubresource.baseArrayLayer = (textureType == ITextureResource::Type::Texture3D) ? 0 : 1;
- srcSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = getTextureAspect(format);
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- texCopyInfo.srcSubresource = srcSubresource;
- texCopyInfo.dstSubresource = dstSubresource;
- texCopyInfo.extent = srcTextureInfo->extents;
- texCopyInfo.srcOffset = { 0, 0, 0 };
- texCopyInfo.dstOffset = { 0, 0, 0 };
-
- bufferCopyInfo.srcSubresource = dstSubresource;
- bufferCopyInfo.extent = dstTextureInfo->extents;
- bufferCopyInfo.textureOffset = { 0, 0, 0 };
- bufferCopyInfo.bufferOffset = 0;
-
- createRequiredResources();
- submitGPUWork();
-
- auto subresourceIndex = getSubresourceIndex(srcSubresource.mipLevel, srcTextureInfo->mipLevelCount, srcSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedData = srcTextureInfo->subresourceDatas[subresourceIndex];
- checkTestResults(srcTextureInfo->extents, expectedData.data, nullptr);
- }
- };
+ auto textureType = srcTextureInfo->textureType;
+ auto format = srcTextureInfo->format;
+
+ srcTextureInfo->extents.width = 4;
+ srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
+ srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ srcTextureInfo->mipLevelCount = 2;
+ srcTextureInfo->arrayLayerCount =
+ (textureType == ITextureResource::Type::Texture3D) ? 1 : 2;
+
+ dstTextureInfo = srcTextureInfo;
+
+ generateTextureData(srcTextureInfo, validationFormat);
+
+ SubresourceRange srcSubresource = {};
+ srcSubresource.aspectMask = getTextureAspect(format);
+ srcSubresource.mipLevel = 0;
+ srcSubresource.mipLevelCount = 1;
+ srcSubresource.baseArrayLayer = (textureType == ITextureResource::Type::Texture3D) ? 0 : 1;
+ srcSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = getTextureAspect(format);
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ texCopyInfo.srcSubresource = srcSubresource;
+ texCopyInfo.dstSubresource = dstSubresource;
+ texCopyInfo.extent = srcTextureInfo->extents;
+ texCopyInfo.srcOffset = {0, 0, 0};
+ texCopyInfo.dstOffset = {0, 0, 0};
+
+ bufferCopyInfo.srcSubresource = dstSubresource;
+ bufferCopyInfo.extent = dstTextureInfo->extents;
+ bufferCopyInfo.textureOffset = {0, 0, 0};
+ bufferCopyInfo.bufferOffset = 0;
+
+ createRequiredResources();
+ submitGPUWork();
+
+ auto subresourceIndex = getSubresourceIndex(
+ srcSubresource.mipLevel,
+ srcTextureInfo->mipLevelCount,
+ srcSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedData =
+ srcTextureInfo->subresourceDatas[subresourceIndex];
+ checkTestResults(srcTextureInfo->extents, expectedData.data, nullptr);
+ }
+};
- struct LargeSrcToSmallDst : BaseCopyTextureTest
+struct LargeSrcToSmallDst : BaseCopyTextureTest
+{
+ void run()
{
- void run()
- {
- auto textureType = srcTextureInfo->textureType;
- auto format = srcTextureInfo->format;
-
- srcTextureInfo->extents.width = 8;
- srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 8;
- srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- srcTextureInfo->mipLevelCount = 1;
- srcTextureInfo->arrayLayerCount = 1;
-
- generateTextureData(srcTextureInfo, validationFormat);
-
- dstTextureInfo->extents.width = 4;
- dstTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
- dstTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- dstTextureInfo->mipLevelCount = 1;
- dstTextureInfo->arrayLayerCount = 1;
-
- SubresourceRange srcSubresource = {};
- srcSubresource.aspectMask = getTextureAspect(format);
- srcSubresource.mipLevel = 0;
- srcSubresource.mipLevelCount = 1;
- srcSubresource.baseArrayLayer = 0;
- srcSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = getTextureAspect(format);
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- texCopyInfo.srcSubresource = srcSubresource;
- texCopyInfo.dstSubresource = dstSubresource;
- texCopyInfo.extent = dstTextureInfo->extents;
- texCopyInfo.srcOffset = { 0, 0, 0 };
- texCopyInfo.dstOffset = { 0, 0, 0 };
-
- bufferCopyInfo.srcSubresource = dstSubresource;
- bufferCopyInfo.extent = dstTextureInfo->extents;
- bufferCopyInfo.textureOffset = { 0, 0, 0 };
- bufferCopyInfo.bufferOffset = 0;
-
- createRequiredResources();
- submitGPUWork();
-
- auto subresourceIndex = getSubresourceIndex(srcSubresource.mipLevel, srcTextureInfo->mipLevelCount, srcSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedData = srcTextureInfo->subresourceDatas[subresourceIndex];
- checkTestResults(srcTextureInfo->extents, expectedData.data, nullptr);
- }
- };
+ auto textureType = srcTextureInfo->textureType;
+ auto format = srcTextureInfo->format;
+
+ srcTextureInfo->extents.width = 8;
+ srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 8;
+ srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ srcTextureInfo->mipLevelCount = 1;
+ srcTextureInfo->arrayLayerCount = 1;
+
+ generateTextureData(srcTextureInfo, validationFormat);
+
+ dstTextureInfo->extents.width = 4;
+ dstTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
+ dstTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ dstTextureInfo->mipLevelCount = 1;
+ dstTextureInfo->arrayLayerCount = 1;
+
+ SubresourceRange srcSubresource = {};
+ srcSubresource.aspectMask = getTextureAspect(format);
+ srcSubresource.mipLevel = 0;
+ srcSubresource.mipLevelCount = 1;
+ srcSubresource.baseArrayLayer = 0;
+ srcSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = getTextureAspect(format);
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ texCopyInfo.srcSubresource = srcSubresource;
+ texCopyInfo.dstSubresource = dstSubresource;
+ texCopyInfo.extent = dstTextureInfo->extents;
+ texCopyInfo.srcOffset = {0, 0, 0};
+ texCopyInfo.dstOffset = {0, 0, 0};
+
+ bufferCopyInfo.srcSubresource = dstSubresource;
+ bufferCopyInfo.extent = dstTextureInfo->extents;
+ bufferCopyInfo.textureOffset = {0, 0, 0};
+ bufferCopyInfo.bufferOffset = 0;
+
+ createRequiredResources();
+ submitGPUWork();
+
+ auto subresourceIndex = getSubresourceIndex(
+ srcSubresource.mipLevel,
+ srcTextureInfo->mipLevelCount,
+ srcSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedData =
+ srcTextureInfo->subresourceDatas[subresourceIndex];
+ checkTestResults(srcTextureInfo->extents, expectedData.data, nullptr);
+ }
+};
- struct SmallSrcToLargeDst : BaseCopyTextureTest
+struct SmallSrcToLargeDst : BaseCopyTextureTest
+{
+ void run()
{
- void run()
- {
- auto textureType = srcTextureInfo->textureType;
- auto format = srcTextureInfo->format;
-
- srcTextureInfo->extents.width = 4;
- srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
- srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- srcTextureInfo->mipLevelCount = 1;
- srcTextureInfo->arrayLayerCount = 1;
-
- generateTextureData(srcTextureInfo, validationFormat);
-
- dstTextureInfo->extents.width = 8;
- dstTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 8;
- dstTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- dstTextureInfo->mipLevelCount = 1;
- dstTextureInfo->arrayLayerCount = 1;
-
- generateTextureData(dstTextureInfo, validationFormat);
-
- SubresourceRange srcSubresource = {};
- srcSubresource.aspectMask = getTextureAspect(format);
- srcSubresource.mipLevel = 0;
- srcSubresource.mipLevelCount = 1;
- srcSubresource.baseArrayLayer = 0;
- srcSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = getTextureAspect(format);
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- texCopyInfo.srcSubresource = srcSubresource;
- texCopyInfo.dstSubresource = dstSubresource;
- texCopyInfo.extent = srcTextureInfo->extents;
- texCopyInfo.srcOffset = { 0, 0, 0 };
- texCopyInfo.dstOffset = { 0, 0, 0 };
-
- bufferCopyInfo.srcSubresource = dstSubresource;
- bufferCopyInfo.extent = dstTextureInfo->extents;
- bufferCopyInfo.textureOffset = { 0, 0, 0 };
- bufferCopyInfo.bufferOffset = 0;
-
- createRequiredResources();
- submitGPUWork();
-
- auto copiedSubresourceIndex = getSubresourceIndex(srcSubresource.mipLevel, srcTextureInfo->mipLevelCount, srcSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedCopiedData = srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
- auto originalSubresourceIndex = getSubresourceIndex(dstSubresource.mipLevel, dstTextureInfo->mipLevelCount, dstSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedOriginalData = dstTextureInfo->subresourceDatas[originalSubresourceIndex];
- checkTestResults(srcTextureInfo->extents, expectedCopiedData.data, expectedOriginalData.data);
- }
- };
+ auto textureType = srcTextureInfo->textureType;
+ auto format = srcTextureInfo->format;
+
+ srcTextureInfo->extents.width = 4;
+ srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
+ srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ srcTextureInfo->mipLevelCount = 1;
+ srcTextureInfo->arrayLayerCount = 1;
+
+ generateTextureData(srcTextureInfo, validationFormat);
+
+ dstTextureInfo->extents.width = 8;
+ dstTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 8;
+ dstTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ dstTextureInfo->mipLevelCount = 1;
+ dstTextureInfo->arrayLayerCount = 1;
+
+ generateTextureData(dstTextureInfo, validationFormat);
+
+ SubresourceRange srcSubresource = {};
+ srcSubresource.aspectMask = getTextureAspect(format);
+ srcSubresource.mipLevel = 0;
+ srcSubresource.mipLevelCount = 1;
+ srcSubresource.baseArrayLayer = 0;
+ srcSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = getTextureAspect(format);
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ texCopyInfo.srcSubresource = srcSubresource;
+ texCopyInfo.dstSubresource = dstSubresource;
+ texCopyInfo.extent = srcTextureInfo->extents;
+ texCopyInfo.srcOffset = {0, 0, 0};
+ texCopyInfo.dstOffset = {0, 0, 0};
+
+ bufferCopyInfo.srcSubresource = dstSubresource;
+ bufferCopyInfo.extent = dstTextureInfo->extents;
+ bufferCopyInfo.textureOffset = {0, 0, 0};
+ bufferCopyInfo.bufferOffset = 0;
+
+ createRequiredResources();
+ submitGPUWork();
+
+ auto copiedSubresourceIndex = getSubresourceIndex(
+ srcSubresource.mipLevel,
+ srcTextureInfo->mipLevelCount,
+ srcSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedCopiedData =
+ srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
+ auto originalSubresourceIndex = getSubresourceIndex(
+ dstSubresource.mipLevel,
+ dstTextureInfo->mipLevelCount,
+ dstSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedOriginalData =
+ dstTextureInfo->subresourceDatas[originalSubresourceIndex];
+ checkTestResults(
+ srcTextureInfo->extents,
+ expectedCopiedData.data,
+ expectedOriginalData.data);
+ }
+};
- struct CopyBetweenMips : BaseCopyTextureTest
+struct CopyBetweenMips : BaseCopyTextureTest
+{
+ void run()
{
- void run()
- {
- auto textureType = srcTextureInfo->textureType;
- auto format = srcTextureInfo->format;
-
- srcTextureInfo->extents.width = 16;
- srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 16;
- srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- srcTextureInfo->mipLevelCount = 4;
- srcTextureInfo->arrayLayerCount = 1;
-
- generateTextureData(srcTextureInfo, validationFormat);
-
- dstTextureInfo->extents.width = 16;
- dstTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 16;
- dstTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- dstTextureInfo->mipLevelCount = 4;
- dstTextureInfo->arrayLayerCount = 1;
-
- generateTextureData(dstTextureInfo, validationFormat);
-
- SubresourceRange srcSubresource = {};
- srcSubresource.aspectMask = getTextureAspect(format);
- srcSubresource.mipLevel = 2;
- srcSubresource.mipLevelCount = 1;
- srcSubresource.baseArrayLayer = 0;
- srcSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = getTextureAspect(format);
- dstSubresource.mipLevel = 1;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- auto copiedSubresourceIndex = getSubresourceIndex(srcSubresource.mipLevel, srcTextureInfo->mipLevelCount, srcSubresource.baseArrayLayer);
- auto originalSubresourceIndex = getSubresourceIndex(dstSubresource.mipLevel, dstTextureInfo->mipLevelCount, dstSubresource.baseArrayLayer);
-
- texCopyInfo.srcSubresource = srcSubresource;
- texCopyInfo.dstSubresource = dstSubresource;
- texCopyInfo.extent = srcTextureInfo->subresourceObjects[copiedSubresourceIndex]->extents;
- texCopyInfo.srcOffset = { 0, 0, 0 };
- texCopyInfo.dstOffset = { 0, 0, 0 };
-
- bufferCopyInfo.srcSubresource = dstSubresource;
- bufferCopyInfo.extent = dstTextureInfo->subresourceObjects[originalSubresourceIndex]->extents;
- bufferCopyInfo.textureOffset = { 0, 0, 0 };
- bufferCopyInfo.bufferOffset = 0;
-
- createRequiredResources();
- submitGPUWork();
-
- ITextureResource::SubresourceData expectedCopiedData = srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
- ITextureResource::SubresourceData expectedOriginalData = dstTextureInfo->subresourceDatas[originalSubresourceIndex];
- auto srcMipExtent = srcTextureInfo->subresourceObjects[2]->extents;
- checkTestResults(srcMipExtent, expectedCopiedData.data, expectedOriginalData.data);
- }
- };
+ auto textureType = srcTextureInfo->textureType;
+ auto format = srcTextureInfo->format;
+
+ srcTextureInfo->extents.width = 16;
+ srcTextureInfo->extents.height =
+ (textureType == ITextureResource::Type::Texture1D) ? 1 : 16;
+ srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ srcTextureInfo->mipLevelCount = 4;
+ srcTextureInfo->arrayLayerCount = 1;
+
+ generateTextureData(srcTextureInfo, validationFormat);
+
+ dstTextureInfo->extents.width = 16;
+ dstTextureInfo->extents.height =
+ (textureType == ITextureResource::Type::Texture1D) ? 1 : 16;
+ dstTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ dstTextureInfo->mipLevelCount = 4;
+ dstTextureInfo->arrayLayerCount = 1;
+
+ generateTextureData(dstTextureInfo, validationFormat);
+
+ SubresourceRange srcSubresource = {};
+ srcSubresource.aspectMask = getTextureAspect(format);
+ srcSubresource.mipLevel = 2;
+ srcSubresource.mipLevelCount = 1;
+ srcSubresource.baseArrayLayer = 0;
+ srcSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = getTextureAspect(format);
+ dstSubresource.mipLevel = 1;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ auto copiedSubresourceIndex = getSubresourceIndex(
+ srcSubresource.mipLevel,
+ srcTextureInfo->mipLevelCount,
+ srcSubresource.baseArrayLayer);
+ auto originalSubresourceIndex = getSubresourceIndex(
+ dstSubresource.mipLevel,
+ dstTextureInfo->mipLevelCount,
+ dstSubresource.baseArrayLayer);
+
+ texCopyInfo.srcSubresource = srcSubresource;
+ texCopyInfo.dstSubresource = dstSubresource;
+ texCopyInfo.extent = srcTextureInfo->subresourceObjects[copiedSubresourceIndex]->extents;
+ texCopyInfo.srcOffset = {0, 0, 0};
+ texCopyInfo.dstOffset = {0, 0, 0};
+
+ bufferCopyInfo.srcSubresource = dstSubresource;
+ bufferCopyInfo.extent =
+ dstTextureInfo->subresourceObjects[originalSubresourceIndex]->extents;
+ bufferCopyInfo.textureOffset = {0, 0, 0};
+ bufferCopyInfo.bufferOffset = 0;
+
+ createRequiredResources();
+ submitGPUWork();
+
+ ITextureResource::SubresourceData expectedCopiedData =
+ srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
+ ITextureResource::SubresourceData expectedOriginalData =
+ dstTextureInfo->subresourceDatas[originalSubresourceIndex];
+ auto srcMipExtent = srcTextureInfo->subresourceObjects[2]->extents;
+ checkTestResults(srcMipExtent, expectedCopiedData.data, expectedOriginalData.data);
+ }
+};
- struct CopyBetweenLayers : BaseCopyTextureTest
+struct CopyBetweenLayers : BaseCopyTextureTest
+{
+ void run()
{
- void run()
- {
- auto textureType = srcTextureInfo->textureType;
- auto format = srcTextureInfo->format;
-
- srcTextureInfo->extents.width = 4;
- srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
- srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- srcTextureInfo->mipLevelCount = 1;
- srcTextureInfo->arrayLayerCount = (textureType == ITextureResource::Type::Texture3D) ? 1 : 2;
-
- generateTextureData(srcTextureInfo, validationFormat);
- dstTextureInfo = srcTextureInfo;
-
- SubresourceRange srcSubresource = {};
- srcSubresource.aspectMask = getTextureAspect(format);
- srcSubresource.mipLevel = 0;
- srcSubresource.mipLevelCount = 1;
- srcSubresource.baseArrayLayer = 0;
- srcSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = getTextureAspect(format);
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = (textureType == ITextureResource::Type::Texture3D) ? 0 : 1;
- dstSubresource.layerCount = 1;
-
- texCopyInfo.srcSubresource = srcSubresource;
- texCopyInfo.dstSubresource = dstSubresource;
- texCopyInfo.extent = srcTextureInfo->extents;
- texCopyInfo.srcOffset = { 0, 0, 0 };
- texCopyInfo.dstOffset = { 0, 0, 0 };
-
- bufferCopyInfo.srcSubresource = dstSubresource;
- bufferCopyInfo.extent = dstTextureInfo->extents;
- bufferCopyInfo.textureOffset = { 0, 0, 0 };
- bufferCopyInfo.bufferOffset = 0;
-
- createRequiredResources();
- submitGPUWork();
-
- auto copiedSubresourceIndex = getSubresourceIndex(srcSubresource.mipLevel, srcTextureInfo->mipLevelCount, srcSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedCopiedData = srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
- auto originalSubresourceIndex = getSubresourceIndex(dstSubresource.mipLevel, dstTextureInfo->mipLevelCount, dstSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedOriginalData = dstTextureInfo->subresourceDatas[originalSubresourceIndex];
- checkTestResults(srcTextureInfo->extents, expectedCopiedData.data, expectedOriginalData.data);
- }
- };
+ auto textureType = srcTextureInfo->textureType;
+ auto format = srcTextureInfo->format;
+
+ srcTextureInfo->extents.width = 4;
+ srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 4;
+ srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ srcTextureInfo->mipLevelCount = 1;
+ srcTextureInfo->arrayLayerCount =
+ (textureType == ITextureResource::Type::Texture3D) ? 1 : 2;
+
+ generateTextureData(srcTextureInfo, validationFormat);
+ dstTextureInfo = srcTextureInfo;
+
+ SubresourceRange srcSubresource = {};
+ srcSubresource.aspectMask = getTextureAspect(format);
+ srcSubresource.mipLevel = 0;
+ srcSubresource.mipLevelCount = 1;
+ srcSubresource.baseArrayLayer = 0;
+ srcSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = getTextureAspect(format);
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = (textureType == ITextureResource::Type::Texture3D) ? 0 : 1;
+ dstSubresource.layerCount = 1;
+
+ texCopyInfo.srcSubresource = srcSubresource;
+ texCopyInfo.dstSubresource = dstSubresource;
+ texCopyInfo.extent = srcTextureInfo->extents;
+ texCopyInfo.srcOffset = {0, 0, 0};
+ texCopyInfo.dstOffset = {0, 0, 0};
+
+ bufferCopyInfo.srcSubresource = dstSubresource;
+ bufferCopyInfo.extent = dstTextureInfo->extents;
+ bufferCopyInfo.textureOffset = {0, 0, 0};
+ bufferCopyInfo.bufferOffset = 0;
+
+ createRequiredResources();
+ submitGPUWork();
+
+ auto copiedSubresourceIndex = getSubresourceIndex(
+ srcSubresource.mipLevel,
+ srcTextureInfo->mipLevelCount,
+ srcSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedCopiedData =
+ srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
+ auto originalSubresourceIndex = getSubresourceIndex(
+ dstSubresource.mipLevel,
+ dstTextureInfo->mipLevelCount,
+ dstSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedOriginalData =
+ dstTextureInfo->subresourceDatas[originalSubresourceIndex];
+ checkTestResults(
+ srcTextureInfo->extents,
+ expectedCopiedData.data,
+ expectedOriginalData.data);
+ }
+};
- struct CopyWithOffsets : BaseCopyTextureTest
+struct CopyWithOffsets : BaseCopyTextureTest
+{
+ void run()
{
- void run()
+ auto textureType = srcTextureInfo->textureType;
+ auto format = srcTextureInfo->format;
+
+ srcTextureInfo->extents.width = 8;
+ srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 8;
+ srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ srcTextureInfo->mipLevelCount = 1;
+ srcTextureInfo->arrayLayerCount = 1;
+
+ generateTextureData(srcTextureInfo, validationFormat);
+
+ dstTextureInfo->extents.width = 16;
+ dstTextureInfo->extents.height =
+ (textureType == ITextureResource::Type::Texture1D) ? 1 : 16;
+ dstTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 4 : 1;
+ dstTextureInfo->mipLevelCount = 1;
+ dstTextureInfo->arrayLayerCount = 1;
+
+ generateTextureData(dstTextureInfo, validationFormat);
+
+ SubresourceRange srcSubresource = {};
+ srcSubresource.aspectMask = getTextureAspect(format);
+ srcSubresource.mipLevel = 0;
+ srcSubresource.mipLevelCount = 1;
+ srcSubresource.baseArrayLayer = 0;
+ srcSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = getTextureAspect(format);
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ texCopyInfo.srcSubresource = srcSubresource;
+ texCopyInfo.dstSubresource = dstSubresource;
+ texCopyInfo.extent.width = 4;
+ texCopyInfo.extent.height = 4;
+ texCopyInfo.extent.depth = 1;
+ texCopyInfo.srcOffset = {2, 2, 0};
+ texCopyInfo.dstOffset = {4, 4, 0};
+
+ if (textureType == ITextureResource::Type::Texture1D)
{
- auto textureType = srcTextureInfo->textureType;
- auto format = srcTextureInfo->format;
-
- srcTextureInfo->extents.width = 8;
- srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 8;
- srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- srcTextureInfo->mipLevelCount = 1;
- srcTextureInfo->arrayLayerCount = 1;
-
- generateTextureData(srcTextureInfo, validationFormat);
-
- dstTextureInfo->extents.width = 16;
- dstTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 16;
- dstTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 4 : 1;
- dstTextureInfo->mipLevelCount = 1;
- dstTextureInfo->arrayLayerCount = 1;
-
- generateTextureData(dstTextureInfo, validationFormat);
-
- SubresourceRange srcSubresource = {};
- srcSubresource.aspectMask = getTextureAspect(format);
- srcSubresource.mipLevel = 0;
- srcSubresource.mipLevelCount = 1;
- srcSubresource.baseArrayLayer = 0;
- srcSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = getTextureAspect(format);
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- texCopyInfo.srcSubresource = srcSubresource;
- texCopyInfo.dstSubresource = dstSubresource;
- texCopyInfo.extent.width = 4;
- texCopyInfo.extent.height = 4;
- texCopyInfo.extent.depth = 1;
- texCopyInfo.srcOffset = { 2, 2, 0 };
- texCopyInfo.dstOffset = { 4, 4, 0 };
-
- if (textureType == ITextureResource::Type::Texture1D)
- {
- texCopyInfo.extent.height = 1;
- texCopyInfo.srcOffset.y = 0;
- texCopyInfo.dstOffset.y = 0;
- }
- else if (textureType == ITextureResource::Type::Texture3D)
- {
- texCopyInfo.extent.depth = srcTextureInfo->extents.depth;
- texCopyInfo.dstOffset.z = 1;
- }
-
- bufferCopyInfo.srcSubresource = dstSubresource;
- bufferCopyInfo.extent = dstTextureInfo->extents;
- bufferCopyInfo.textureOffset = { 0, 0, 0 };
- bufferCopyInfo.bufferOffset = 0;
-
- createRequiredResources();
- submitGPUWork();
-
- auto copiedSubresourceIndex = getSubresourceIndex(srcSubresource.mipLevel, srcTextureInfo->mipLevelCount, srcSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedCopiedData = srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
- auto originalSubresourceIndex = getSubresourceIndex(dstSubresource.mipLevel, dstTextureInfo->mipLevelCount, dstSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedOriginalData = dstTextureInfo->subresourceDatas[originalSubresourceIndex];
- checkTestResults(srcTextureInfo->extents, expectedCopiedData.data, expectedOriginalData.data);
+ texCopyInfo.extent.height = 1;
+ texCopyInfo.srcOffset.y = 0;
+ texCopyInfo.dstOffset.y = 0;
}
- };
-
- struct CopySectionWithSetExtent : BaseCopyTextureTest
- {
- void run()
+ else if (textureType == ITextureResource::Type::Texture3D)
{
- auto textureType = srcTextureInfo->textureType;
- auto format = srcTextureInfo->format;
-
- srcTextureInfo->extents.width = 8;
- srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 8;
- srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
- srcTextureInfo->mipLevelCount = 1;
- srcTextureInfo->arrayLayerCount = 1;
-
- generateTextureData(srcTextureInfo, validationFormat);
- dstTextureInfo = srcTextureInfo;
-
- SubresourceRange srcSubresource = {};
- srcSubresource.aspectMask = getTextureAspect(format);
- srcSubresource.mipLevel = 0;
- srcSubresource.mipLevelCount = 1;
- srcSubresource.baseArrayLayer = 0;
- srcSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = getTextureAspect(format);
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- texCopyInfo.srcSubresource = srcSubresource;
- texCopyInfo.dstSubresource = dstSubresource;
- texCopyInfo.extent.width = 4;
- texCopyInfo.extent.height = 4;
- texCopyInfo.extent.depth = 1;
- texCopyInfo.srcOffset = { 0, 0, 0 };
- texCopyInfo.dstOffset = { 4, 4, 0 };
-
- if (textureType == ITextureResource::Type::Texture1D)
- {
- texCopyInfo.extent.height = 1;
- texCopyInfo.dstOffset.y = 0;
- }
- else if (textureType == ITextureResource::Type::Texture3D)
- {
- texCopyInfo.extent.depth = srcTextureInfo->extents.depth;
- }
-
- bufferCopyInfo.srcSubresource = dstSubresource;
- bufferCopyInfo.extent = dstTextureInfo->extents;
- bufferCopyInfo.textureOffset = { 0, 0, 0 };
- bufferCopyInfo.bufferOffset = 0;
+ texCopyInfo.extent.depth = srcTextureInfo->extents.depth;
+ texCopyInfo.dstOffset.z = 1;
+ }
- createRequiredResources();
- submitGPUWork();
+ bufferCopyInfo.srcSubresource = dstSubresource;
+ bufferCopyInfo.extent = dstTextureInfo->extents;
+ bufferCopyInfo.textureOffset = {0, 0, 0};
+ bufferCopyInfo.bufferOffset = 0;
+
+ createRequiredResources();
+ submitGPUWork();
+
+ auto copiedSubresourceIndex = getSubresourceIndex(
+ srcSubresource.mipLevel,
+ srcTextureInfo->mipLevelCount,
+ srcSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedCopiedData =
+ srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
+ auto originalSubresourceIndex = getSubresourceIndex(
+ dstSubresource.mipLevel,
+ dstTextureInfo->mipLevelCount,
+ dstSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedOriginalData =
+ dstTextureInfo->subresourceDatas[originalSubresourceIndex];
+ checkTestResults(
+ srcTextureInfo->extents,
+ expectedCopiedData.data,
+ expectedOriginalData.data);
+ }
+};
- auto copiedSubresourceIndex = getSubresourceIndex(srcSubresource.mipLevel, srcTextureInfo->mipLevelCount, srcSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedCopiedData = srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
- auto originalSubresourceIndex = getSubresourceIndex(dstSubresource.mipLevel, dstTextureInfo->mipLevelCount, dstSubresource.baseArrayLayer);
- ITextureResource::SubresourceData expectedOriginalData = dstTextureInfo->subresourceDatas[originalSubresourceIndex];
- checkTestResults(srcTextureInfo->extents, expectedCopiedData.data, expectedOriginalData.data);
+struct CopySectionWithSetExtent : BaseCopyTextureTest
+{
+ void run()
+ {
+ auto textureType = srcTextureInfo->textureType;
+ auto format = srcTextureInfo->format;
+
+ srcTextureInfo->extents.width = 8;
+ srcTextureInfo->extents.height = (textureType == ITextureResource::Type::Texture1D) ? 1 : 8;
+ srcTextureInfo->extents.depth = (textureType == ITextureResource::Type::Texture3D) ? 2 : 1;
+ srcTextureInfo->mipLevelCount = 1;
+ srcTextureInfo->arrayLayerCount = 1;
+
+ generateTextureData(srcTextureInfo, validationFormat);
+ dstTextureInfo = srcTextureInfo;
+
+ SubresourceRange srcSubresource = {};
+ srcSubresource.aspectMask = getTextureAspect(format);
+ srcSubresource.mipLevel = 0;
+ srcSubresource.mipLevelCount = 1;
+ srcSubresource.baseArrayLayer = 0;
+ srcSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = getTextureAspect(format);
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ texCopyInfo.srcSubresource = srcSubresource;
+ texCopyInfo.dstSubresource = dstSubresource;
+ texCopyInfo.extent.width = 4;
+ texCopyInfo.extent.height = 4;
+ texCopyInfo.extent.depth = 1;
+ texCopyInfo.srcOffset = {0, 0, 0};
+ texCopyInfo.dstOffset = {4, 4, 0};
+
+ if (textureType == ITextureResource::Type::Texture1D)
+ {
+ texCopyInfo.extent.height = 1;
+ texCopyInfo.dstOffset.y = 0;
+ }
+ else if (textureType == ITextureResource::Type::Texture3D)
+ {
+ texCopyInfo.extent.depth = srcTextureInfo->extents.depth;
}
- };
- template<typename T>
- void copyTextureTestImpl(IDevice* device, UnitTestContext* context)
- {
- const bool isVkd3d = SLANG_ENABLE_VKD3D &&
- strcmp(device->getDeviceInfo().apiName, "Direct3D 12") == 0;
+ bufferCopyInfo.srcSubresource = dstSubresource;
+ bufferCopyInfo.extent = dstTextureInfo->extents;
+ bufferCopyInfo.textureOffset = {0, 0, 0};
+ bufferCopyInfo.bufferOffset = 0;
+
+ createRequiredResources();
+ submitGPUWork();
+
+ auto copiedSubresourceIndex = getSubresourceIndex(
+ srcSubresource.mipLevel,
+ srcTextureInfo->mipLevelCount,
+ srcSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedCopiedData =
+ srcTextureInfo->subresourceDatas[copiedSubresourceIndex];
+ auto originalSubresourceIndex = getSubresourceIndex(
+ dstSubresource.mipLevel,
+ dstTextureInfo->mipLevelCount,
+ dstSubresource.baseArrayLayer);
+ ITextureResource::SubresourceData expectedOriginalData =
+ dstTextureInfo->subresourceDatas[originalSubresourceIndex];
+ checkTestResults(
+ srcTextureInfo->extents,
+ expectedCopiedData.data,
+ expectedOriginalData.data);
+ }
+};
- // Skip Type::Unknown and Type::Buffer as well as Format::Unknown
- // TODO: Add support for TextureCube
- Format formats[] = { Format::R8G8B8A8_UNORM, Format::R16_FLOAT, Format::R16G16_FLOAT, Format::R10G10B10A2_UNORM, Format::B5G5R5A1_UNORM };
- for (uint32_t i = 2; i < (uint32_t)ITextureResource::Type::_Count - 1; ++i)
+template<typename T>
+void copyTextureTestImpl(IDevice* device, UnitTestContext* context)
+{
+ const bool isVkd3d =
+ SLANG_ENABLE_VKD3D && strcmp(device->getDeviceInfo().apiName, "Direct3D 12") == 0;
+
+ // Skip Type::Unknown and Type::Buffer as well as Format::Unknown
+ // TODO: Add support for TextureCube
+ Format formats[] = {
+ Format::R8G8B8A8_UNORM,
+ Format::R16_FLOAT,
+ Format::R16G16_FLOAT,
+ Format::R10G10B10A2_UNORM,
+ Format::B5G5R5A1_UNORM};
+ for (uint32_t i = 2; i < (uint32_t)ITextureResource::Type::_Count - 1; ++i)
+ {
+ for (auto format : formats)
{
- for (auto format : formats)
+ // Fails validation VUID-VkImageCreateInfo-imageCreateMaxMipLevels-02251
+ if (isVkd3d &&
+ (format == Format::R32G32B32_TYPELESS || format == Format::R32G32B32_FLOAT ||
+ format == Format::R32G32B32_UINT || format == Format::R32G32B32_SINT))
{
- // Fails validation VUID-VkImageCreateInfo-imageCreateMaxMipLevels-02251
- if(isVkd3d && (format == Format::R32G32B32_TYPELESS ||
- format == Format::R32G32B32_FLOAT ||
- format == Format::R32G32B32_UINT ||
- format == Format::R32G32B32_SINT))
- {
- continue;
- }
- auto type = (ITextureResource::Type)i;
- auto validationFormat = getValidationTextureFormat(format);
- if (!validationFormat)
- continue;
-
- T test;
- test.init(device, context, format, validationFormat, type);
- test.run();
+ continue;
}
+ auto type = (ITextureResource::Type)i;
+ auto validationFormat = getValidationTextureFormat(format);
+ if (!validationFormat)
+ continue;
+
+ T test;
+ test.init(device, context, format, validationFormat, type);
+ test.run();
}
}
+}
- SLANG_UNIT_TEST(copyTextureSimple)
- {
- runTestImpl(copyTextureTestImpl<SimpleCopyTexture>, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(copyTextureTestImpl<SimpleCopyTexture>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(copyTextureSimple)
+{
+ runTestImpl(
+ copyTextureTestImpl<SimpleCopyTexture>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+ runTestImpl(
+ copyTextureTestImpl<SimpleCopyTexture>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
+}
- SLANG_UNIT_TEST(copyTextureSection)
- {
- runTestImpl(copyTextureTestImpl<CopyTextureSection>, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(copyTextureTestImpl<CopyTextureSection>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(copyTextureSection)
+{
+ runTestImpl(
+ copyTextureTestImpl<CopyTextureSection>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+ runTestImpl(
+ copyTextureTestImpl<CopyTextureSection>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
+}
- SLANG_UNIT_TEST(copyLargeToSmallTexture)
- {
- runTestImpl(copyTextureTestImpl<LargeSrcToSmallDst>, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(copyTextureTestImpl<LargeSrcToSmallDst>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(copyLargeToSmallTexture)
+{
+ runTestImpl(
+ copyTextureTestImpl<LargeSrcToSmallDst>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+ runTestImpl(
+ copyTextureTestImpl<LargeSrcToSmallDst>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
+}
- SLANG_UNIT_TEST(copySmallToLargeTexture)
- {
- runTestImpl(copyTextureTestImpl<SmallSrcToLargeDst>, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(copyTextureTestImpl<SmallSrcToLargeDst>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(copySmallToLargeTexture)
+{
+ runTestImpl(
+ copyTextureTestImpl<SmallSrcToLargeDst>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+ runTestImpl(
+ copyTextureTestImpl<SmallSrcToLargeDst>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
+}
- SLANG_UNIT_TEST(copyBetweenMips)
- {
- runTestImpl(copyTextureTestImpl<CopyBetweenMips>, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(copyTextureTestImpl<CopyBetweenMips>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(copyBetweenMips)
+{
+ runTestImpl(copyTextureTestImpl<CopyBetweenMips>, unitTestContext, Slang::RenderApiFlag::D3D12);
+ runTestImpl(
+ copyTextureTestImpl<CopyBetweenMips>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
+}
- SLANG_UNIT_TEST(copyBetweenLayers)
- {
- runTestImpl(copyTextureTestImpl<CopyBetweenLayers>, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(copyTextureTestImpl<CopyBetweenLayers>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(copyBetweenLayers)
+{
+ runTestImpl(
+ copyTextureTestImpl<CopyBetweenLayers>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+ runTestImpl(
+ copyTextureTestImpl<CopyBetweenLayers>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
+}
- SLANG_UNIT_TEST(copyWithOffsets)
- {
- runTestImpl(copyTextureTestImpl<CopyWithOffsets>, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(copyTextureTestImpl<CopyWithOffsets>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(copyWithOffsets)
+{
+ runTestImpl(copyTextureTestImpl<CopyWithOffsets>, unitTestContext, Slang::RenderApiFlag::D3D12);
+ runTestImpl(
+ copyTextureTestImpl<CopyWithOffsets>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
+}
- SLANG_UNIT_TEST(copySectionWithSetExtent)
- {
- runTestImpl(copyTextureTestImpl<CopySectionWithSetExtent>, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(copyTextureTestImpl<CopySectionWithSetExtent>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(copySectionWithSetExtent)
+{
+ runTestImpl(
+ copyTextureTestImpl<CopySectionWithSetExtent>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+ runTestImpl(
+ copyTextureTestImpl<CopySectionWithSetExtent>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/create-buffer-from-handle.cpp b/tools/gfx-unit-test/create-buffer-from-handle.cpp
index 4e2261465..a4e743196 100644
--- a/tools/gfx-unit-test/create-buffer-from-handle.cpp
+++ b/tools/gfx-unit-test/create-buffer-from-handle.cpp
@@ -1,101 +1,103 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void createBufferFromHandleTestImpl(IDevice* device, UnitTestContext* context)
+void createBufferFromHandleTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "compute-trivial",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 1.0f, 2.0f, 3.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> originalNumbersBuffer;
+ GFX_CHECK_CALL_ABORT(device->createBufferResource(
+ bufferDesc,
+ (void*)initialData,
+ originalNumbersBuffer.writeRef()));
+
+ InteropHandle handle;
+ originalNumbersBuffer->getNativeResourceHandle(&handle);
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferFromNativeHandle(handle, bufferDesc, numbersBuffer.writeRef()));
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(0.0f, 1.0f, 2.0f, 3.0f));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "compute-trivial", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 1.0f, 2.0f, 3.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> originalNumbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- originalNumbersBuffer.writeRef()));
-
- InteropHandle handle;
- originalNumbersBuffer->getNativeResourceHandle(&handle);
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferFromNativeHandle(handle, bufferDesc, numbersBuffer.writeRef()));
- compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(0.0f, 1.0f, 2.0f, 3.0f));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor rootCursor(rootObject);
- // Bind buffer view to the entry point.
- rootCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(1.0f, 2.0f, 3.0f, 4.0f));
- }
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- SLANG_UNIT_TEST(createBufferFromHandleD3D12)
- {
- runTestImpl(createBufferFromHandleTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- SLANG_UNIT_TEST(createBufferFromHandleVulkan)
- {
- runTestImpl(createBufferFromHandleTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ ShaderCursor rootCursor(rootObject);
+ // Bind buffer view to the entry point.
+ rootCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(1.0f, 2.0f, 3.0f, 4.0f));
+}
+
+SLANG_UNIT_TEST(createBufferFromHandleD3D12)
+{
+ runTestImpl(createBufferFromHandleTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
}
+
+SLANG_UNIT_TEST(createBufferFromHandleVulkan)
+{
+ runTestImpl(createBufferFromHandleTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/existing-device-handle-test.cpp b/tools/gfx-unit-test/existing-device-handle-test.cpp
index d6f66af84..03f924b5c 100644
--- a/tools/gfx-unit-test/existing-device-handle-test.cpp
+++ b/tools/gfx-unit-test/existing-device-handle-test.cpp
@@ -1,151 +1,143 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void existingDeviceHandleTestImpl(IDevice* device, UnitTestContext* context)
+void existingDeviceHandleTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "compute-trivial",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 1.0f, 2.0f, 3.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "compute-trivial", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 1.0f, 2.0f, 3.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor rootCursor(rootObject);
- // Bind buffer view to the root.
- rootCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(1.0f, 2.0f, 3.0f, 4.0f));
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ ShaderCursor rootCursor(rootObject);
+ // Bind buffer view to the root.
+ rootCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- void existingDeviceHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(1.0f, 2.0f, 3.0f, 4.0f));
+}
+
+void existingDeviceHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+{
+ if ((api & context->enabledApis) == 0)
{
- if ((api & context->enabledApis) == 0)
- {
- SLANG_IGNORE_TEST;
- }
- Slang::ComPtr<IDevice> device;
- IDevice::Desc deviceDesc = {};
- switch (api)
- {
- case Slang::RenderApiFlag::D3D12:
- deviceDesc.deviceType = gfx::DeviceType::DirectX12;
- break;
- case Slang::RenderApiFlag::Vulkan:
- deviceDesc.deviceType = gfx::DeviceType::Vulkan;
- break;
- case Slang::RenderApiFlag::CUDA:
- deviceDesc.deviceType = gfx::DeviceType::CUDA;
- break;
- default:
- SLANG_IGNORE_TEST;
- }
- deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
- const char* searchPaths[] = { "", "../../tools/gfx-unit-test", "tools/gfx-unit-test" };
- deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
- deviceDesc.slang.searchPaths = searchPaths;
- auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
- if (SLANG_FAILED(createDeviceResult) || !device)
- {
- SLANG_IGNORE_TEST;
- }
-
- IDevice::InteropHandles handles;
- GFX_CHECK_CALL_ABORT(device->getNativeDeviceHandles(&handles));
- Slang::ComPtr<IDevice> testDevice;
- IDevice::Desc testDeviceDesc = deviceDesc;
- testDeviceDesc.existingDeviceHandles.handles[0] = handles.handles[0];
- if (api == Slang::RenderApiFlag::Vulkan)
- {
- testDeviceDesc.existingDeviceHandles.handles[1] = handles.handles[1];
- testDeviceDesc.existingDeviceHandles.handles[2] = handles.handles[2];
- }
- auto createTestDeviceResult = gfxCreateDevice(&testDeviceDesc, testDevice.writeRef());
- if (SLANG_FAILED(createTestDeviceResult) || !device)
- {
- SLANG_IGNORE_TEST;
- }
-
- existingDeviceHandleTestImpl(device, context);
+ SLANG_IGNORE_TEST;
}
-
- SLANG_UNIT_TEST(existingDeviceHandleD3D12)
+ Slang::ComPtr<IDevice> device;
+ IDevice::Desc deviceDesc = {};
+ switch (api)
{
- return existingDeviceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+ case Slang::RenderApiFlag::D3D12: deviceDesc.deviceType = gfx::DeviceType::DirectX12; break;
+ case Slang::RenderApiFlag::Vulkan: deviceDesc.deviceType = gfx::DeviceType::Vulkan; break;
+ case Slang::RenderApiFlag::CUDA: deviceDesc.deviceType = gfx::DeviceType::CUDA; break;
+ default: SLANG_IGNORE_TEST;
+ }
+ deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
+ const char* searchPaths[] = {"", "../../tools/gfx-unit-test", "tools/gfx-unit-test"};
+ deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
+ deviceDesc.slang.searchPaths = searchPaths;
+ auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
+ if (SLANG_FAILED(createDeviceResult) || !device)
+ {
+ SLANG_IGNORE_TEST;
}
- SLANG_UNIT_TEST(existingDeviceHandleVulkan)
+ IDevice::InteropHandles handles;
+ GFX_CHECK_CALL_ABORT(device->getNativeDeviceHandles(&handles));
+ Slang::ComPtr<IDevice> testDevice;
+ IDevice::Desc testDeviceDesc = deviceDesc;
+ testDeviceDesc.existingDeviceHandles.handles[0] = handles.handles[0];
+ if (api == Slang::RenderApiFlag::Vulkan)
{
- return existingDeviceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ testDeviceDesc.existingDeviceHandles.handles[1] = handles.handles[1];
+ testDeviceDesc.existingDeviceHandles.handles[2] = handles.handles[2];
}
-#if SLANG_WIN64
- SLANG_UNIT_TEST(existingDeviceHandleCUDA)
+ auto createTestDeviceResult = gfxCreateDevice(&testDeviceDesc, testDevice.writeRef());
+ if (SLANG_FAILED(createTestDeviceResult) || !device)
{
- return existingDeviceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::CUDA);
+ SLANG_IGNORE_TEST;
}
-#endif
+
+ existingDeviceHandleTestImpl(device, context);
+}
+
+SLANG_UNIT_TEST(existingDeviceHandleD3D12)
+{
+ return existingDeviceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
}
+
+SLANG_UNIT_TEST(existingDeviceHandleVulkan)
+{
+ return existingDeviceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+#if SLANG_WIN64
+SLANG_UNIT_TEST(existingDeviceHandleCUDA)
+{
+ return existingDeviceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::CUDA);
+}
+#endif
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/format-unit-tests.cpp b/tools/gfx-unit-test/format-unit-tests.cpp
index 5755e03cd..6ce38a26a 100644
--- a/tools/gfx-unit-test/format-unit-tests.cpp
+++ b/tools/gfx-unit-test/format-unit-tests.cpp
@@ -1,1119 +1,1489 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- gfx::Format convertTypelessFormat(gfx::Format format)
+gfx::Format convertTypelessFormat(gfx::Format format)
+{
+ switch (format)
+ {
+ case gfx::Format::R32G32B32A32_TYPELESS: return gfx::Format::R32G32B32A32_FLOAT;
+ case gfx::Format::R32G32B32_TYPELESS: return gfx::Format::R32G32B32_FLOAT;
+ case gfx::Format::R32G32_TYPELESS: return gfx::Format::R32G32_FLOAT;
+ case gfx::Format::R32_TYPELESS: return gfx::Format::R32_FLOAT;
+ case gfx::Format::R16G16B16A16_TYPELESS: return gfx::Format::R16G16B16A16_FLOAT;
+ case gfx::Format::R16G16_TYPELESS: return gfx::Format::R16G16_FLOAT;
+ case gfx::Format::R16_TYPELESS: return gfx::Format::R16_FLOAT;
+ case gfx::Format::R8G8B8A8_TYPELESS: return gfx::Format::R8G8B8A8_UNORM;
+ case gfx::Format::R8G8_TYPELESS: return gfx::Format::R8G8_UNORM;
+ case gfx::Format::R8_TYPELESS: return gfx::Format::R8_UNORM;
+ case gfx::Format::B8G8R8A8_TYPELESS: return gfx::Format::B8G8R8A8_UNORM;
+ case gfx::Format::R10G10B10A2_TYPELESS: return gfx::Format::R10G10B10A2_UINT;
+ default: return gfx::Format::Unknown;
+ }
+}
+
+void setUpAndRunTest(
+ IDevice* device,
+ ComPtr<IResourceView> texView,
+ ComPtr<IResourceView> bufferView,
+ const char* entryPoint,
+ ComPtr<ISamplerState> sampler = nullptr)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "format-test-shaders",
+ entryPoint,
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
+ {
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+
+ // Bind texture view to the entry point
+ entryPointCursor.getPath("tex").setResource(texView);
+
+ if (sampler)
+ entryPointCursor.getPath("sampler").setSampler(sampler);
+
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
+}
+
+ComPtr<IResourceView> createTexView(
+ IDevice* device,
+ ITextureResource::Extents size,
+ gfx::Format format,
+ ITextureResource::SubresourceData* data,
+ int mips = 1)
+{
+ ITextureResource::Desc texDesc = {};
+ texDesc.type = IResource::Type::Texture2D;
+ texDesc.numMipLevels = mips;
+ texDesc.arraySize = 1;
+ texDesc.size = size;
+ texDesc.defaultState = ResourceState::ShaderResource;
+ texDesc.format = format;
+
+ ComPtr<ITextureResource> inTex;
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(texDesc, data, inTex.writeRef()));
+
+ ComPtr<IResourceView> texView;
+ IResourceView::Desc texViewDesc = {};
+ texViewDesc.type = IResourceView::Type::ShaderResource;
+ texViewDesc.format = gfxIsTypelessFormat(format) ? convertTypelessFormat(format) : format;
+ GFX_CHECK_CALL_ABORT(device->createTextureView(inTex, texViewDesc, texView.writeRef()));
+ return texView;
+}
+
+template<typename T>
+ComPtr<IBufferResource> createBuffer(IDevice* device, int size, void* initialData)
+{
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = size * sizeof(T);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(T);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> outBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, initialData, outBuffer.writeRef()));
+ return outBuffer;
+}
+
+ComPtr<IResourceView> createBufferView(IDevice* device, ComPtr<IBufferResource> outBuffer)
+{
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(outBuffer, nullptr, viewDesc, bufferView.writeRef()));
+ return bufferView;
+}
+
+void formatTestsImpl(IDevice* device, UnitTestContext* context)
+{
+ ISamplerState::Desc samplerDesc;
+ auto sampler = device->createSamplerState(samplerDesc);
+
+ float initFloatData[16] = {0.0f};
+ auto floatResults = createBuffer<float>(device, 16, initFloatData);
+ auto floatBufferView = createBufferView(device, floatResults);
+
+ uint32_t initUintData[16] = {0u};
+ auto uintResults = createBuffer<uint32_t>(device, 16, initUintData);
+ auto uintBufferView = createBufferView(device, uintResults);
+
+ int32_t initIntData[16] = {0};
+ auto intResults = createBuffer<uint32_t>(device, 16, initIntData);
+ auto intBufferView = createBufferView(device, intResults);
+
+ ITextureResource::Extents size = {};
+ size.width = 2;
+ size.height = 2;
+ size.depth = 1;
+
+ ITextureResource::Extents bcSize = {};
+ bcSize.width = 4;
+ bcSize.height = 4;
+ bcSize.depth = 1;
+
+ // Note: D32_FLOAT and D16_UNORM are not directly tested as they are only used for raster. These
+ // are the same as R32_FLOAT and R16_UNORM, respectively, when passed to a shader.
+ {
+ float texData[] = {
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.5f,
+ 0.5f,
+ 0.5f,
+ 1.0f};
+ ITextureResource::SubresourceData subData = {(void*)texData, 32, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32B32A32_FLOAT, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.5f,
+ 0.5f,
+ 0.5f,
+ 1.0f));
+
+ texView = createTexView(device, size, gfx::Format::R32G32B32A32_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.5f,
+ 0.5f,
+ 0.5f,
+ 1.0f));
+ }
+
+ // Ignore this test since it is not supported by swiftshader and nvidia's driver.
+ if (false)
+ {
+ float texData[] = {1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f};
+ ITextureResource::SubresourceData subData = {(void*)texData, 24, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32B32_FLOAT, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<
+ float>(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f));
+
+ texView = createTexView(device, size, gfx::Format::R32G32B32_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<
+ float>(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f));
+ }
+
+ {
+ float texData[] = {1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32_FLOAT, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f));
+
+ texView = createTexView(device, size, gfx::Format::R32G32_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f));
+ }
+
+ {
+ float texData[] = {1.0f, 0.0f, 0.5f, 0.25f};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32_FLOAT, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.5f, 0.25f));
+
+ texView = createTexView(device, size, gfx::Format::R32_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.5f, 0.25f));
+ }
+
+ {
+ uint16_t texData[] = {
+ 15360u,
+ 0u,
+ 0u,
+ 15360u,
+ 0u,
+ 15360u,
+ 0u,
+ 15360u,
+ 0u,
+ 0u,
+ 15360u,
+ 15360u,
+ 14336u,
+ 14336u,
+ 14336u,
+ 15360u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_FLOAT, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.5f,
+ 0.5f,
+ 0.5f,
+ 1.0f));
+
+ texView = createTexView(device, size, gfx::Format::R16G16B16A16_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.5f,
+ 0.5f,
+ 0.5f,
+ 1.0f));
+ }
+
+ {
+ uint16_t texData[] = {15360u, 0u, 0u, 15360u, 15360u, 15360u, 14336u, 14336u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16_FLOAT, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f));
+
+ texView = createTexView(device, size, gfx::Format::R16G16_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f));
+ }
+
+ {
+ uint16_t texData[] = {15360u, 0u, 14336u, 13312u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16_FLOAT, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.5f, 0.25f));
+
+ texView = createTexView(device, size, gfx::Format::R16_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.5f, 0.25f));
+ }
+
+ {
+ uint32_t texData[] =
+ {255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u, 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 32, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32B32A32_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(
+ 255u,
+ 0u,
+ 0u,
+ 255u,
+ 0u,
+ 255u,
+ 0u,
+ 255u,
+ 0u,
+ 0u,
+ 255u,
+ 255u,
+ 127u,
+ 127u,
+ 127u,
+ 255u));
+ }
+
+ // Ignore this test since validation layer reports that it is unsupported.
+ if (false)
{
- switch (format)
- {
- case gfx::Format::R32G32B32A32_TYPELESS:
- return gfx::Format::R32G32B32A32_FLOAT;
- case gfx::Format::R32G32B32_TYPELESS:
- return gfx::Format::R32G32B32_FLOAT;
- case gfx::Format::R32G32_TYPELESS:
- return gfx::Format::R32G32_FLOAT;
- case gfx::Format::R32_TYPELESS:
- return gfx::Format::R32_FLOAT;
- case gfx::Format::R16G16B16A16_TYPELESS:
- return gfx::Format::R16G16B16A16_FLOAT;
- case gfx::Format::R16G16_TYPELESS:
- return gfx::Format::R16G16_FLOAT;
- case gfx::Format::R16_TYPELESS:
- return gfx::Format::R16_FLOAT;
- case gfx::Format::R8G8B8A8_TYPELESS:
- return gfx::Format::R8G8B8A8_UNORM;
- case gfx::Format::R8G8_TYPELESS:
- return gfx::Format::R8G8_UNORM;
- case gfx::Format::R8_TYPELESS:
- return gfx::Format::R8_UNORM;
- case gfx::Format::B8G8R8A8_TYPELESS:
- return gfx::Format::B8G8R8A8_UNORM;
- case gfx::Format::R10G10B10A2_TYPELESS:
- return gfx::Format::R10G10B10A2_UINT;
- default:
- return gfx::Format::Unknown;
- }
+ uint32_t texData[] = {255u, 0u, 0u, 0u, 255u, 0u, 0u, 0u, 255u, 127u, 127u, 127u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 24, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32B32_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint3");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(255u, 0u, 0u, 0u, 255u, 0u, 0u, 0u, 255u, 127u, 127u, 127u));
}
- void setUpAndRunTest(
- IDevice* device,
- ComPtr<IResourceView> texView,
- ComPtr<IResourceView> bufferView,
- const char* entryPoint,
- ComPtr<ISamplerState> sampler = nullptr)
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "format-test-shaders", entryPoint, slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
-
- // Bind texture view to the entry point
- entryPointCursor.getPath("tex").setResource(texView);
-
- if (sampler) entryPointCursor.getPath("sampler").setSampler(sampler);
-
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ uint32_t texData[] = {255u, 0u, 0u, 255u, 255u, 255u, 127u, 127u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint2");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u, 255u, 255u, 127u, 127u));
}
- ComPtr<IResourceView> createTexView(
- IDevice* device,
- ITextureResource::Extents size,
- gfx::Format format,
- ITextureResource::SubresourceData* data,
- int mips = 1)
{
- ITextureResource::Desc texDesc = {};
- texDesc.type = IResource::Type::Texture2D;
- texDesc.numMipLevels = mips;
- texDesc.arraySize = 1;
- texDesc.size = size;
- texDesc.defaultState = ResourceState::ShaderResource;
- texDesc.format = format;
-
- ComPtr<ITextureResource> inTex;
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- texDesc,
- data,
- inTex.writeRef()));
-
- ComPtr<IResourceView> texView;
- IResourceView::Desc texViewDesc = {};
- texViewDesc.type = IResourceView::Type::ShaderResource;
- texViewDesc.format = gfxIsTypelessFormat(format) ? convertTypelessFormat(format) : format;
- GFX_CHECK_CALL_ABORT(device->createTextureView(inTex, texViewDesc, texView.writeRef()));
- return texView;
+ uint32_t texData[] = {255u, 0u, 127u, 73u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint");
+ compareComputeResult(device, uintResults, Slang::makeArray<uint32_t>(255u, 0u, 127u, 73u));
}
- template <typename T>
- ComPtr<IBufferResource> createBuffer(IDevice* device, int size, void* initialData)
{
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = size * sizeof(T);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(T);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> outBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- initialData,
- outBuffer.writeRef()));
- return outBuffer;
+ uint16_t texData[] =
+ {255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u, 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(
+ 255u,
+ 0u,
+ 0u,
+ 255u,
+ 0u,
+ 255u,
+ 0u,
+ 255u,
+ 0u,
+ 0u,
+ 255u,
+ 255u,
+ 127u,
+ 127u,
+ 127u,
+ 255u));
}
- ComPtr<IResourceView> createBufferView(IDevice* device, ComPtr<IBufferResource> outBuffer)
{
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(outBuffer, nullptr, viewDesc, bufferView.writeRef()));
- return bufferView;
+ uint16_t texData[] = {255u, 0u, 0u, 255u, 255u, 255u, 127u, 127u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint2");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u, 255u, 255u, 127u, 127u));
}
- void formatTestsImpl(IDevice* device, UnitTestContext* context)
{
- ISamplerState::Desc samplerDesc;
- auto sampler = device->createSamplerState(samplerDesc);
+ uint16_t texData[] = {255u, 0u, 127u, 73u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
- float initFloatData[16] = { 0.0f };
- auto floatResults = createBuffer<float>(device, 16, initFloatData);
- auto floatBufferView = createBufferView(device, floatResults);
+ auto texView = createTexView(device, size, gfx::Format::R16_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint");
+ compareComputeResult(device, uintResults, Slang::makeArray<uint32_t>(255u, 0u, 127u, 73u));
+ }
- uint32_t initUintData[16] = { 0u };
- auto uintResults = createBuffer<uint32_t>(device, 16, initUintData);
- auto uintBufferView = createBufferView(device, uintResults);
+ {
+ uint8_t texData[] =
+ {255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u, 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8G8B8A8_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(
+ 255u,
+ 0u,
+ 0u,
+ 255u,
+ 0u,
+ 255u,
+ 0u,
+ 255u,
+ 0u,
+ 0u,
+ 255u,
+ 255u,
+ 127u,
+ 127u,
+ 127u,
+ 255u));
+ }
- int32_t initIntData[16] = { 0 };
- auto intResults = createBuffer<uint32_t>(device, 16, initIntData);
- auto intBufferView = createBufferView(device, intResults);
+ {
+ uint8_t texData[] = {255u, 0u, 0u, 255u, 255u, 255u, 127u, 127u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8G8_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint2");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u, 255u, 255u, 127u, 127u));
+ }
+ {
+ uint8_t texData[] = {255u, 0u, 127u, 73u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 2, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint");
+ compareComputeResult(device, uintResults, Slang::makeArray<uint32_t>(255u, 0u, 127u, 73u));
+ }
+
+ {
+ int32_t texData[] = {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 127, 127, 127, 255};
+ ITextureResource::SubresourceData subData = {(void*)texData, 32, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32B32A32_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt4");
+ compareComputeResult(
+ device,
+ intResults,
+ Slang::makeArray<
+ int32_t>(255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 127, 127, 127, 255));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces unsupported format warnings for this
+ // test.
+ if (false)
+ {
+ int32_t texData[] = {255, 0, 0, 0, 255, 0, 0, 0, 255, 127, 127, 127};
+ ITextureResource::SubresourceData subData = {(void*)texData, 24, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32B32_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt3");
+ compareComputeResult(
+ device,
+ intResults,
+ Slang::makeArray<int32_t>(255, 0, 0, 0, 255, 0, 0, 0, 255, 127, 127, 127));
+ }
+
+ {
+ int32_t texData[] = {255, 0, 0, 255, 255, 255, 127, 127};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32G32_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt2");
+ compareComputeResult(
+ device,
+ intResults,
+ Slang::makeArray<int32_t>(255, 0, 0, 255, 255, 255, 127, 127));
+ }
+
+ {
+ int32_t texData[] = {255, 0, 127, 73};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R32_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt");
+ compareComputeResult(device, intResults, Slang::makeArray<int32_t>(255, 0, 127, 73));
+ }
+
+ {
+ int16_t texData[] = {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 127, 127, 127, 255};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt4");
+ compareComputeResult(
+ device,
+ intResults,
+ Slang::makeArray<
+ int32_t>(255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 127, 127, 127, 255));
+ }
+
+ {
+ int16_t texData[] = {255, 0, 0, 255, 255, 255, 127, 127};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt2");
+ compareComputeResult(
+ device,
+ intResults,
+ Slang::makeArray<int32_t>(255, 0, 0, 255, 255, 255, 127, 127));
+ }
+
+ {
+ int16_t texData[] = {255, 0, 127, 73};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt");
+ compareComputeResult(device, intResults, Slang::makeArray<int32_t>(255, 0, 127, 73));
+ }
+
+ {
+ int8_t texData[] = {127, 0, 0, 127, 0, 127, 0, 127, 0, 0, 127, 127, 0, 0, 0, 127};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8G8B8A8_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt4");
+ compareComputeResult(
+ device,
+ intResults,
+ Slang::makeArray<
+ int32_t>(127, 0, 0, 127, 0, 127, 0, 127, 0, 0, 127, 127, 0, 0, 0, 127));
+ }
+
+ {
+ int8_t texData[] = {127, 0, 0, 127, 127, 127, 73, 73};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8G8_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt2");
+ compareComputeResult(
+ device,
+ intResults,
+ Slang::makeArray<int32_t>(127, 0, 0, 127, 127, 127, 73, 73));
+ }
+
+ {
+ int8_t texData[] = {127, 0, 73, 25};
+ ITextureResource::SubresourceData subData = {(void*)texData, 2, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8_SINT, &subData);
+ setUpAndRunTest(device, texView, intBufferView, "copyTexInt");
+ compareComputeResult(device, intResults, Slang::makeArray<int32_t>(127, 0, 73, 25));
+ }
+
+ {
+ uint16_t texData[] = {
+ 65535u,
+ 0u,
+ 0u,
+ 65535u,
+ 0u,
+ 65535u,
+ 0u,
+ 65535u,
+ 0u,
+ 0u,
+ 65535u,
+ 65535u,
+ 32767u,
+ 32767u,
+ 32767u,
+ 32767u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.499992371f,
+ 0.499992371f,
+ 0.499992371f,
+ 0.499992371f));
+ }
+
+ {
+ uint16_t texData[] = {65535u, 0u, 0u, 65535u, 65535u, 65535u, 32767u, 32767u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<
+ float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.499992371f, 0.499992371f));
+ }
+
+ {
+ uint16_t texData[] = {65535u, 0u, 32767u, 16383u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.499992371f, 0.249988556f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] =
+ {0u, 0u, 0u, 255u, 127u, 127u, 127u, 255u, 255u, 255u, 255u, 255u, 0u, 0u, 0u, 0u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8G8B8A8_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.498039216f,
+ 0.498039216f,
+ 0.498039216f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f));
+
+ texView = createTexView(device, size, gfx::Format::R8G8B8A8_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.498039216f,
+ 0.498039216f,
+ 0.498039216f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f));
+
+ texView = createTexView(device, size, gfx::Format::R8G8B8A8_UNORM_SRGB, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.211914062f,
+ 0.211914062f,
+ 0.211914062f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] = {255u, 0u, 0u, 255u, 255u, 255u, 127u, 127u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8G8_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<
+ float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.498039216f, 0.498039216f));
+
+ texView = createTexView(device, size, gfx::Format::R8G8_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<
+ float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.498039216f, 0.498039216f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] = {255u, 0u, 127u, 63u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 2, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.498039216f, 0.247058824f));
+
+ texView = createTexView(device, size, gfx::Format::R8_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.498039216f, 0.247058824f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] =
+ {0u, 0u, 0u, 255u, 127u, 127u, 127u, 255u, 255u, 255u, 255u, 255u, 0u, 0u, 0u, 0u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::B8G8R8A8_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.498039216f,
+ 0.498039216f,
+ 0.498039216f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f));
+
+ texView = createTexView(device, size, gfx::Format::B8G8R8A8_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.498039216f,
+ 0.498039216f,
+ 0.498039216f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f));
+
+ texView = createTexView(device, size, gfx::Format::B8G8R8A8_UNORM_SRGB, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.211914062f,
+ 0.211914062f,
+ 0.211914062f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f));
+ }
+
+ {
+ int16_t texData[] =
+ {32767, 0, 0, 32767, 0, 32767, 0, 32767, 0, 0, 32767, 32767, -32768, -32768, 0, 32767};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_SNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ -1.0f,
+ -1.0f,
+ 0.0f,
+ 1.0f));
+ }
+
+ {
+ int16_t texData[] = {32767, 0, 0, 32767, 32767, 32767, -32768, -32768};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16G16_SNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f));
+ }
+
+ {
+ int16_t texData[] = {32767, 0, -32768, 0};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R16_SNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, -1.0f, 0.0f));
+ }
+
+ {
+ int8_t texData[] = {127, 0, 0, 127, 0, 127, 0, 127, 0, 0, 127, 127, -128, -128, 0, 127};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8G8B8A8_SNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ -1.0f,
+ -1.0f,
+ 0.0f,
+ 1.0f));
+ }
+
+ {
+ int8_t texData[] = {127, 0, 0, 127, 127, 127, -128, -128};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8G8_SNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f));
+ }
+
+ {
+ int8_t texData[] = {127, 0, -128, 0};
+ ITextureResource::SubresourceData subData = {(void*)texData, 2, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R8_SNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 0.0f, -1.0f, 0.0f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces unsupported format warnings for this
+ // test.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] = {15u, 240u, 240u, 240u, 0u, 255u, 119u, 119u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::B4G4R4A4_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.466666669f,
+ 0.466666669f,
+ 0.466666669f,
+ 0.466666669f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint16_t texData[] = {31u, 2016u, 63488u, 31727u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 4, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::B5G6R5_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.482352942f,
+ 0.490196079f,
+ 0.482352942f));
+
+ texView = createTexView(device, size, gfx::Format::B5G5R5A1_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0313725509f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.968627453f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.968627453f,
+ 1.0f,
+ 0.482352942f,
+ 0.0f));
+ }
+
+ {
+ uint32_t texData[] = {2950951416u, 2013265920u, 3086219772u, 3087007228u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R9G9B9E5_SHAREDEXP, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 63.0f,
+ 63.0f,
+ 63.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 127.0f,
+ 127.0f,
+ 127.0f,
+ 127.0f,
+ 127.5f,
+ 127.75f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint32_t texData[] = {4294967295u, 0u, 2683829759u, 1193046471u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R10G10B10A2_TYPELESS, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(
+ 1023u,
+ 1023u,
+ 1023u,
+ 3u,
+ 0u,
+ 0u,
+ 0u,
+ 0u,
+ 511u,
+ 511u,
+ 511u,
+ 2u,
+ 455u,
+ 796u,
+ 113u,
+ 1u));
+
+ texView = createTexView(device, size, gfx::Format::R10G10B10A2_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.499511242f,
+ 0.499511242f,
+ 0.499511242f,
+ 0.666666687f,
+ 0.444770277f,
+ 0.778103590f,
+ 0.110459432f,
+ 0.333333343f));
+
+ texView = createTexView(device, size, gfx::Format::R10G10B10A2_UINT, &subData);
+ setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
+ compareComputeResult(
+ device,
+ uintResults,
+ Slang::makeArray<uint32_t>(
+ 1023u,
+ 1023u,
+ 1023u,
+ 3u,
+ 0u,
+ 0u,
+ 0u,
+ 0u,
+ 511u,
+ 511u,
+ 511u,
+ 2u,
+ 455u,
+ 796u,
+ 113u,
+ 1u));
+ }
+
+ {
+ uint32_t texData[] = {3085827519u, 0u, 2951478655u, 1880884096u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, size, gfx::Format::R11G11B10_FLOAT, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 254.0f,
+ 254.0f,
+ 252.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 127.0f,
+ 127.0f,
+ 126.0f,
+ 0.5f,
+ 0.5f,
+ 0.5f));
+ }
+
+ // These BC1 tests also check that mipmaps are working correctly for compressed formats.
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] = {16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 16u, 0u, 0u, 0u, 0u, 0u,
+ 0u, 0u, 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 16u, 0u, 0u, 0u,
+ 0u, 0u, 0u, 0u, 255u, 255u, 255u, 255u, 0u, 0u, 0u, 0u};
+ ITextureResource::SubresourceData subData[] = {
+ ITextureResource::SubresourceData{(void*)texData, 16, 32},
+ ITextureResource::SubresourceData{(void*)(texData + 32), 8, 0}};
ITextureResource::Extents size = {};
- size.width = 2;
- size.height = 2;
+ size.width = 8;
+ size.height = 8;
size.depth = 1;
- ITextureResource::Extents bcSize = {};
- bcSize.width = 4;
- bcSize.height = 4;
- bcSize.depth = 1;
-
- // Note: D32_FLOAT and D16_UNORM are not directly tested as they are only used for raster. These
- // are the same as R32_FLOAT and R16_UNORM, respectively, when passed to a shader.
- {
- float texData[] = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f };
- ITextureResource::SubresourceData subData = { (void*)texData, 32, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32B32A32_FLOAT, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f));
-
- texView = createTexView(device, size, gfx::Format::R32G32B32A32_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f));
- }
-
- // Ignore this test since it is not supported by swiftshader and nvidia's driver.
- if (false)
- {
- float texData[] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f };
- ITextureResource::SubresourceData subData = { (void*)texData, 24, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32B32_FLOAT, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f));
-
- texView = createTexView(device, size, gfx::Format::R32G32B32_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
- 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f));
- }
-
- {
- float texData[] = { 1.0f, 0.0f, 0.0f, 1.0f,
- 1.0f, 1.0f, 0.5f, 0.5f };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32_FLOAT, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f,
- 1.0f, 1.0f, 0.5f, 0.5f));
-
- texView = createTexView(device, size, gfx::Format::R32G32_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f,
- 1.0f, 1.0f, 0.5f, 0.5f));
- }
-
- {
- float texData[] = { 1.0f, 0.0f, 0.5f, 0.25f };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32_FLOAT, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.5f, 0.25f));
-
- texView = createTexView(device, size, gfx::Format::R32_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.5f, 0.25f));
- }
-
- {
- uint16_t texData[] = { 15360u, 0u, 0u, 15360u, 0u, 15360u, 0u, 15360u,
- 0u, 0u, 15360u, 15360u, 14336u, 14336u, 14336u, 15360u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_FLOAT, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f));
-
- texView = createTexView(device, size, gfx::Format::R16G16B16A16_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f));
- }
-
- {
- uint16_t texData[] = { 15360u, 0u, 0u, 15360u,
- 15360u, 15360u, 14336u, 14336u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16_FLOAT, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f,
- 1.0f, 1.0f, 0.5f, 0.5f));
-
- texView = createTexView(device, size, gfx::Format::R16G16_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f,
- 1.0f, 1.0f, 0.5f, 0.5f));
- }
-
- {
- uint16_t texData[] = { 15360u, 0u, 14336u, 13312u };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16_FLOAT, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.5f, 0.25f));
-
- texView = createTexView(device, size, gfx::Format::R16_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.5f, 0.25f));
- }
-
- {
- uint32_t texData[] = { 255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u,
- 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u };
- ITextureResource::SubresourceData subData = { (void*)texData, 32, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32B32A32_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u,
- 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u));
- }
-
- // Ignore this test since validation layer reports that it is unsupported.
- if (false)
- {
- uint32_t texData[] = { 255u, 0u, 0u, 0u, 255u, 0u,
- 0u, 0u, 255u, 127u, 127u, 127u };
- ITextureResource::SubresourceData subData = { (void*)texData, 24, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32B32_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint3");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 0u, 0u, 255u, 0u,
- 0u, 0u, 255u, 127u, 127u, 127u));
- }
-
- {
- uint32_t texData[] = { 255u, 0u, 0u, 255u,
- 255u, 255u, 127u, 127u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint2");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u,
- 255u, 255u, 127u, 127u));
- }
-
- {
- uint32_t texData[] = { 255u, 0u, 127u, 73u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 127u, 73u));
- }
-
- {
- uint16_t texData[] = { 255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u,
- 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u,
- 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u));
- }
-
- {
- uint16_t texData[] = { 255u, 0u, 0u, 255u,
- 255u, 255u, 127u, 127u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint2");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u,
- 255u, 255u, 127u, 127u));
- }
-
- {
- uint16_t texData[] = { 255u, 0u, 127u, 73u };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 127u, 73u));
- }
-
- {
- uint8_t texData[] = { 255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u,
- 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8G8B8A8_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u, 0u, 255u, 0u, 255u,
- 0u, 0u, 255u, 255u, 127u, 127u, 127u, 255u));
- }
-
- {
- uint8_t texData[] = { 255u, 0u, 0u, 255u,
- 255u, 255u, 127u, 127u };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8G8_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint2");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 0u, 255u,
- 255u, 255u, 127u, 127u));
- }
-
- {
- uint8_t texData[] = { 255u, 0u, 127u, 73u };
- ITextureResource::SubresourceData subData = { (void*)texData, 2, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(255u, 0u, 127u, 73u));
- }
-
- {
- int32_t texData[] = { 255, 0, 0, 255, 0, 255, 0, 255,
- 0, 0, 255, 255, 127, 127, 127, 255 };
- ITextureResource::SubresourceData subData = { (void*)texData, 32, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32B32A32_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt4");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(255, 0, 0, 255, 0, 255, 0, 255,
- 0, 0, 255, 255, 127, 127, 127, 255));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces unsupported format warnings for this test.
- if (false)
- {
- int32_t texData[] = { 255, 0, 0, 0, 255, 0,
- 0, 0, 255, 127, 127, 127 };
- ITextureResource::SubresourceData subData = { (void*)texData, 24, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32B32_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt3");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(255, 0, 0, 0, 255, 0,
- 0, 0, 255, 127, 127, 127));
- }
-
- {
- int32_t texData[] = { 255, 0, 0, 255,
- 255, 255, 127, 127 };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32G32_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt2");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(255, 0, 0, 255,
- 255, 255, 127, 127));
- }
-
- {
- int32_t texData[] = { 255, 0, 127, 73 };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R32_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(255, 0, 127, 73));
- }
-
- {
- int16_t texData[] = { 255, 0, 0, 255, 0, 255, 0, 255,
- 0, 0, 255, 255, 127, 127, 127, 255 };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt4");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(255, 0, 0, 255, 0, 255, 0, 255,
- 0, 0, 255, 255, 127, 127, 127, 255));
- }
-
- {
- int16_t texData[] = { 255, 0, 0, 255,
- 255, 255, 127, 127 };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt2");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(255, 0, 0, 255,
- 255, 255, 127, 127));
- }
-
- {
- int16_t texData[] = { 255, 0, 127, 73 };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(255, 0, 127, 73));
- }
-
- {
- int8_t texData[] = { 127, 0, 0, 127, 0, 127, 0, 127,
- 0, 0, 127, 127, 0, 0, 0, 127 };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8G8B8A8_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt4");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(127, 0, 0, 127, 0, 127, 0, 127,
- 0, 0, 127, 127, 0, 0, 0, 127));
- }
-
- {
- int8_t texData[] = { 127, 0, 0, 127,
- 127, 127, 73, 73 };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8G8_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt2");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(127, 0, 0, 127,
- 127, 127, 73, 73));
- }
-
- {
- int8_t texData[] = { 127, 0, 73, 25 };
- ITextureResource::SubresourceData subData = { (void*)texData, 2, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8_SINT, &subData);
- setUpAndRunTest(device, texView, intBufferView, "copyTexInt");
- compareComputeResult(
- device,
- intResults,
- Slang::makeArray<int32_t>(127, 0, 73, 25));
- }
-
- {
- uint16_t texData[] = { 65535u, 0u, 0u, 65535u, 0u, 65535u, 0u, 65535u,
- 0u, 0u, 65535u, 65535u, 32767u, 32767u, 32767u, 32767u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.499992371f, 0.499992371f, 0.499992371f, 0.499992371f));
- }
-
- {
- uint16_t texData[] = { 65535u, 0u, 0u, 65535u,
- 65535u, 65535u, 32767u, 32767u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f,
- 1.0f, 1.0f, 0.499992371f, 0.499992371f));
- }
-
- {
- uint16_t texData[] = { 65535u, 0u, 32767u, 16383u };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.499992371f, 0.249988556f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 0u, 0u, 0u, 255u, 127u, 127u, 127u, 255u,
- 255u, 255u, 255u, 255u, 0u, 0u, 0u, 0u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0};
-
- auto texView = createTexView(device, size, gfx::Format::R8G8B8A8_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.0f, 1.0f, 0.498039216f, 0.498039216f, 0.498039216f, 1.0f,
- 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f));
-
- texView = createTexView(device, size, gfx::Format::R8G8B8A8_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.0f, 1.0f, 0.498039216f, 0.498039216f, 0.498039216f, 1.0f,
- 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f));
-
- texView = createTexView(device, size, gfx::Format::R8G8B8A8_UNORM_SRGB, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.0f, 1.0f, 0.211914062f, 0.211914062f, 0.211914062f,
- 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 255u, 0u, 0u, 255u, 255u, 255u, 127u, 127u };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8G8_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.498039216f, 0.498039216f));
-
- texView = createTexView(device, size, gfx::Format::R8G8_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.498039216f, 0.498039216f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 255u, 0u, 127u, 63u };
- ITextureResource::SubresourceData subData = { (void*)texData, 2, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.498039216f, 0.247058824f));
-
- texView = createTexView(device, size, gfx::Format::R8_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.498039216f, 0.247058824f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 0u, 0u, 0u, 255u, 127u, 127u, 127u, 255u,
- 255u, 255u, 255u, 255u, 0u, 0u, 0u, 0u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::B8G8R8A8_TYPELESS, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.0f, 1.0f, 0.498039216f, 0.498039216f, 0.498039216f, 1.0f,
- 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f));
-
- texView = createTexView(device, size, gfx::Format::B8G8R8A8_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.0f, 1.0f, 0.498039216f, 0.498039216f, 0.498039216f, 1.0f,
- 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f));
-
- texView = createTexView(device, size, gfx::Format::B8G8R8A8_UNORM_SRGB, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.0f, 1.0f, 0.211914062f, 0.211914062f, 0.211914062f,
- 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f));
- }
-
- {
- int16_t texData[] = { 32767, 0, 0, 32767, 0, 32767, 0, 32767,
- 0, 0, 32767, 32767, -32768, -32768, 0, 32767 };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16B16A16_SNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f));
- }
-
- {
- int16_t texData[] = { 32767, 0, 0, 32767,
- 32767, 32767, -32768, -32768 };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16G16_SNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f));
- }
-
- {
- int16_t texData[] = { 32767, 0, -32768, 0};
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R16_SNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, -1.0f, 0.0f));
- }
-
- {
- int8_t texData[] = { 127, 0, 0, 127, 0, 127, 0, 127,
- 0, 0, 127, 127, -128, -128, 0, 127 };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8G8B8A8_SNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f));
- }
-
- {
- int8_t texData[] = { 127, 0, 0, 127,
- 127, 127, -128, -128 };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8G8_SNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat2");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f));
- }
-
- {
- int8_t texData[] = { 127, 0, -128, 0 };
- ITextureResource::SubresourceData subData = { (void*)texData, 2, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R8_SNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, -1.0f, 0.0f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces unsupported format warnings for this test.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 15u, 240u, 240u, 240u, 0u, 255u, 119u, 119u };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::B4G4R4A4_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 1.0f, 0.0f, 0.0f, 1.0f, 0.466666669f, 0.466666669f, 0.466666669f, 0.466666669f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint16_t texData[] = { 31u, 2016u, 63488u, 31727u };
- ITextureResource::SubresourceData subData = { (void*)texData, 4, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::B5G6R5_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
- 1.0f, 0.0f, 0.0f, 0.482352942f, 0.490196079f, 0.482352942f));
-
- texView = createTexView(device, size, gfx::Format::B5G5R5A1_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 1.0f, 0.0f, 0.0313725509f, 1.0f, 0.0f, 0.0f,
- 0.968627453f, 0.0f, 0.0f, 1.0f, 0.968627453f, 1.0f, 0.482352942f, 0.0f));
- }
-
- {
- uint32_t texData[] = { 2950951416u, 2013265920u, 3086219772u, 3087007228u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R9G9B9E5_SHAREDEXP, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(63.0f, 63.0f, 63.0f, 0.0f, 0.0f, 0.0f,
- 127.0f, 127.0f, 127.0f, 127.0f, 127.5f, 127.75f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint32_t texData[] = { 4294967295u, 0u, 2683829759u, 1193046471u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R10G10B10A2_TYPELESS, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(1023u, 1023u, 1023u, 3u, 0u, 0u, 0u, 0u,
- 511u, 511u, 511u, 2u, 455u, 796u, 113u, 1u));
-
- texView = createTexView(device, size, gfx::Format::R10G10B10A2_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
- 0.499511242f, 0.499511242f, 0.499511242f, 0.666666687f,
- 0.444770277f, 0.778103590f, 0.110459432f, 0.333333343f));
-
- texView = createTexView(device, size, gfx::Format::R10G10B10A2_UINT, &subData);
- setUpAndRunTest(device, texView, uintBufferView, "copyTexUint4");
- compareComputeResult(
- device,
- uintResults,
- Slang::makeArray<uint32_t>(1023u, 1023u, 1023u, 3u, 0u, 0u, 0u, 0u,
- 511u, 511u, 511u, 2u, 455u, 796u, 113u, 1u));
- }
-
- {
- uint32_t texData[] = { 3085827519u, 0u, 2951478655u, 1880884096u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, size, gfx::Format::R11G11B10_FLOAT, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "copyTexFloat3");
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(254.0f, 254.0f, 252.0f, 0.0f, 0.0f, 0.0f, 127.0f, 127.0f, 126.0f, 0.5f, 0.5f, 0.5f));
- }
-
- // These BC1 tests also check that mipmaps are working correctly for compressed formats.
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
- 255u, 255u, 255u, 255u, 0u, 0u, 0u, 0u };
- ITextureResource::SubresourceData subData[] = {
- ITextureResource::SubresourceData {(void*)texData, 16, 32},
- ITextureResource::SubresourceData {(void*)(texData + 32), 8, 0}
- };
- ITextureResource::Extents size = {};
- size.width = 8;
- size.height = 8;
- size.depth = 1;
-
- auto texView = createTexView(device, size, gfx::Format::BC1_UNORM, subData, 2);
- setUpAndRunTest(device, texView, floatBufferView, "sampleMips", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.517647088f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f));
-
- texView = createTexView(device, size, gfx::Format::BC1_UNORM_SRGB, subData, 2);
- setUpAndRunTest(device, texView, floatBufferView, "sampleMips", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.230468750f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 255u, 255u, 255u, 255u, 255u, 255u, 255u, 255u,
- 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, bcSize, gfx::Format::BC2_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.517647088f, 1.0f));
-
- texView = createTexView(device, bcSize, gfx::Format::BC2_UNORM_SRGB, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.230468750f, 1.0f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 0u, 255u, 255u, 255u, 255u, 255u, 255u, 255u,
- 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, bcSize, gfx::Format::BC3_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.517647088f, 1.0f));
-
- texView = createTexView(device, bcSize, gfx::Format::BC3_UNORM_SRGB, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0f, 0.230468750f, 1.0f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 127u, 0u, 0u, 0u, 0u, 0u, 0u, 0u };
- ITextureResource::SubresourceData subData = { (void*)texData, 8, 0 };
-
- auto texView = createTexView(device, bcSize, gfx::Format::BC4_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.498039216f, 0.0f, 0.0f, 1.0f));
-
- texView = createTexView(device, bcSize, gfx::Format::BC4_SNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 127u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 127u, 0u, 0u, 0u, 0u, 0u, 0u, 0u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, bcSize, gfx::Format::BC5_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.498039216f, 0.498039216f, 0.0f, 1.0f, 0.498039216f, 0.498039216f, 0.0f, 1.0f));
-
- texView = createTexView(device, bcSize, gfx::Format::BC5_SNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f));
- }
-
- // BC6H_UF16 and BC6H_SF16 are tested separately due to requiring different texture data.
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 98u, 238u, 232u, 77u, 240u, 66u, 148u, 31u,
- 124u, 95u, 2u, 224u, 255u, 107u, 77u, 250u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, bcSize, gfx::Format::BC6H_UF16, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.336669922f, 0.911132812f, 2.13867188f, 1.0f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 107u, 238u, 232u, 77u, 240u, 71u, 128u, 127u,
- 1u, 0u, 255u, 255u, 170u, 218u, 221u, 254u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, bcSize, gfx::Format::BC6H_SF16, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.336914062f, 0.910644531f, 2.14062500f, 1.0f));
- }
-
- // Ignore this test on swiftshader. Swiftshader produces different results than expected.
- if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- uint8_t texData[] = { 104u, 0u, 0u, 0u, 64u, 163u, 209u, 104u,
- 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u };
- ITextureResource::SubresourceData subData = { (void*)texData, 16, 0 };
-
- auto texView = createTexView(device, bcSize, gfx::Format::BC7_UNORM, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.101960786f, 0.0f, 1.0f));
-
- texView = createTexView(device, bcSize, gfx::Format::BC7_UNORM_SRGB, &subData);
- setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
- compareComputeResult(
- device,
- floatResults,
- Slang::makeArray<float>(0.0f, 0.0103149414f, 0.0f, 1.0f));
- }
+ auto texView = createTexView(device, size, gfx::Format::BC1_UNORM, subData, 2);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleMips", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.0f, 0.0f, 0.517647088f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f));
+
+ texView = createTexView(device, size, gfx::Format::BC1_UNORM_SRGB, subData, 2);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleMips", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.0f, 0.0f, 0.230468750f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f));
}
- SLANG_UNIT_TEST(FormatTestsD3D11)
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
{
- runTestImpl(formatTestsImpl, unitTestContext, Slang::RenderApiFlag::D3D11);
+ uint8_t texData[] =
+ {255u, 255u, 255u, 255u, 255u, 255u, 255u, 255u, 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, bcSize, gfx::Format::BC2_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.0f, 0.0f, 0.517647088f, 1.0f));
+
+ texView = createTexView(device, bcSize, gfx::Format::BC2_UNORM_SRGB, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.0f, 0.0f, 0.230468750f, 1.0f));
}
-#if SLANG_WINDOWS_FAMILY
- SLANG_UNIT_TEST(FormatTestsD3D12)
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
{
- runTestImpl(formatTestsImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+ uint8_t texData[] =
+ {0u, 255u, 255u, 255u, 255u, 255u, 255u, 255u, 16u, 0u, 0u, 0u, 0u, 0u, 0u, 0u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, bcSize, gfx::Format::BC3_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.0f, 0.0f, 0.517647088f, 1.0f));
+
+ texView = createTexView(device, bcSize, gfx::Format::BC3_UNORM_SRGB, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.0f, 0.0f, 0.230468750f, 1.0f));
}
-#endif
- SLANG_UNIT_TEST(FormatTestsVulkan)
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
{
- runTestImpl(formatTestsImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ uint8_t texData[] = {127u, 0u, 0u, 0u, 0u, 0u, 0u, 0u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 8, 0};
+
+ auto texView = createTexView(device, bcSize, gfx::Format::BC4_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.498039216f, 0.0f, 0.0f, 1.0f));
+
+ texView = createTexView(device, bcSize, gfx::Format::BC4_SNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(device, floatResults, Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f));
}
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] = {127u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 127u, 0u, 0u, 0u, 0u, 0u, 0u, 0u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, bcSize, gfx::Format::BC5_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(
+ 0.498039216f,
+ 0.498039216f,
+ 0.0f,
+ 1.0f,
+ 0.498039216f,
+ 0.498039216f,
+ 0.0f,
+ 1.0f));
+
+ texView = createTexView(device, bcSize, gfx::Format::BC5_SNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f));
+ }
+
+ // BC6H_UF16 and BC6H_SF16 are tested separately due to requiring different texture data.
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] = {
+ 98u,
+ 238u,
+ 232u,
+ 77u,
+ 240u,
+ 66u,
+ 148u,
+ 31u,
+ 124u,
+ 95u,
+ 2u,
+ 224u,
+ 255u,
+ 107u,
+ 77u,
+ 250u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, bcSize, gfx::Format::BC6H_UF16, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.336669922f, 0.911132812f, 2.13867188f, 1.0f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] = {
+ 107u,
+ 238u,
+ 232u,
+ 77u,
+ 240u,
+ 71u,
+ 128u,
+ 127u,
+ 1u,
+ 0u,
+ 255u,
+ 255u,
+ 170u,
+ 218u,
+ 221u,
+ 254u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, bcSize, gfx::Format::BC6H_SF16, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.336914062f, 0.910644531f, 2.14062500f, 1.0f));
+ }
+
+ // Ignore this test on swiftshader. Swiftshader produces different results than expected.
+ if (!Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
+ {
+ uint8_t texData[] =
+ {104u, 0u, 0u, 0u, 64u, 163u, 209u, 104u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u};
+ ITextureResource::SubresourceData subData = {(void*)texData, 16, 0};
+
+ auto texView = createTexView(device, bcSize, gfx::Format::BC7_UNORM, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.0f, 0.101960786f, 0.0f, 1.0f));
+
+ texView = createTexView(device, bcSize, gfx::Format::BC7_UNORM_SRGB, &subData);
+ setUpAndRunTest(device, texView, floatBufferView, "sampleTex", sampler);
+ compareComputeResult(
+ device,
+ floatResults,
+ Slang::makeArray<float>(0.0f, 0.0103149414f, 0.0f, 1.0f));
+ }
}
+
+SLANG_UNIT_TEST(FormatTestsD3D11)
+{
+ runTestImpl(formatTestsImpl, unitTestContext, Slang::RenderApiFlag::D3D11);
+}
+
+#if SLANG_WINDOWS_FAMILY
+SLANG_UNIT_TEST(FormatTestsD3D12)
+{
+ runTestImpl(formatTestsImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+#endif
+
+SLANG_UNIT_TEST(FormatTestsVulkan)
+{
+ runTestImpl(formatTestsImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/get-buffer-resource-handle-test.cpp b/tools/gfx-unit-test/get-buffer-resource-handle-test.cpp
index 36b6b3cad..a143ac135 100644
--- a/tools/gfx-unit-test/get-buffer-resource-handle-test.cpp
+++ b/tools/gfx-unit-test/get-buffer-resource-handle-test.cpp
@@ -1,9 +1,8 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
@@ -13,97 +12,87 @@ using namespace gfx;
namespace gfx_test
{
- void getBufferResourceHandleTestImpl(IDevice* device, UnitTestContext* context)
- {
- const int numberCount = 1;
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
+void getBufferResourceHandleTestImpl(IDevice* device, UnitTestContext* context)
+{
+ const int numberCount = 1;
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
- ComPtr<IBufferResource> buffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- nullptr,
- buffer.writeRef()));
+ ComPtr<IBufferResource> buffer;
+ GFX_CHECK_CALL_ABORT(device->createBufferResource(bufferDesc, nullptr, buffer.writeRef()));
- InteropHandle handle;
- GFX_CHECK_CALL_ABORT(buffer->getNativeResourceHandle(&handle));
- if (device->getDeviceInfo().deviceType == gfx::DeviceType::Vulkan)
- {
- SLANG_CHECK(handle.handleValue != 0);
- SLANG_CHECK(handle.api == InteropHandleAPI::Vulkan);
- }
+ InteropHandle handle;
+ GFX_CHECK_CALL_ABORT(buffer->getNativeResourceHandle(&handle));
+ if (device->getDeviceInfo().deviceType == gfx::DeviceType::Vulkan)
+ {
+ SLANG_CHECK(handle.handleValue != 0);
+ SLANG_CHECK(handle.api == InteropHandleAPI::Vulkan);
+ }
#if SLANG_WINDOWS_FAMILY
- else
- {
- SLANG_CHECK(handle.api == InteropHandleAPI::D3D12);
- auto d3d12Handle = (ID3D12Resource*)handle.handleValue;
- Slang::ComPtr<IUnknown> testHandle1;
- GFX_CHECK_CALL_ABORT(d3d12Handle->QueryInterface<IUnknown>(testHandle1.writeRef()));
- Slang::ComPtr<ID3D12Resource> testHandle2;
- GFX_CHECK_CALL_ABORT(testHandle1->QueryInterface<ID3D12Resource>(testHandle2.writeRef()));
- SLANG_CHECK(d3d12Handle == testHandle2.get());
- }
-#endif
+ else
+ {
+ SLANG_CHECK(handle.api == InteropHandleAPI::D3D12);
+ auto d3d12Handle = (ID3D12Resource*)handle.handleValue;
+ Slang::ComPtr<IUnknown> testHandle1;
+ GFX_CHECK_CALL_ABORT(d3d12Handle->QueryInterface<IUnknown>(testHandle1.writeRef()));
+ Slang::ComPtr<ID3D12Resource> testHandle2;
+ GFX_CHECK_CALL_ABORT(testHandle1->QueryInterface<ID3D12Resource>(testHandle2.writeRef()));
+ SLANG_CHECK(d3d12Handle == testHandle2.get());
}
+#endif
+}
- void getBufferResourceHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+void getBufferResourceHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+{
+ if ((api & context->enabledApis) == 0)
{
- if ((api & context->enabledApis) == 0)
- {
- SLANG_IGNORE_TEST;
- }
- Slang::ComPtr<IDevice> device;
- IDevice::Desc deviceDesc = {};
- switch (api)
- {
- case Slang::RenderApiFlag::D3D11:
- deviceDesc.deviceType = gfx::DeviceType::DirectX11;
- break;
- case Slang::RenderApiFlag::D3D12:
- deviceDesc.deviceType = gfx::DeviceType::DirectX12;
- break;
- case Slang::RenderApiFlag::Vulkan:
- deviceDesc.deviceType = gfx::DeviceType::Vulkan;
- break;
- default:
- SLANG_IGNORE_TEST;
- }
- deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
- const char* searchPaths[] = { "", "../../tools/gfx-unit-test", "tools/gfx-unit-test" };
- deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
- deviceDesc.slang.searchPaths = searchPaths;
- auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
- if (SLANG_FAILED(createDeviceResult))
- {
- SLANG_IGNORE_TEST;
- }
- // Ignore this test on swiftshader. Swiftshader seems to have a bug that causes the test
- // to crash.
- if (Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- SLANG_IGNORE_TEST;
- }
-
- getBufferResourceHandleTestImpl(device, context);
+ SLANG_IGNORE_TEST;
}
-
- SLANG_UNIT_TEST(getBufferResourceHandleD3D12)
+ Slang::ComPtr<IDevice> device;
+ IDevice::Desc deviceDesc = {};
+ switch (api)
{
- return getBufferResourceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+ case Slang::RenderApiFlag::D3D11: deviceDesc.deviceType = gfx::DeviceType::DirectX11; break;
+ case Slang::RenderApiFlag::D3D12: deviceDesc.deviceType = gfx::DeviceType::DirectX12; break;
+ case Slang::RenderApiFlag::Vulkan: deviceDesc.deviceType = gfx::DeviceType::Vulkan; break;
+ default: SLANG_IGNORE_TEST;
}
-
- SLANG_UNIT_TEST(getBufferResourceHandleVulkan)
+ deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
+ const char* searchPaths[] = {"", "../../tools/gfx-unit-test", "tools/gfx-unit-test"};
+ deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
+ deviceDesc.slang.searchPaths = searchPaths;
+ auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
+ if (SLANG_FAILED(createDeviceResult))
+ {
+ SLANG_IGNORE_TEST;
+ }
+ // Ignore this test on swiftshader. Swiftshader seems to have a bug that causes the test
+ // to crash.
+ if (Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
{
- return getBufferResourceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ SLANG_IGNORE_TEST;
}
+ getBufferResourceHandleTestImpl(device, context);
}
+
+SLANG_UNIT_TEST(getBufferResourceHandleD3D12)
+{
+ return getBufferResourceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(getBufferResourceHandleVulkan)
+{
+ return getBufferResourceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/get-cmd-buffer-handle-test.cpp b/tools/gfx-unit-test/get-cmd-buffer-handle-test.cpp
index 120c331ed..cd9a401f7 100644
--- a/tools/gfx-unit-test/get-cmd-buffer-handle-test.cpp
+++ b/tools/gfx-unit-test/get-cmd-buffer-handle-test.cpp
@@ -1,9 +1,8 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
@@ -13,93 +12,84 @@ using namespace gfx;
namespace gfx_test
{
- void getBufferHandleTestImpl(IDevice* device, UnitTestContext* context)
- {
- // We need to create a transient heap in order to create a command buffer.
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- struct CloseComandBufferRAII
- {
- ICommandBuffer* m_commandBuffer;
- ~CloseComandBufferRAII()
- {
- m_commandBuffer->close();
- }
- } closeCommandBufferRAII{ commandBuffer };
- InteropHandle handle = {};
- GFX_CHECK_CALL_ABORT(commandBuffer->getNativeHandle(&handle));
- if (device->getDeviceInfo().deviceType == gfx::DeviceType::Vulkan)
- {
- SLANG_CHECK(handle.handleValue != 0);
- }
-#if SLANG_WINDOWS_FAMILY
- else
- {
- auto d3d12Handle = (ID3D12GraphicsCommandList*)handle.handleValue;
- Slang::ComPtr<IUnknown> testHandle1;
- GFX_CHECK_CALL_ABORT(d3d12Handle->QueryInterface<IUnknown>(testHandle1.writeRef()));
- Slang::ComPtr<ID3D12GraphicsCommandList> testHandle2;
- GFX_CHECK_CALL_ABORT(d3d12Handle->QueryInterface<ID3D12GraphicsCommandList>(testHandle2.writeRef()));
- SLANG_CHECK(d3d12Handle == testHandle2.get());
- }
-#endif
- }
+void getBufferHandleTestImpl(IDevice* device, UnitTestContext* context)
+{
+ // We need to create a transient heap in order to create a command buffer.
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
- void getBufferHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ struct CloseComandBufferRAII
+ {
+ ICommandBuffer* m_commandBuffer;
+ ~CloseComandBufferRAII() { m_commandBuffer->close(); }
+ } closeCommandBufferRAII{commandBuffer};
+ InteropHandle handle = {};
+ GFX_CHECK_CALL_ABORT(commandBuffer->getNativeHandle(&handle));
+ if (device->getDeviceInfo().deviceType == gfx::DeviceType::Vulkan)
{
- if ((api & context->enabledApis) == 0)
- {
- SLANG_IGNORE_TEST;
- }
- Slang::ComPtr<IDevice> device;
- IDevice::Desc deviceDesc = {};
- switch (api)
- {
- case Slang::RenderApiFlag::D3D11:
- deviceDesc.deviceType = gfx::DeviceType::DirectX11;
- break;
- case Slang::RenderApiFlag::D3D12:
- deviceDesc.deviceType = gfx::DeviceType::DirectX12;
- break;
- case Slang::RenderApiFlag::Vulkan:
- deviceDesc.deviceType = gfx::DeviceType::Vulkan;
- break;
- default:
- SLANG_IGNORE_TEST;
- }
- deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
- const char* searchPaths[] = { "", "../../tools/gfx-unit-test", "tools/gfx-unit-test" };
- deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
- deviceDesc.slang.searchPaths = searchPaths;
- auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
- if (SLANG_FAILED(createDeviceResult))
- {
- SLANG_IGNORE_TEST;
- }
- // Ignore this test on swiftshader. Swiftshader seems to have a bug that causes the test
- // to crash.
- if (Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- SLANG_IGNORE_TEST;
- }
- getBufferHandleTestImpl(device, context);
+ SLANG_CHECK(handle.handleValue != 0);
}
-
#if SLANG_WINDOWS_FAMILY
- SLANG_UNIT_TEST(getCmdBufferHandleD3D12)
+ else
{
- return getBufferHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+ auto d3d12Handle = (ID3D12GraphicsCommandList*)handle.handleValue;
+ Slang::ComPtr<IUnknown> testHandle1;
+ GFX_CHECK_CALL_ABORT(d3d12Handle->QueryInterface<IUnknown>(testHandle1.writeRef()));
+ Slang::ComPtr<ID3D12GraphicsCommandList> testHandle2;
+ GFX_CHECK_CALL_ABORT(
+ d3d12Handle->QueryInterface<ID3D12GraphicsCommandList>(testHandle2.writeRef()));
+ SLANG_CHECK(d3d12Handle == testHandle2.get());
}
#endif
+}
- SLANG_UNIT_TEST(getCmdBufferHandleVulkan)
+void getBufferHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+{
+ if ((api & context->enabledApis) == 0)
+ {
+ SLANG_IGNORE_TEST;
+ }
+ Slang::ComPtr<IDevice> device;
+ IDevice::Desc deviceDesc = {};
+ switch (api)
+ {
+ case Slang::RenderApiFlag::D3D11: deviceDesc.deviceType = gfx::DeviceType::DirectX11; break;
+ case Slang::RenderApiFlag::D3D12: deviceDesc.deviceType = gfx::DeviceType::DirectX12; break;
+ case Slang::RenderApiFlag::Vulkan: deviceDesc.deviceType = gfx::DeviceType::Vulkan; break;
+ default: SLANG_IGNORE_TEST;
+ }
+ deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
+ const char* searchPaths[] = {"", "../../tools/gfx-unit-test", "tools/gfx-unit-test"};
+ deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
+ deviceDesc.slang.searchPaths = searchPaths;
+ auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
+ if (SLANG_FAILED(createDeviceResult))
+ {
+ SLANG_IGNORE_TEST;
+ }
+ // Ignore this test on swiftshader. Swiftshader seems to have a bug that causes the test
+ // to crash.
+ if (Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
{
- return getBufferHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ SLANG_IGNORE_TEST;
}
+ getBufferHandleTestImpl(device, context);
+}
+
+#if SLANG_WINDOWS_FAMILY
+SLANG_UNIT_TEST(getCmdBufferHandleD3D12)
+{
+ return getBufferHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+#endif
+SLANG_UNIT_TEST(getCmdBufferHandleVulkan)
+{
+ return getBufferHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/get-cmd-queue-handle-test.cpp b/tools/gfx-unit-test/get-cmd-queue-handle-test.cpp
index e14729718..8e589a899 100644
--- a/tools/gfx-unit-test/get-cmd-queue-handle-test.cpp
+++ b/tools/gfx-unit-test/get-cmd-queue-handle-test.cpp
@@ -1,9 +1,8 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
@@ -13,77 +12,71 @@ using namespace gfx;
namespace gfx_test
{
- void getQueueHandleTestImpl(IDevice* device, UnitTestContext* context)
+void getQueueHandleTestImpl(IDevice* device, UnitTestContext* context)
+{
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+ InteropHandle handle;
+ GFX_CHECK_CALL_ABORT(queue->getNativeHandle(&handle));
+ if (device->getDeviceInfo().deviceType == gfx::DeviceType::Vulkan)
{
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
- InteropHandle handle;
- GFX_CHECK_CALL_ABORT(queue->getNativeHandle(&handle));
- if (device->getDeviceInfo().deviceType == gfx::DeviceType::Vulkan)
- {
- SLANG_CHECK(handle.handleValue != 0);
- }
+ SLANG_CHECK(handle.handleValue != 0);
+ }
#if SLANG_WINDOWS_FAMILY
- else
- {
- auto d3d12Queue = (ID3D12CommandQueue*)handle.handleValue;
- Slang::ComPtr<IUnknown> testHandle1;
- GFX_CHECK_CALL_ABORT(d3d12Queue->QueryInterface<IUnknown>(testHandle1.writeRef()));
- Slang::ComPtr<ID3D12CommandQueue> testHandle2;
- GFX_CHECK_CALL_ABORT(testHandle1->QueryInterface<ID3D12CommandQueue>(testHandle2.writeRef()));
- SLANG_CHECK(d3d12Queue == testHandle2.get());
- }
-#endif
+ else
+ {
+ auto d3d12Queue = (ID3D12CommandQueue*)handle.handleValue;
+ Slang::ComPtr<IUnknown> testHandle1;
+ GFX_CHECK_CALL_ABORT(d3d12Queue->QueryInterface<IUnknown>(testHandle1.writeRef()));
+ Slang::ComPtr<ID3D12CommandQueue> testHandle2;
+ GFX_CHECK_CALL_ABORT(
+ testHandle1->QueryInterface<ID3D12CommandQueue>(testHandle2.writeRef()));
+ SLANG_CHECK(d3d12Queue == testHandle2.get());
}
+#endif
+}
- void getQueueHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+void getQueueHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+{
+ if ((api & context->enabledApis) == 0)
{
- if ((api & context->enabledApis) == 0)
- {
- SLANG_IGNORE_TEST;
- }
- Slang::ComPtr<IDevice> device;
- IDevice::Desc deviceDesc = {};
- switch (api)
- {
- case Slang::RenderApiFlag::D3D11:
- deviceDesc.deviceType = gfx::DeviceType::DirectX11;
- break;
- case Slang::RenderApiFlag::D3D12:
- deviceDesc.deviceType = gfx::DeviceType::DirectX12;
- break;
- case Slang::RenderApiFlag::Vulkan:
- deviceDesc.deviceType = gfx::DeviceType::Vulkan;
- break;
- default:
- SLANG_IGNORE_TEST;
- }
- deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
- const char* searchPaths[] = { "", "../../tools/gfx-unit-test", "tools/gfx-unit-test" };
- deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
- deviceDesc.slang.searchPaths = searchPaths;
- auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
- if (SLANG_FAILED(createDeviceResult))
- {
- SLANG_IGNORE_TEST;
- }
- // Ignore this test on swiftshader. Swiftshader seems to have a bug that causes the test
- // to crash.
- if (Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- SLANG_IGNORE_TEST;
- }
- getQueueHandleTestImpl(device, context);
+ SLANG_IGNORE_TEST;
}
-
- SLANG_UNIT_TEST(getCmdQueueHandleD3D12)
+ Slang::ComPtr<IDevice> device;
+ IDevice::Desc deviceDesc = {};
+ switch (api)
{
- return getQueueHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+ case Slang::RenderApiFlag::D3D11: deviceDesc.deviceType = gfx::DeviceType::DirectX11; break;
+ case Slang::RenderApiFlag::D3D12: deviceDesc.deviceType = gfx::DeviceType::DirectX12; break;
+ case Slang::RenderApiFlag::Vulkan: deviceDesc.deviceType = gfx::DeviceType::Vulkan; break;
+ default: SLANG_IGNORE_TEST;
}
-
- SLANG_UNIT_TEST(getCmdQueueHandleVulkan)
+ deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
+ const char* searchPaths[] = {"", "../../tools/gfx-unit-test", "tools/gfx-unit-test"};
+ deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
+ deviceDesc.slang.searchPaths = searchPaths;
+ auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
+ if (SLANG_FAILED(createDeviceResult))
+ {
+ SLANG_IGNORE_TEST;
+ }
+ // Ignore this test on swiftshader. Swiftshader seems to have a bug that causes the test
+ // to crash.
+ if (Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
{
- return getQueueHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ SLANG_IGNORE_TEST;
}
+ getQueueHandleTestImpl(device, context);
+}
+
+SLANG_UNIT_TEST(getCmdQueueHandleD3D12)
+{
+ return getQueueHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+SLANG_UNIT_TEST(getCmdQueueHandleVulkan)
+{
+ return getQueueHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/get-supported-resource-states-test.cpp b/tools/gfx-unit-test/get-supported-resource-states-test.cpp
index fc7c57771..a3f331384 100644
--- a/tools/gfx-unit-test/get-supported-resource-states-test.cpp
+++ b/tools/gfx-unit-test/get-supported-resource-states-test.cpp
@@ -1,9 +1,8 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
@@ -14,195 +13,181 @@ using namespace gfx;
namespace
{
- using namespace gfx_test;
+using namespace gfx_test;
- struct GetSupportedResourceStatesBase
- {
- IDevice* device;
- UnitTestContext* context;
+struct GetSupportedResourceStatesBase
+{
+ IDevice* device;
+ UnitTestContext* context;
- ResourceStateSet formatSupportedStates;
- ResourceStateSet textureAllowedStates;
- ResourceStateSet bufferAllowedStates;
+ ResourceStateSet formatSupportedStates;
+ ResourceStateSet textureAllowedStates;
+ ResourceStateSet bufferAllowedStates;
- ComPtr<ITextureResource> texture;
- ComPtr<IBufferResource> buffer;
+ ComPtr<ITextureResource> texture;
+ ComPtr<IBufferResource> buffer;
- void init(IDevice* device, UnitTestContext* context)
- {
- this->device = device;
- this->context = context;
- }
+ void init(IDevice* device, UnitTestContext* context)
+ {
+ this->device = device;
+ this->context = context;
+ }
- Format convertTypelessFormat(Format format)
+ Format convertTypelessFormat(Format format)
+ {
+ switch (format)
{
- switch (format)
- {
- case Format::R32G32B32A32_TYPELESS:
- return Format::R32G32B32A32_FLOAT;
- case Format::R32G32B32_TYPELESS:
- return Format::R32G32B32_FLOAT;
- case Format::R32G32_TYPELESS:
- return Format::R32G32_FLOAT;
- case Format::R32_TYPELESS:
- return Format::R32_FLOAT;
- case Format::R16G16B16A16_TYPELESS:
- return Format::R16G16B16A16_FLOAT;
- case Format::R16G16_TYPELESS:
- return Format::R16G16_FLOAT;
- case Format::R16_TYPELESS:
- return Format::R16_FLOAT;
- case Format::R8G8B8A8_TYPELESS:
- return Format::R8G8B8A8_UNORM;
- case Format::R8G8_TYPELESS:
- return Format::R8G8_UNORM;
- case Format::R8_TYPELESS:
- return Format::R8_UNORM;
- case Format::B8G8R8A8_TYPELESS:
- return Format::B8G8R8A8_UNORM;
- case Format::R10G10B10A2_TYPELESS:
- return Format::R10G10B10A2_UINT;
- default:
- return Format::Unknown;
- }
+ case Format::R32G32B32A32_TYPELESS: return Format::R32G32B32A32_FLOAT;
+ case Format::R32G32B32_TYPELESS: return Format::R32G32B32_FLOAT;
+ case Format::R32G32_TYPELESS: return Format::R32G32_FLOAT;
+ case Format::R32_TYPELESS: return Format::R32_FLOAT;
+ case Format::R16G16B16A16_TYPELESS: return Format::R16G16B16A16_FLOAT;
+ case Format::R16G16_TYPELESS: return Format::R16G16_FLOAT;
+ case Format::R16_TYPELESS: return Format::R16_FLOAT;
+ case Format::R8G8B8A8_TYPELESS: return Format::R8G8B8A8_UNORM;
+ case Format::R8G8_TYPELESS: return Format::R8G8_UNORM;
+ case Format::R8_TYPELESS: return Format::R8_UNORM;
+ case Format::B8G8R8A8_TYPELESS: return Format::B8G8R8A8_UNORM;
+ case Format::R10G10B10A2_TYPELESS: return Format::R10G10B10A2_UINT;
+ default: return Format::Unknown;
}
+ }
- void transitionResourceStates(IDevice* device)
- {
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+ void transitionResourceStates(IDevice* device)
+ {
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeResourceCommands();
- ResourceState currentTextureState = texture->getDesc()->defaultState;
- ResourceState currentBufferState = buffer->getDesc()->defaultState;
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeResourceCommands();
+ ResourceState currentTextureState = texture->getDesc()->defaultState;
+ ResourceState currentBufferState = buffer->getDesc()->defaultState;
- for (uint32_t i = 0; i < (uint32_t)ResourceState::_Count; ++i)
+ for (uint32_t i = 0; i < (uint32_t)ResourceState::_Count; ++i)
+ {
+ auto nextState = (ResourceState)i;
+ if (formatSupportedStates.contains(nextState))
{
- auto nextState = (ResourceState)i;
- if (formatSupportedStates.contains(nextState))
+ if (bufferAllowedStates.contains(nextState))
+ {
+ encoder->bufferBarrier(buffer, currentBufferState, nextState);
+ currentBufferState = nextState;
+ }
+ if (textureAllowedStates.contains(nextState))
{
- if (bufferAllowedStates.contains(nextState))
- {
- encoder->bufferBarrier(buffer, currentBufferState, nextState);
- currentBufferState = nextState;
- }
- if (textureAllowedStates.contains(nextState))
- {
- encoder->textureBarrier(texture, currentTextureState, nextState);
- currentTextureState = nextState;
- }
+ encoder->textureBarrier(texture, currentTextureState, nextState);
+ currentTextureState = nextState;
}
}
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
}
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- void run()
+ void run()
+ {
+ // Skip Format::Unknown
+ for (uint32_t i = 1; i < (uint32_t)Format::_Count; ++i)
{
- // Skip Format::Unknown
- for (uint32_t i = 1; i < (uint32_t)Format::_Count; ++i)
- {
- auto baseFormat = (Format)i;
- FormatInfo info;
- gfxGetFormatInfo(baseFormat, &info);
- // Ignore 3-channel textures for now since validation layer seem to report unsupported errors there.
- if (info.channelCount == 3)
- continue;
-
- auto format = gfxIsTypelessFormat(baseFormat) ? convertTypelessFormat(baseFormat) : baseFormat;
- GFX_CHECK_CALL_ABORT(device->getFormatSupportedResourceStates(format, &formatSupportedStates));
-
- textureAllowedStates.add(
- ResourceState::RenderTarget,
- ResourceState::DepthRead,
- ResourceState::DepthWrite,
- ResourceState::Present,
- ResourceState::ResolveSource,
- ResourceState::ResolveDestination,
- ResourceState::Undefined,
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopySource,
- ResourceState::CopyDestination);
-
- bufferAllowedStates.add(
- ResourceState::VertexBuffer,
- ResourceState::IndexBuffer,
- ResourceState::ConstantBuffer,
- ResourceState::StreamOutput,
- ResourceState::IndirectArgument,
- ResourceState::AccelerationStructure,
- ResourceState::Undefined,
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopySource,
- ResourceState::CopyDestination);
-
- ResourceState currentState = ResourceState::CopySource;
- ITextureResource::Extents extent;
- extent.width = 4;
- extent.height = 4;
- extent.depth = 1;
-
- ITextureResource::Desc texDesc = {};
- texDesc.type = IResource::Type::Texture2D;
- texDesc.numMipLevels = 1;
- texDesc.arraySize = 1;
- texDesc.size = extent;
- texDesc.defaultState = currentState;
- texDesc.allowedStates = formatSupportedStates & textureAllowedStates;
- texDesc.memoryType = MemoryType::DeviceLocal;
- texDesc.format = format;
-
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- texDesc,
- nullptr,
- texture.writeRef()));
-
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = 256;
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = formatSupportedStates & bufferAllowedStates;
- bufferDesc.defaultState = currentState;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- nullptr,
- buffer.writeRef()));
-
- transitionResourceStates(device);
- }
- }
- };
+ auto baseFormat = (Format)i;
+ FormatInfo info;
+ gfxGetFormatInfo(baseFormat, &info);
+ // Ignore 3-channel textures for now since validation layer seem to report unsupported
+ // errors there.
+ if (info.channelCount == 3)
+ continue;
+
+ auto format =
+ gfxIsTypelessFormat(baseFormat) ? convertTypelessFormat(baseFormat) : baseFormat;
+ GFX_CHECK_CALL_ABORT(
+ device->getFormatSupportedResourceStates(format, &formatSupportedStates));
+
+ textureAllowedStates.add(
+ ResourceState::RenderTarget,
+ ResourceState::DepthRead,
+ ResourceState::DepthWrite,
+ ResourceState::Present,
+ ResourceState::ResolveSource,
+ ResourceState::ResolveDestination,
+ ResourceState::Undefined,
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopySource,
+ ResourceState::CopyDestination);
+
+ bufferAllowedStates.add(
+ ResourceState::VertexBuffer,
+ ResourceState::IndexBuffer,
+ ResourceState::ConstantBuffer,
+ ResourceState::StreamOutput,
+ ResourceState::IndirectArgument,
+ ResourceState::AccelerationStructure,
+ ResourceState::Undefined,
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopySource,
+ ResourceState::CopyDestination);
+
+ ResourceState currentState = ResourceState::CopySource;
+ ITextureResource::Extents extent;
+ extent.width = 4;
+ extent.height = 4;
+ extent.depth = 1;
+
+ ITextureResource::Desc texDesc = {};
+ texDesc.type = IResource::Type::Texture2D;
+ texDesc.numMipLevels = 1;
+ texDesc.arraySize = 1;
+ texDesc.size = extent;
+ texDesc.defaultState = currentState;
+ texDesc.allowedStates = formatSupportedStates & textureAllowedStates;
+ texDesc.memoryType = MemoryType::DeviceLocal;
+ texDesc.format = format;
- void supportedResourceStatesTestImpl(IDevice* device, UnitTestContext* context)
- {
- GetSupportedResourceStatesBase test;
- test.init(device, context);
- test.run();
+ GFX_CHECK_CALL_ABORT(
+ device->createTextureResource(texDesc, nullptr, texture.writeRef()));
+
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = 256;
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = formatSupportedStates & bufferAllowedStates;
+ bufferDesc.defaultState = currentState;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, nullptr, buffer.writeRef()));
+
+ transitionResourceStates(device);
+ }
}
+};
+
+void supportedResourceStatesTestImpl(IDevice* device, UnitTestContext* context)
+{
+ GetSupportedResourceStatesBase test;
+ test.init(device, context);
+ test.run();
}
+} // namespace
namespace gfx_test
{
- SLANG_UNIT_TEST(getSupportedResourceStatesD3D12)
- {
- runTestImpl(supportedResourceStatesTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+SLANG_UNIT_TEST(getSupportedResourceStatesD3D12)
+{
+ runTestImpl(supportedResourceStatesTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
- SLANG_UNIT_TEST(getSupportedResourceStatesVulkan)
- {
- runTestImpl(supportedResourceStatesTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(getSupportedResourceStatesVulkan)
+{
+ runTestImpl(supportedResourceStatesTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/get-texture-resource-handle-test.cpp b/tools/gfx-unit-test/get-texture-resource-handle-test.cpp
index 6b4862707..238d5a4fe 100644
--- a/tools/gfx-unit-test/get-texture-resource-handle-test.cpp
+++ b/tools/gfx-unit-test/get-texture-resource-handle-test.cpp
@@ -1,9 +1,8 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
@@ -13,90 +12,83 @@ using namespace gfx;
namespace gfx_test
{
- void getTextureResourceHandleTestImpl(IDevice* device, UnitTestContext* context)
- {
- ITextureResource::Desc desc = {};
- desc.type = IResource::Type::Texture2D;
- desc.numMipLevels = 1;
- desc.size.width = 1;
- desc.size.height = 1;
- desc.size.depth = 1;
- desc.defaultState = ResourceState::UnorderedAccess;
- desc.format = Format::R16G16B16A16_FLOAT;
+void getTextureResourceHandleTestImpl(IDevice* device, UnitTestContext* context)
+{
+ ITextureResource::Desc desc = {};
+ desc.type = IResource::Type::Texture2D;
+ desc.numMipLevels = 1;
+ desc.size.width = 1;
+ desc.size.height = 1;
+ desc.size.depth = 1;
+ desc.defaultState = ResourceState::UnorderedAccess;
+ desc.format = Format::R16G16B16A16_FLOAT;
- Slang::ComPtr<ITextureResource> buffer;
- buffer = device->createTextureResource(desc);
+ Slang::ComPtr<ITextureResource> buffer;
+ buffer = device->createTextureResource(desc);
- InteropHandle handle;
- GFX_CHECK_CALL_ABORT(buffer->getNativeResourceHandle(&handle));
- if (device->getDeviceInfo().deviceType == gfx::DeviceType::Vulkan)
- {
- SLANG_CHECK(handle.handleValue != 0);
- SLANG_CHECK(handle.api == InteropHandleAPI::Vulkan);
- }
+ InteropHandle handle;
+ GFX_CHECK_CALL_ABORT(buffer->getNativeResourceHandle(&handle));
+ if (device->getDeviceInfo().deviceType == gfx::DeviceType::Vulkan)
+ {
+ SLANG_CHECK(handle.handleValue != 0);
+ SLANG_CHECK(handle.api == InteropHandleAPI::Vulkan);
+ }
#if SLANG_WINDOWS_FAMILY
- else
- {
- SLANG_CHECK(handle.api == InteropHandleAPI::D3D12);
- auto d3d12Handle = (ID3D12Resource*)handle.handleValue;
- Slang::ComPtr<IUnknown> testHandle1;
- GFX_CHECK_CALL_ABORT(d3d12Handle->QueryInterface<IUnknown>(testHandle1.writeRef()));
- Slang::ComPtr<ID3D12Resource> testHandle2;
- GFX_CHECK_CALL_ABORT(testHandle1->QueryInterface<ID3D12Resource>(testHandle2.writeRef()));
- SLANG_CHECK(d3d12Handle == testHandle2.get());
- }
-#endif
+ else
+ {
+ SLANG_CHECK(handle.api == InteropHandleAPI::D3D12);
+ auto d3d12Handle = (ID3D12Resource*)handle.handleValue;
+ Slang::ComPtr<IUnknown> testHandle1;
+ GFX_CHECK_CALL_ABORT(d3d12Handle->QueryInterface<IUnknown>(testHandle1.writeRef()));
+ Slang::ComPtr<ID3D12Resource> testHandle2;
+ GFX_CHECK_CALL_ABORT(testHandle1->QueryInterface<ID3D12Resource>(testHandle2.writeRef()));
+ SLANG_CHECK(d3d12Handle == testHandle2.get());
}
+#endif
+}
- void getTextureResourceHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+void getTextureResourceHandleTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+{
+ if ((api & context->enabledApis) == 0)
{
- if ((api & context->enabledApis) == 0)
- {
- SLANG_IGNORE_TEST;
- }
- Slang::ComPtr<IDevice> device;
- IDevice::Desc deviceDesc = {};
- switch (api)
- {
- case Slang::RenderApiFlag::D3D11:
- deviceDesc.deviceType = gfx::DeviceType::DirectX11;
- break;
- case Slang::RenderApiFlag::D3D12:
- deviceDesc.deviceType = gfx::DeviceType::DirectX12;
- break;
- case Slang::RenderApiFlag::Vulkan:
- deviceDesc.deviceType = gfx::DeviceType::Vulkan;
- break;
- default:
- SLANG_IGNORE_TEST;
- }
- deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
- const char* searchPaths[] = { "", "../../tools/gfx-unit-test", "tools/gfx-unit-test" };
- deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
- deviceDesc.slang.searchPaths = searchPaths;
- auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
- if (SLANG_FAILED(createDeviceResult))
- {
- SLANG_IGNORE_TEST;
- }
- // Ignore this test on swiftshader. Swiftshader seems to have a bug that causes the test
- // to crash.
- if (Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
- {
- SLANG_IGNORE_TEST;
- }
- getTextureResourceHandleTestImpl(device, context);
+ SLANG_IGNORE_TEST;
}
-
- SLANG_UNIT_TEST(getTextureResourceHandleD3D12)
+ Slang::ComPtr<IDevice> device;
+ IDevice::Desc deviceDesc = {};
+ switch (api)
{
- return getTextureResourceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+ case Slang::RenderApiFlag::D3D11: deviceDesc.deviceType = gfx::DeviceType::DirectX11; break;
+ case Slang::RenderApiFlag::D3D12: deviceDesc.deviceType = gfx::DeviceType::DirectX12; break;
+ case Slang::RenderApiFlag::Vulkan: deviceDesc.deviceType = gfx::DeviceType::Vulkan; break;
+ default: SLANG_IGNORE_TEST;
}
-
- SLANG_UNIT_TEST(getTextureResourceHandleVulkan)
+ deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
+ const char* searchPaths[] = {"", "../../tools/gfx-unit-test", "tools/gfx-unit-test"};
+ deviceDesc.slang.searchPathCount = (SlangInt)SLANG_COUNT_OF(searchPaths);
+ deviceDesc.slang.searchPaths = searchPaths;
+ auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
+ if (SLANG_FAILED(createDeviceResult))
+ {
+ SLANG_IGNORE_TEST;
+ }
+ // Ignore this test on swiftshader. Swiftshader seems to have a bug that causes the test
+ // to crash.
+ if (Slang::String(device->getDeviceInfo().adapterName).toLower().contains("swiftshader"))
{
- return getTextureResourceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ SLANG_IGNORE_TEST;
}
+ getTextureResourceHandleTestImpl(device, context);
+}
+
+SLANG_UNIT_TEST(getTextureResourceHandleD3D12)
+{
+ return getTextureResourceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+SLANG_UNIT_TEST(getTextureResourceHandleVulkan)
+{
+ return getTextureResourceHandleTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/gfx-test-texture-util.cpp b/tools/gfx-unit-test/gfx-test-texture-util.cpp
index 21e82ab22..a4f86d1d8 100644
--- a/tools/gfx-unit-test/gfx-test-texture-util.cpp
+++ b/tools/gfx-unit-test/gfx-test-texture-util.cpp
@@ -1,15 +1,15 @@
#include "gfx-test-texture-util.h"
-#include "gfx-test-util.h"
-#include "tools/unit-test/slang-unit-test.h"
+#include "gfx-test-util.h"
#include "slang-com-ptr.h"
+#include "tools/unit-test/slang-unit-test.h"
-#include <stdlib.h>
#include <stdio.h>
+#include <stdlib.h>
#ifdef _MSC_VER
#pragma warning(push)
-#pragma warning(disable: 4996)
+#pragma warning(disable : 4996)
#endif
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "external/stb/stb_image_write.h"
@@ -20,8 +20,9 @@
#define GFX_ENABLE_RENDERDOC_INTEGRATION 0
#if GFX_ENABLE_RENDERDOC_INTEGRATION
-# include "external/renderdoc_app.h"
-# include <windows.h>
+#include "external/renderdoc_app.h"
+
+#include <windows.h>
#endif
using namespace Slang;
@@ -29,232 +30,235 @@ using namespace gfx;
namespace gfx_test
{
- TextureAspect getTextureAspect(Format format)
+TextureAspect getTextureAspect(Format format)
+{
+ switch (format)
{
- switch (format)
- {
- case Format::D16_UNORM:
- case Format::D32_FLOAT:
- return TextureAspect::Depth;
- default:
- return TextureAspect::Color;
- }
+ case Format::D16_UNORM:
+ case Format::D32_FLOAT: return TextureAspect::Depth;
+ default: return TextureAspect::Color;
}
+}
- Size getTexelSize(Format format)
- {
- FormatInfo info;
- GFX_CHECK_CALL_ABORT(gfxGetFormatInfo(format, &info));
- return info.blockSizeInBytes / info.pixelsPerBlock;
- }
+Size getTexelSize(Format format)
+{
+ FormatInfo info;
+ GFX_CHECK_CALL_ABORT(gfxGetFormatInfo(format, &info));
+ return info.blockSizeInBytes / info.pixelsPerBlock;
+}
- GfxIndex getSubresourceIndex(GfxIndex mipLevel, GfxCount mipLevelCount, GfxIndex baseArrayLayer)
- {
- return baseArrayLayer * mipLevelCount + mipLevel;
- }
+GfxIndex getSubresourceIndex(GfxIndex mipLevel, GfxCount mipLevelCount, GfxIndex baseArrayLayer)
+{
+ return baseArrayLayer * mipLevelCount + mipLevel;
+}
- RefPtr<ValidationTextureFormatBase> getValidationTextureFormat(Format format)
+RefPtr<ValidationTextureFormatBase> getValidationTextureFormat(Format format)
+{
+ switch (format)
{
- switch (format)
- {
- case Format::R32G32B32A32_TYPELESS: return new ValidationTextureFormat<uint32_t>(4);
- case Format::R32G32B32_TYPELESS: return new ValidationTextureFormat<uint32_t>(3);
- case Format::R32G32_TYPELESS: return new ValidationTextureFormat<uint32_t>(2);
- case Format::R32_TYPELESS: return new ValidationTextureFormat<uint32_t>(1);
-
- case Format::R16G16B16A16_TYPELESS: return new ValidationTextureFormat<uint16_t>(4);
- case Format::R16G16_TYPELESS: return new ValidationTextureFormat<uint16_t>(2);
- case Format::R16_TYPELESS: return new ValidationTextureFormat<uint16_t>(1);
-
- case Format::R8G8B8A8_TYPELESS: return new ValidationTextureFormat<uint8_t>(4);
- case Format::R8G8_TYPELESS: return new ValidationTextureFormat<uint8_t>(2);
- case Format::R8_TYPELESS: return new ValidationTextureFormat<uint8_t>(1);
- case Format::B8G8R8A8_TYPELESS: return new ValidationTextureFormat<uint8_t>(4);
-
- case Format::R32G32B32A32_FLOAT: return new ValidationTextureFormat<float>(4);
- case Format::R32G32B32_FLOAT: return new ValidationTextureFormat<float>(3);
- case Format::R32G32_FLOAT: return new ValidationTextureFormat<float>(2);
- case Format::R32_FLOAT: return new ValidationTextureFormat<float>(1);
-
- case Format::R16G16B16A16_FLOAT: return new ValidationTextureFormat<uint16_t>(4);
- case Format::R16G16_FLOAT: return new ValidationTextureFormat<uint16_t>(2);
- case Format::R16_FLOAT: return new ValidationTextureFormat<uint16_t>(1);
-
- case Format::R64_UINT: return new ValidationTextureFormat<uint64_t>(1);
-
- case Format::R32G32B32A32_UINT: return new ValidationTextureFormat<uint32_t>(4);
- case Format::R32G32B32_UINT: return new ValidationTextureFormat<uint32_t>(3);
- case Format::R32G32_UINT: return new ValidationTextureFormat<uint32_t>(2);
- case Format::R32_UINT: return new ValidationTextureFormat<uint32_t>(1);
-
- case Format::R16G16B16A16_UINT: return new ValidationTextureFormat<uint16_t>(4);
- case Format::R16G16_UINT: return new ValidationTextureFormat<uint16_t>(2);
- case Format::R16_UINT: return new ValidationTextureFormat<uint16_t>(1);
-
- case Format::R8G8B8A8_UINT: return new ValidationTextureFormat<uint8_t>(4);
- case Format::R8G8_UINT: return new ValidationTextureFormat<uint8_t>(2);
- case Format::R8_UINT: return new ValidationTextureFormat<uint8_t>(1);
-
- case Format::R64_SINT: return new ValidationTextureFormat<int64_t>(1);
-
- case Format::R32G32B32A32_SINT: return new ValidationTextureFormat<int32_t>(4);
- case Format::R32G32B32_SINT: return new ValidationTextureFormat<int32_t>(3);
- case Format::R32G32_SINT: return new ValidationTextureFormat<int32_t>(2);
- case Format::R32_SINT: return new ValidationTextureFormat<int32_t>(1);
-
- case Format::R16G16B16A16_SINT: return new ValidationTextureFormat<int16_t>(4);
- case Format::R16G16_SINT: return new ValidationTextureFormat<int16_t>(2);
- case Format::R16_SINT: return new ValidationTextureFormat<int16_t>(1);
-
- case Format::R8G8B8A8_SINT: return new ValidationTextureFormat<int8_t>(4);
- case Format::R8G8_SINT: return new ValidationTextureFormat<int8_t>(2);
- case Format::R8_SINT: return new ValidationTextureFormat<int8_t>(1);
-
- case Format::R16G16B16A16_UNORM: return new ValidationTextureFormat<uint16_t>(4);
- case Format::R16G16_UNORM: return new ValidationTextureFormat<uint16_t>(2);
- case Format::R16_UNORM: return new ValidationTextureFormat<uint16_t>(1);
-
- case Format::R8G8B8A8_UNORM: return new ValidationTextureFormat<uint8_t>(4);
- case Format::R8G8B8A8_UNORM_SRGB: return new ValidationTextureFormat<uint8_t>(4);
- case Format::R8G8_UNORM: return new ValidationTextureFormat<uint8_t>(2);
- case Format::R8_UNORM: return new ValidationTextureFormat<uint8_t>(1);
- case Format::B8G8R8A8_UNORM: return new ValidationTextureFormat<uint8_t>(4);
- case Format::B8G8R8A8_UNORM_SRGB: return new ValidationTextureFormat<uint8_t>(4);
- case Format::B8G8R8X8_UNORM: return new ValidationTextureFormat<uint8_t>(3);
- case Format::B8G8R8X8_UNORM_SRGB: return new ValidationTextureFormat<uint8_t>(3);
-
- case Format::R16G16B16A16_SNORM: return new ValidationTextureFormat<int16_t>(4);
- case Format::R16G16_SNORM: return new ValidationTextureFormat<int16_t>(2);
- case Format::R16_SNORM: return new ValidationTextureFormat<int16_t>(1);
-
- case Format::R8G8B8A8_SNORM: return new ValidationTextureFormat<int8_t>(4);
- case Format::R8G8_SNORM: return new ValidationTextureFormat<int8_t>(2);
- case Format::R8_SNORM: return new ValidationTextureFormat<int8_t>(1);
-
- case Format::D32_FLOAT: return new ValidationTextureFormat<float>(1);
- case Format::D16_UNORM: return new ValidationTextureFormat<uint16_t>(1);
-
- case Format::B4G4R4A4_UNORM: return new PackedValidationTextureFormat<uint16_t>(4, 4, 4, 4);
- case Format::B5G6R5_UNORM: return new PackedValidationTextureFormat<uint16_t>(5, 6, 5, 0);
- case Format::B5G5R5A1_UNORM: return new PackedValidationTextureFormat<uint16_t>(5, 5, 5, 1);
-
- case Format::R9G9B9E5_SHAREDEXP: return new ValidationTextureFormat<uint32_t>(1);
- case Format::R10G10B10A2_TYPELESS: return new PackedValidationTextureFormat<uint32_t>(10, 10, 10, 2);
- case Format::R10G10B10A2_UNORM: return new PackedValidationTextureFormat<uint32_t>(10, 10, 10, 2);
- case Format::R10G10B10A2_UINT: return new PackedValidationTextureFormat<uint32_t>(10, 10, 10, 2);
- case Format::R11G11B10_FLOAT: return new PackedValidationTextureFormat<uint32_t>(11, 11, 10, 0);
-
- // TODO: Add testing support for BC formats
-// BC1_UNORM,
-// BC1_UNORM_SRGB,
-// BC2_UNORM,
-// BC2_UNORM_SRGB,
-// BC3_UNORM,
-// BC3_UNORM_SRGB,
-// BC4_UNORM,
-// BC4_SNORM,
-// BC5_UNORM,
-// BC5_SNORM,
-// BC6H_UF16,
-// BC6H_SF16,
-// BC7_UNORM,
-// BC7_UNORM_SRGB,
- default:
- return nullptr;
- }
+ case Format::R32G32B32A32_TYPELESS: return new ValidationTextureFormat<uint32_t>(4);
+ case Format::R32G32B32_TYPELESS: return new ValidationTextureFormat<uint32_t>(3);
+ case Format::R32G32_TYPELESS: return new ValidationTextureFormat<uint32_t>(2);
+ case Format::R32_TYPELESS: return new ValidationTextureFormat<uint32_t>(1);
+
+ case Format::R16G16B16A16_TYPELESS: return new ValidationTextureFormat<uint16_t>(4);
+ case Format::R16G16_TYPELESS: return new ValidationTextureFormat<uint16_t>(2);
+ case Format::R16_TYPELESS: return new ValidationTextureFormat<uint16_t>(1);
+
+ case Format::R8G8B8A8_TYPELESS: return new ValidationTextureFormat<uint8_t>(4);
+ case Format::R8G8_TYPELESS: return new ValidationTextureFormat<uint8_t>(2);
+ case Format::R8_TYPELESS: return new ValidationTextureFormat<uint8_t>(1);
+ case Format::B8G8R8A8_TYPELESS: return new ValidationTextureFormat<uint8_t>(4);
+
+ case Format::R32G32B32A32_FLOAT: return new ValidationTextureFormat<float>(4);
+ case Format::R32G32B32_FLOAT: return new ValidationTextureFormat<float>(3);
+ case Format::R32G32_FLOAT: return new ValidationTextureFormat<float>(2);
+ case Format::R32_FLOAT: return new ValidationTextureFormat<float>(1);
+
+ case Format::R16G16B16A16_FLOAT: return new ValidationTextureFormat<uint16_t>(4);
+ case Format::R16G16_FLOAT: return new ValidationTextureFormat<uint16_t>(2);
+ case Format::R16_FLOAT: return new ValidationTextureFormat<uint16_t>(1);
+
+ case Format::R64_UINT: return new ValidationTextureFormat<uint64_t>(1);
+
+ case Format::R32G32B32A32_UINT: return new ValidationTextureFormat<uint32_t>(4);
+ case Format::R32G32B32_UINT: return new ValidationTextureFormat<uint32_t>(3);
+ case Format::R32G32_UINT: return new ValidationTextureFormat<uint32_t>(2);
+ case Format::R32_UINT: return new ValidationTextureFormat<uint32_t>(1);
+
+ case Format::R16G16B16A16_UINT: return new ValidationTextureFormat<uint16_t>(4);
+ case Format::R16G16_UINT: return new ValidationTextureFormat<uint16_t>(2);
+ case Format::R16_UINT: return new ValidationTextureFormat<uint16_t>(1);
+
+ case Format::R8G8B8A8_UINT: return new ValidationTextureFormat<uint8_t>(4);
+ case Format::R8G8_UINT: return new ValidationTextureFormat<uint8_t>(2);
+ case Format::R8_UINT: return new ValidationTextureFormat<uint8_t>(1);
+
+ case Format::R64_SINT: return new ValidationTextureFormat<int64_t>(1);
+
+ case Format::R32G32B32A32_SINT: return new ValidationTextureFormat<int32_t>(4);
+ case Format::R32G32B32_SINT: return new ValidationTextureFormat<int32_t>(3);
+ case Format::R32G32_SINT: return new ValidationTextureFormat<int32_t>(2);
+ case Format::R32_SINT: return new ValidationTextureFormat<int32_t>(1);
+
+ case Format::R16G16B16A16_SINT: return new ValidationTextureFormat<int16_t>(4);
+ case Format::R16G16_SINT: return new ValidationTextureFormat<int16_t>(2);
+ case Format::R16_SINT: return new ValidationTextureFormat<int16_t>(1);
+
+ case Format::R8G8B8A8_SINT: return new ValidationTextureFormat<int8_t>(4);
+ case Format::R8G8_SINT: return new ValidationTextureFormat<int8_t>(2);
+ case Format::R8_SINT: return new ValidationTextureFormat<int8_t>(1);
+
+ case Format::R16G16B16A16_UNORM: return new ValidationTextureFormat<uint16_t>(4);
+ case Format::R16G16_UNORM: return new ValidationTextureFormat<uint16_t>(2);
+ case Format::R16_UNORM: return new ValidationTextureFormat<uint16_t>(1);
+
+ case Format::R8G8B8A8_UNORM: return new ValidationTextureFormat<uint8_t>(4);
+ case Format::R8G8B8A8_UNORM_SRGB: return new ValidationTextureFormat<uint8_t>(4);
+ case Format::R8G8_UNORM: return new ValidationTextureFormat<uint8_t>(2);
+ case Format::R8_UNORM: return new ValidationTextureFormat<uint8_t>(1);
+ case Format::B8G8R8A8_UNORM: return new ValidationTextureFormat<uint8_t>(4);
+ case Format::B8G8R8A8_UNORM_SRGB: return new ValidationTextureFormat<uint8_t>(4);
+ case Format::B8G8R8X8_UNORM: return new ValidationTextureFormat<uint8_t>(3);
+ case Format::B8G8R8X8_UNORM_SRGB: return new ValidationTextureFormat<uint8_t>(3);
+
+ case Format::R16G16B16A16_SNORM: return new ValidationTextureFormat<int16_t>(4);
+ case Format::R16G16_SNORM: return new ValidationTextureFormat<int16_t>(2);
+ case Format::R16_SNORM: return new ValidationTextureFormat<int16_t>(1);
+
+ case Format::R8G8B8A8_SNORM: return new ValidationTextureFormat<int8_t>(4);
+ case Format::R8G8_SNORM: return new ValidationTextureFormat<int8_t>(2);
+ case Format::R8_SNORM: return new ValidationTextureFormat<int8_t>(1);
+
+ case Format::D32_FLOAT: return new ValidationTextureFormat<float>(1);
+ case Format::D16_UNORM: return new ValidationTextureFormat<uint16_t>(1);
+
+ case Format::B4G4R4A4_UNORM: return new PackedValidationTextureFormat<uint16_t>(4, 4, 4, 4);
+ case Format::B5G6R5_UNORM: return new PackedValidationTextureFormat<uint16_t>(5, 6, 5, 0);
+ case Format::B5G5R5A1_UNORM: return new PackedValidationTextureFormat<uint16_t>(5, 5, 5, 1);
+
+ case Format::R9G9B9E5_SHAREDEXP: return new ValidationTextureFormat<uint32_t>(1);
+ case Format::R10G10B10A2_TYPELESS:
+ return new PackedValidationTextureFormat<uint32_t>(10, 10, 10, 2);
+ case Format::R10G10B10A2_UNORM:
+ return new PackedValidationTextureFormat<uint32_t>(10, 10, 10, 2);
+ case Format::R10G10B10A2_UINT:
+ return new PackedValidationTextureFormat<uint32_t>(10, 10, 10, 2);
+ case Format::R11G11B10_FLOAT:
+ return new PackedValidationTextureFormat<uint32_t>(11, 11, 10, 0);
+
+ // TODO: Add testing support for BC formats
+ // BC1_UNORM,
+ // BC1_UNORM_SRGB,
+ // BC2_UNORM,
+ // BC2_UNORM_SRGB,
+ // BC3_UNORM,
+ // BC3_UNORM_SRGB,
+ // BC4_UNORM,
+ // BC4_SNORM,
+ // BC5_UNORM,
+ // BC5_SNORM,
+ // BC6H_UF16,
+ // BC6H_SF16,
+ // BC7_UNORM,
+ // BC7_UNORM_SRGB,
+ default: return nullptr;
}
+}
- void generateTextureData(RefPtr<TextureInfo> texture, ValidationTextureFormatBase* validationFormat)
- {
- auto extents = texture->extents;
- auto arrayLayers = texture->arrayLayerCount;
- auto mipLevels = texture->mipLevelCount;
- auto texelSize = getTexelSize(texture->format);
+void generateTextureData(RefPtr<TextureInfo> texture, ValidationTextureFormatBase* validationFormat)
+{
+ auto extents = texture->extents;
+ auto arrayLayers = texture->arrayLayerCount;
+ auto mipLevels = texture->mipLevelCount;
+ auto texelSize = getTexelSize(texture->format);
- for (GfxIndex layer = 0; layer < arrayLayers; ++layer)
+ for (GfxIndex layer = 0; layer < arrayLayers; ++layer)
+ {
+ for (GfxIndex mip = 0; mip < mipLevels; ++mip)
{
- for (GfxIndex mip = 0; mip < mipLevels; ++mip)
+ RefPtr<ValidationTextureData> subresource = new ValidationTextureData();
+
+ auto mipWidth = Math::Max(extents.width >> mip, 1);
+ auto mipHeight = Math::Max(extents.height >> mip, 1);
+ auto mipDepth = Math::Max(extents.depth >> mip, 1);
+ auto mipSize = mipWidth * mipHeight * mipDepth * texelSize;
+ subresource->textureData = malloc(mipSize);
+ SLANG_CHECK_ABORT(subresource->textureData);
+
+ subresource->extents.width = mipWidth;
+ subresource->extents.height = mipHeight;
+ subresource->extents.depth = mipDepth;
+ subresource->strides.x = texelSize;
+ subresource->strides.y = mipWidth * texelSize;
+ subresource->strides.z = mipHeight * subresource->strides.y;
+ texture->subresourceObjects.add(subresource);
+
+ for (int z = 0; z < mipDepth; ++z)
{
- RefPtr<ValidationTextureData> subresource = new ValidationTextureData();
-
- auto mipWidth = Math::Max(extents.width >> mip, 1);
- auto mipHeight = Math::Max(extents.height >> mip, 1);
- auto mipDepth = Math::Max(extents.depth >> mip, 1);
- auto mipSize = mipWidth * mipHeight * mipDepth * texelSize;
- subresource->textureData = malloc(mipSize);
- SLANG_CHECK_ABORT(subresource->textureData);
-
- subresource->extents.width = mipWidth;
- subresource->extents.height = mipHeight;
- subresource->extents.depth = mipDepth;
- subresource->strides.x = texelSize;
- subresource->strides.y = mipWidth * texelSize;
- subresource->strides.z = mipHeight * subresource->strides.y;
- texture->subresourceObjects.add(subresource);
-
- for (int z = 0; z < mipDepth; ++z)
+ for (int y = 0; y < mipHeight; ++y)
{
- for (int y = 0; y < mipHeight; ++y)
+ for (int x = 0; x < mipWidth; ++x)
{
- for (int x = 0; x < mipWidth; ++x)
- {
- auto texel = subresource->getBlockAt(x, y, z);
- validationFormat->initializeTexel(texel, x, y, z, mip, layer);
- }
+ auto texel = subresource->getBlockAt(x, y, z);
+ validationFormat->initializeTexel(texel, x, y, z, mip, layer);
}
}
-
- ITextureResource::SubresourceData subData = {};
- subData.data = subresource->textureData;
- subData.strideY = subresource->strides.y;
- subData.strideZ = subresource->strides.z;
- texture->subresourceDatas.add(subData);
}
+
+ ITextureResource::SubresourceData subData = {};
+ subData.data = subresource->textureData;
+ subData.strideY = subresource->strides.y;
+ subData.strideZ = subresource->strides.z;
+ texture->subresourceDatas.add(subData);
}
}
+}
- List<uint8_t> removePadding(ISlangBlob* pixels, GfxCount width, GfxCount height, Size rowPitch, Size pixelSize)
+List<uint8_t> removePadding(
+ ISlangBlob* pixels,
+ GfxCount width,
+ GfxCount height,
+ Size rowPitch,
+ Size pixelSize)
+{
+ List<uint8_t> buffer;
+ buffer.setCount(height * rowPitch);
+ for (GfxIndex i = 0; i < height; ++i)
{
- List<uint8_t> buffer;
- buffer.setCount(height * rowPitch);
- for (GfxIndex i = 0; i < height; ++i)
- {
- Offset srcOffset = i * rowPitch;
- Offset dstOffset = i * width * pixelSize;
- memcpy(buffer.getBuffer() + dstOffset, (char*)pixels->getBufferPointer() + srcOffset, width * pixelSize);
- }
-
- return buffer;
+ Offset srcOffset = i * rowPitch;
+ Offset dstOffset = i * width * pixelSize;
+ memcpy(
+ buffer.getBuffer() + dstOffset,
+ (char*)pixels->getBufferPointer() + srcOffset,
+ width * pixelSize);
}
- Slang::Result writeImage(
- const char* filename,
- ISlangBlob* pixels,
- uint32_t width,
- uint32_t height)
- {
- int stbResult =
- stbi_write_hdr(filename, width, height, 4, (float*)pixels->getBufferPointer());
+ return buffer;
+}
- return stbResult ? SLANG_OK : SLANG_FAIL;
- }
+Slang::Result writeImage(const char* filename, ISlangBlob* pixels, uint32_t width, uint32_t height)
+{
+ int stbResult = stbi_write_hdr(filename, width, height, 4, (float*)pixels->getBufferPointer());
- Slang::Result writeImage(
- const char* filename,
- ISlangBlob* pixels,
- uint32_t width,
- uint32_t height,
- uint32_t rowPitch,
- uint32_t pixelSize)
- {
- if (rowPitch == width * pixelSize)
- return writeImage(filename, pixels, width, height);
+ return stbResult ? SLANG_OK : SLANG_FAIL;
+}
- List<uint8_t> buffer = removePadding(pixels, width, height, rowPitch, pixelSize);
+Slang::Result writeImage(
+ const char* filename,
+ ISlangBlob* pixels,
+ uint32_t width,
+ uint32_t height,
+ uint32_t rowPitch,
+ uint32_t pixelSize)
+{
+ if (rowPitch == width * pixelSize)
+ return writeImage(filename, pixels, width, height);
- int stbResult =
- stbi_write_hdr(filename, width, height, 4, (float*)buffer.getBuffer());
+ List<uint8_t> buffer = removePadding(pixels, width, height, rowPitch, pixelSize);
- return stbResult ? SLANG_OK : SLANG_FAIL;
- }
+ int stbResult = stbi_write_hdr(filename, width, height, 4, (float*)buffer.getBuffer());
+
+ return stbResult ? SLANG_OK : SLANG_FAIL;
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/gfx-test-texture-util.h b/tools/gfx-unit-test/gfx-test-texture-util.h
index 7069ff667..7c6b9443f 100644
--- a/tools/gfx-unit-test/gfx-test-texture-util.h
+++ b/tools/gfx-unit-test/gfx-test-texture-util.h
@@ -10,187 +10,205 @@ using namespace gfx;
namespace gfx_test
{
- struct Strides
- {
- Size x;
- Size y;
- Size z;
- };
+struct Strides
+{
+ Size x;
+ Size y;
+ Size z;
+};
- struct ValidationTextureFormatBase : RefObject
- {
- virtual void validateBlocksEqual(const void* actual, const void* expected) = 0;
+struct ValidationTextureFormatBase : RefObject
+{
+ virtual void validateBlocksEqual(const void* actual, const void* expected) = 0;
+
+ virtual void initializeTexel(
+ void* texel,
+ GfxIndex x,
+ GfxIndex y,
+ GfxIndex z,
+ GfxIndex mipLevel,
+ GfxIndex arrayLayer) = 0;
+};
+
+template<typename T>
+struct ValidationTextureFormat : ValidationTextureFormatBase
+{
+ int componentCount;
- virtual void initializeTexel(void* texel, GfxIndex x, GfxIndex y, GfxIndex z, GfxIndex mipLevel, GfxIndex arrayLayer) = 0;
- };
+ ValidationTextureFormat(int componentCount)
+ : componentCount(componentCount){};
- template <typename T>
- struct ValidationTextureFormat : ValidationTextureFormatBase
+ virtual void validateBlocksEqual(const void* actual, const void* expected) override
{
- int componentCount;
-
- ValidationTextureFormat(int componentCount) : componentCount(componentCount) {};
+ auto a = (const T*)actual;
+ auto e = (const T*)expected;
- virtual void validateBlocksEqual(const void* actual, const void* expected) override
+ for (Int i = 0; i < componentCount; ++i)
{
- auto a = (const T*)actual;
- auto e = (const T*)expected;
-
- for (Int i = 0; i < componentCount; ++i)
- {
- SLANG_CHECK(a[i] == e[i]);
- }
+ SLANG_CHECK(a[i] == e[i]);
}
+ }
+
+ virtual void initializeTexel(
+ void* texel,
+ GfxIndex x,
+ GfxIndex y,
+ GfxIndex z,
+ GfxIndex mipLevel,
+ GfxIndex arrayLayer) override
+ {
+ auto temp = (T*)texel;
- virtual void initializeTexel(void* texel, GfxIndex x, GfxIndex y, GfxIndex z, GfxIndex mipLevel, GfxIndex arrayLayer) override
+ switch (componentCount)
{
- auto temp = (T*)texel;
-
- switch (componentCount)
- {
- case 1:
- temp[0] = T(x + y + z + mipLevel + arrayLayer);
- break;
- case 2:
- temp[0] = T(x + z + arrayLayer);
- temp[1] = T(y + mipLevel);
- break;
- case 3:
- temp[0] = T(x + mipLevel);
- temp[1] = T(y + arrayLayer);
- temp[2] = T(z);
- break;
- case 4:
- temp[0] = T(x + arrayLayer);
- temp[1] = (T)y;
- temp[2] = (T)z;
- temp[3] = (T)mipLevel;
- break;
- default:
- assert(!"component count should be no greater than 4");
- SLANG_CHECK_ABORT(false);
- }
+ case 1: temp[0] = T(x + y + z + mipLevel + arrayLayer); break;
+ case 2:
+ temp[0] = T(x + z + arrayLayer);
+ temp[1] = T(y + mipLevel);
+ break;
+ case 3:
+ temp[0] = T(x + mipLevel);
+ temp[1] = T(y + arrayLayer);
+ temp[2] = T(z);
+ break;
+ case 4:
+ temp[0] = T(x + arrayLayer);
+ temp[1] = (T)y;
+ temp[2] = (T)z;
+ temp[3] = (T)mipLevel;
+ break;
+ default: assert(!"component count should be no greater than 4"); SLANG_CHECK_ABORT(false);
}
- };
+ }
+};
- template <typename T>
- struct PackedValidationTextureFormat : ValidationTextureFormatBase
- {
- int rBits;
- int gBits;
- int bBits;
- int aBits;
+template<typename T>
+struct PackedValidationTextureFormat : ValidationTextureFormatBase
+{
+ int rBits;
+ int gBits;
+ int bBits;
+ int aBits;
+
+ PackedValidationTextureFormat(int rBits, int gBits, int bBits, int aBits)
+ : rBits(rBits), gBits(gBits), bBits(bBits), aBits(aBits){};
- PackedValidationTextureFormat(int rBits, int gBits, int bBits, int aBits)
- : rBits(rBits), gBits(gBits), bBits(bBits), aBits(aBits) {};
+ virtual void validateBlocksEqual(const void* actual, const void* expected) override
+ {
+ T a[4];
+ T e[4];
+ unpackTexel(*(const T*)actual, a);
+ unpackTexel(*(const T*)expected, e);
- virtual void validateBlocksEqual(const void* actual, const void* expected) override
+ for (Int i = 0; i < 4; ++i)
{
- T a[4];
- T e[4];
- unpackTexel(*(const T*)actual, a);
- unpackTexel(*(const T*)expected, e);
-
- for (Int i = 0; i < 4; ++i)
- {
- SLANG_CHECK(a[i] == e[i]);
- }
+ SLANG_CHECK(a[i] == e[i]);
}
+ }
+
+ virtual void initializeTexel(
+ void* texel,
+ GfxIndex x,
+ GfxIndex y,
+ GfxIndex z,
+ GfxIndex mipLevel,
+ GfxIndex arrayLayer) override
+ {
+ T temp = 0;
- virtual void initializeTexel(void* texel, GfxIndex x, GfxIndex y, GfxIndex z, GfxIndex mipLevel, GfxIndex arrayLayer) override
+ // The only formats which currently use this have either 3 or 4 channels. TODO: BC formats?
+ if (aBits == 0)
{
- T temp = 0;
-
- // The only formats which currently use this have either 3 or 4 channels. TODO: BC formats?
- if (aBits == 0)
- {
- temp |= z;
- temp <<= gBits;
- temp |= (y + arrayLayer);
- temp <<= rBits;
- temp |= (x + mipLevel);
- }
- else
- {
- temp |= mipLevel;
- temp <<= bBits;
- temp |= z;
- temp <<= gBits;
- temp |= y;
- temp <<= rBits;
- temp |= (x + arrayLayer);
- }
-
- *(T*)texel = temp;
+ temp |= z;
+ temp <<= gBits;
+ temp |= (y + arrayLayer);
+ temp <<= rBits;
+ temp |= (x + mipLevel);
}
-
- void unpackTexel(T texel, T* outComponents)
+ else
{
- outComponents[0] = texel & ((1 << rBits) - 1);
- texel >>= rBits;
+ temp |= mipLevel;
+ temp <<= bBits;
+ temp |= z;
+ temp <<= gBits;
+ temp |= y;
+ temp <<= rBits;
+ temp |= (x + arrayLayer);
+ }
- outComponents[1] = texel & ((1 << gBits) - 1);
- texel >>= gBits;
+ *(T*)texel = temp;
+ }
- outComponents[2] = texel & ((1 << bBits) - 1);
- texel >>= bBits;
+ void unpackTexel(T texel, T* outComponents)
+ {
+ outComponents[0] = texel & ((1 << rBits) - 1);
+ texel >>= rBits;
- outComponents[3] = texel & ((1 << aBits) - 1);
- texel >>= aBits;
- }
- };
+ outComponents[1] = texel & ((1 << gBits) - 1);
+ texel >>= gBits;
- // Struct containing texture data and information for a specific subresource.
- struct ValidationTextureData : RefObject
- {
- const void* textureData;
- ITextureResource::Extents extents;
- Strides strides;
+ outComponents[2] = texel & ((1 << bBits) - 1);
+ texel >>= bBits;
- void* getBlockAt(GfxIndex x, GfxIndex y, GfxIndex z)
- {
- assert(x >= 0 && x < extents.width);
- assert(y >= 0 && y < extents.height);
- assert(z >= 0 && z < extents.depth);
+ outComponents[3] = texel & ((1 << aBits) - 1);
+ texel >>= aBits;
+ }
+};
- char* layerData = (char*)textureData + z * strides.z;
- char* rowData = layerData + y * strides.y;
- return rowData + x * strides.x;
- }
- };
+// Struct containing texture data and information for a specific subresource.
+struct ValidationTextureData : RefObject
+{
+ const void* textureData;
+ ITextureResource::Extents extents;
+ Strides strides;
- // Struct containing relevant information for a texture, including a list of its subresources
- // and all relevant information for each subresource.
- struct TextureInfo : RefObject
+ void* getBlockAt(GfxIndex x, GfxIndex y, GfxIndex z)
{
- Format format;
- ITextureResource::Type textureType;
-
- ITextureResource::Extents extents;
- GfxCount mipLevelCount;
- GfxCount arrayLayerCount;
-
- List<RefPtr<ValidationTextureData>> subresourceObjects;
- List<ITextureResource::SubresourceData> subresourceDatas;
- };
-
- TextureAspect getTextureAspect(Format format);
- Size getTexelSize(Format format);
- GfxIndex getSubresourceIndex(GfxIndex mipLevel, GfxCount mipLevelCount, GfxIndex baseArrayLayer);
- RefPtr<ValidationTextureFormatBase> getValidationTextureFormat(Format format);
- void generateTextureData(RefPtr<TextureInfo> texture, ValidationTextureFormatBase* validationFormat);
-
- List<uint8_t> removePadding(ISlangBlob* pixels, GfxCount width, GfxCount height, Size rowPitch, Size pixelSize);
- Slang::Result writeImage(
- const char* filename,
- ISlangBlob* pixels,
- uint32_t width,
- uint32_t height);
- Slang::Result writeImage(
- const char* filename,
- ISlangBlob* pixels,
- uint32_t width,
- uint32_t height,
- uint32_t rowPitch,
- uint32_t pixelSize);
-}
+ assert(x >= 0 && x < extents.width);
+ assert(y >= 0 && y < extents.height);
+ assert(z >= 0 && z < extents.depth);
+
+ char* layerData = (char*)textureData + z * strides.z;
+ char* rowData = layerData + y * strides.y;
+ return rowData + x * strides.x;
+ }
+};
+
+// Struct containing relevant information for a texture, including a list of its subresources
+// and all relevant information for each subresource.
+struct TextureInfo : RefObject
+{
+ Format format;
+ ITextureResource::Type textureType;
+
+ ITextureResource::Extents extents;
+ GfxCount mipLevelCount;
+ GfxCount arrayLayerCount;
+
+ List<RefPtr<ValidationTextureData>> subresourceObjects;
+ List<ITextureResource::SubresourceData> subresourceDatas;
+};
+
+TextureAspect getTextureAspect(Format format);
+Size getTexelSize(Format format);
+GfxIndex getSubresourceIndex(GfxIndex mipLevel, GfxCount mipLevelCount, GfxIndex baseArrayLayer);
+RefPtr<ValidationTextureFormatBase> getValidationTextureFormat(Format format);
+void generateTextureData(
+ RefPtr<TextureInfo> texture,
+ ValidationTextureFormatBase* validationFormat);
+
+List<uint8_t> removePadding(
+ ISlangBlob* pixels,
+ GfxCount width,
+ GfxCount height,
+ Size rowPitch,
+ Size pixelSize);
+Slang::Result writeImage(const char* filename, ISlangBlob* pixels, uint32_t width, uint32_t height);
+Slang::Result writeImage(
+ const char* filename,
+ ISlangBlob* pixels,
+ uint32_t width,
+ uint32_t height,
+ uint32_t rowPitch,
+ uint32_t pixelSize);
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/gfx-test-util.cpp b/tools/gfx-unit-test/gfx-test-util.cpp
index 1c7289325..18aaabdaf 100644
--- a/tools/gfx-unit-test/gfx-test-util.cpp
+++ b/tools/gfx-unit-test/gfx-test-util.cpp
@@ -1,350 +1,360 @@
#include "gfx-test-util.h"
-#include "tools/unit-test/slang-unit-test.h"
#include "slang-com-ptr.h"
+#include "tools/unit-test/slang-unit-test.h"
#define GFX_ENABLE_RENDERDOC_INTEGRATION 0
#define GFX_ENABLE_SPIRV_DEBUG 0
#if GFX_ENABLE_RENDERDOC_INTEGRATION
-# include "external/renderdoc_app.h"
-# include <windows.h>
+#include "external/renderdoc_app.h"
+
+#include <windows.h>
#endif
using Slang::ComPtr;
namespace gfx_test
{
- void diagnoseIfNeeded(slang::IBlob* diagnosticsBlob)
+void diagnoseIfNeeded(slang::IBlob* diagnosticsBlob)
+{
+ if (diagnosticsBlob != nullptr)
{
- if (diagnosticsBlob != nullptr)
- {
- getTestReporter()->message(TestMessageType::Info, (const char*)diagnosticsBlob->getBufferPointer());
- }
+ getTestReporter()->message(
+ TestMessageType::Info,
+ (const char*)diagnosticsBlob->getBufferPointer());
}
+}
- Slang::Result loadComputeProgram(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- const char* shaderModuleName,
- const char* entryPointName,
- slang::ProgramLayout*& slangReflection)
- {
- Slang::ComPtr<slang::ISession> slangSession;
- SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- if (!module)
- return SLANG_FAIL;
-
- ComPtr<slang::IEntryPoint> computeEntryPoint;
- SLANG_RETURN_ON_FAIL(
- module->findEntryPointByName(entryPointName, computeEntryPoint.writeRef()));
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(module);
- componentTypes.add(computeEntryPoint);
-
- Slang::ComPtr<slang::IComponentType> composedProgram;
- SlangResult result = slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- composedProgram.writeRef(),
- diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- ComPtr<slang::IComponentType> linkedProgram;
- result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- composedProgram = linkedProgram;
- slangReflection = composedProgram->getLayout();
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = composedProgram.get();
-
- auto shaderProgram = device->createProgram(programDesc);
-
- outShaderProgram = shaderProgram;
- return SLANG_OK;
- }
+Slang::Result loadComputeProgram(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ const char* shaderModuleName,
+ const char* entryPointName,
+ slang::ProgramLayout*& slangReflection)
+{
+ Slang::ComPtr<slang::ISession> slangSession;
+ SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ if (!module)
+ return SLANG_FAIL;
+
+ ComPtr<slang::IEntryPoint> computeEntryPoint;
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName(entryPointName, computeEntryPoint.writeRef()));
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(module);
+ componentTypes.add(computeEntryPoint);
+
+ Slang::ComPtr<slang::IComponentType> composedProgram;
+ SlangResult result = slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ composedProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ ComPtr<slang::IComponentType> linkedProgram;
+ result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ composedProgram = linkedProgram;
+ slangReflection = composedProgram->getLayout();
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = composedProgram.get();
+
+ auto shaderProgram = device->createProgram(programDesc);
+
+ outShaderProgram = shaderProgram;
+ return SLANG_OK;
+}
- Slang::Result loadComputeProgram(
- gfx::IDevice* device,
- slang::ISession* slangSession,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- const char* shaderModuleName,
- const char* entryPointName,
- slang::ProgramLayout*& slangReflection)
- {
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- if (!module)
- return SLANG_FAIL;
-
- ComPtr<slang::IEntryPoint> computeEntryPoint;
- SLANG_RETURN_ON_FAIL(
- module->findEntryPointByName(entryPointName, computeEntryPoint.writeRef()));
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(module);
- componentTypes.add(computeEntryPoint);
-
- Slang::ComPtr<slang::IComponentType> composedProgram;
- SlangResult result = slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- composedProgram.writeRef(),
- diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- ComPtr<slang::IComponentType> linkedProgram;
- result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- composedProgram = linkedProgram;
- slangReflection = composedProgram->getLayout();
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = composedProgram.get();
-
- auto shaderProgram = device->createProgram(programDesc);
-
- outShaderProgram = shaderProgram;
- return SLANG_OK;
- }
+Slang::Result loadComputeProgram(
+ gfx::IDevice* device,
+ slang::ISession* slangSession,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ const char* shaderModuleName,
+ const char* entryPointName,
+ slang::ProgramLayout*& slangReflection)
+{
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ if (!module)
+ return SLANG_FAIL;
+
+ ComPtr<slang::IEntryPoint> computeEntryPoint;
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName(entryPointName, computeEntryPoint.writeRef()));
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(module);
+ componentTypes.add(computeEntryPoint);
+
+ Slang::ComPtr<slang::IComponentType> composedProgram;
+ SlangResult result = slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ composedProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ ComPtr<slang::IComponentType> linkedProgram;
+ result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ composedProgram = linkedProgram;
+ slangReflection = composedProgram->getLayout();
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = composedProgram.get();
+
+ auto shaderProgram = device->createProgram(programDesc);
+
+ outShaderProgram = shaderProgram;
+ return SLANG_OK;
+}
- Slang::Result loadComputeProgramFromSource(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- Slang::String source)
- {
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+Slang::Result loadComputeProgramFromSource(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ Slang::String source)
+{
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- gfx::IShaderProgram::CreateDesc2 programDesc = {};
- programDesc.sourceType = gfx::ShaderModuleSourceType::SlangSource;
- programDesc.sourceData = (void*)source.getBuffer();
- programDesc.sourceDataSize = source.getLength();
+ gfx::IShaderProgram::CreateDesc2 programDesc = {};
+ programDesc.sourceType = gfx::ShaderModuleSourceType::SlangSource;
+ programDesc.sourceData = (void*)source.getBuffer();
+ programDesc.sourceDataSize = source.getLength();
- return device->createProgram2(programDesc, outShaderProgram.writeRef(), diagnosticsBlob.writeRef());
- }
+ return device->createProgram2(
+ programDesc,
+ outShaderProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+}
- Slang::Result loadGraphicsProgram(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- const char* shaderModuleName,
- const char* vertexEntryPointName,
- const char* fragmentEntryPointName,
- slang::ProgramLayout*& slangReflection)
- {
- Slang::ComPtr<slang::ISession> slangSession;
- SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- if (!module)
- return SLANG_FAIL;
-
- ComPtr<slang::IEntryPoint> vertexEntryPoint;
- SLANG_RETURN_ON_FAIL(
- module->findEntryPointByName(vertexEntryPointName, vertexEntryPoint.writeRef()));
-
- ComPtr<slang::IEntryPoint> fragmentEntryPoint;
- SLANG_RETURN_ON_FAIL(
- module->findEntryPointByName(fragmentEntryPointName, fragmentEntryPoint.writeRef()));
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(module);
- componentTypes.add(vertexEntryPoint);
- componentTypes.add(fragmentEntryPoint);
-
- Slang::ComPtr<slang::IComponentType> composedProgram;
- SlangResult result = slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- composedProgram.writeRef(),
- diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
- slangReflection = composedProgram->getLayout();
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = composedProgram.get();
-
- auto shaderProgram = device->createProgram(programDesc);
-
- outShaderProgram = shaderProgram;
- return SLANG_OK;
- }
+Slang::Result loadGraphicsProgram(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ const char* shaderModuleName,
+ const char* vertexEntryPointName,
+ const char* fragmentEntryPointName,
+ slang::ProgramLayout*& slangReflection)
+{
+ Slang::ComPtr<slang::ISession> slangSession;
+ SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ if (!module)
+ return SLANG_FAIL;
+
+ ComPtr<slang::IEntryPoint> vertexEntryPoint;
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName(vertexEntryPointName, vertexEntryPoint.writeRef()));
+
+ ComPtr<slang::IEntryPoint> fragmentEntryPoint;
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName(fragmentEntryPointName, fragmentEntryPoint.writeRef()));
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(module);
+ componentTypes.add(vertexEntryPoint);
+ componentTypes.add(fragmentEntryPoint);
+
+ Slang::ComPtr<slang::IComponentType> composedProgram;
+ SlangResult result = slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ composedProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+ slangReflection = composedProgram->getLayout();
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = composedProgram.get();
+
+ auto shaderProgram = device->createProgram(programDesc);
+
+ outShaderProgram = shaderProgram;
+ return SLANG_OK;
+}
- void compareComputeResult(
- gfx::IDevice* device,
- gfx::ITextureResource* texture,
- gfx::ResourceState state,
- void* expectedResult,
- size_t expectedResultRowPitch,
- size_t rowCount)
+void compareComputeResult(
+ gfx::IDevice* device,
+ gfx::ITextureResource* texture,
+ gfx::ResourceState state,
+ void* expectedResult,
+ size_t expectedResultRowPitch,
+ size_t rowCount)
+{
+ // Read back the results.
+ ComPtr<ISlangBlob> resultBlob;
+ size_t rowPitch = 0;
+ size_t pixelSize = 0;
+ GFX_CHECK_CALL_ABORT(
+ device->readTextureResource(texture, state, resultBlob.writeRef(), &rowPitch, &pixelSize));
+ // Compare results.
+ for (size_t row = 0; row < rowCount; row++)
{
- // Read back the results.
- ComPtr<ISlangBlob> resultBlob;
- size_t rowPitch = 0;
- size_t pixelSize = 0;
- GFX_CHECK_CALL_ABORT(device->readTextureResource(
- texture, state, resultBlob.writeRef(), &rowPitch, &pixelSize));
- // Compare results.
- for (size_t row = 0; row < rowCount; row++)
- {
- SLANG_CHECK(
- memcmp(
- (uint8_t*)resultBlob->getBufferPointer() + rowPitch * row,
- (uint8_t*)expectedResult + expectedResultRowPitch * row,
- expectedResultRowPitch) == 0);
- }
+ SLANG_CHECK(
+ memcmp(
+ (uint8_t*)resultBlob->getBufferPointer() + rowPitch * row,
+ (uint8_t*)expectedResult + expectedResultRowPitch * row,
+ expectedResultRowPitch) == 0);
}
+}
- void compareComputeResult(gfx::IDevice* device, gfx::IBufferResource* buffer, size_t offset, const void* expectedResult, size_t expectedBufferSize)
- {
- // Read back the results.
- ComPtr<ISlangBlob> resultBlob;
- GFX_CHECK_CALL_ABORT(device->readBufferResource(
- buffer, offset, expectedBufferSize, resultBlob.writeRef()));
- SLANG_CHECK(resultBlob->getBufferSize() == expectedBufferSize);
- // Compare results.
- SLANG_CHECK(memcmp(resultBlob->getBufferPointer(), (uint8_t*)expectedResult, expectedBufferSize) == 0);
- }
+void compareComputeResult(
+ gfx::IDevice* device,
+ gfx::IBufferResource* buffer,
+ size_t offset,
+ const void* expectedResult,
+ size_t expectedBufferSize)
+{
+ // Read back the results.
+ ComPtr<ISlangBlob> resultBlob;
+ GFX_CHECK_CALL_ABORT(
+ device->readBufferResource(buffer, offset, expectedBufferSize, resultBlob.writeRef()));
+ SLANG_CHECK(resultBlob->getBufferSize() == expectedBufferSize);
+ // Compare results.
+ SLANG_CHECK(
+ memcmp(resultBlob->getBufferPointer(), (uint8_t*)expectedResult, expectedBufferSize) == 0);
+}
- void compareComputeResultFuzzy(const float* result, float* expectedResult, size_t expectedBufferSize)
+void compareComputeResultFuzzy(
+ const float* result,
+ float* expectedResult,
+ size_t expectedBufferSize)
+{
+ for (size_t i = 0; i < expectedBufferSize / sizeof(float); ++i)
{
- for (size_t i = 0; i < expectedBufferSize / sizeof(float); ++i)
- {
- SLANG_CHECK(abs(result[i] - expectedResult[i]) <= 0.01);
- }
+ SLANG_CHECK(abs(result[i] - expectedResult[i]) <= 0.01);
}
+}
- void compareComputeResultFuzzy(gfx::IDevice* device, gfx::IBufferResource* buffer, float* expectedResult, size_t expectedBufferSize)
- {
- // Read back the results.
- ComPtr<ISlangBlob> resultBlob;
- GFX_CHECK_CALL_ABORT(device->readBufferResource(
- buffer, 0, expectedBufferSize, resultBlob.writeRef()));
- SLANG_CHECK(resultBlob->getBufferSize() == expectedBufferSize);
- // Compare results with a tolerance of 0.01.
- auto result = (float*)resultBlob->getBufferPointer();
- compareComputeResultFuzzy(result, expectedResult, expectedBufferSize);
- }
+void compareComputeResultFuzzy(
+ gfx::IDevice* device,
+ gfx::IBufferResource* buffer,
+ float* expectedResult,
+ size_t expectedBufferSize)
+{
+ // Read back the results.
+ ComPtr<ISlangBlob> resultBlob;
+ GFX_CHECK_CALL_ABORT(
+ device->readBufferResource(buffer, 0, expectedBufferSize, resultBlob.writeRef()));
+ SLANG_CHECK(resultBlob->getBufferSize() == expectedBufferSize);
+ // Compare results with a tolerance of 0.01.
+ auto result = (float*)resultBlob->getBufferPointer();
+ compareComputeResultFuzzy(result, expectedResult, expectedBufferSize);
+}
- Slang::ComPtr<gfx::IDevice> createTestingDevice(
- UnitTestContext* context,
- Slang::RenderApiFlag::Enum api,
- Slang::List<const char*> additionalSearchPaths,
- gfx::IDevice::ShaderCacheDesc shaderCache)
+Slang::ComPtr<gfx::IDevice> createTestingDevice(
+ UnitTestContext* context,
+ Slang::RenderApiFlag::Enum api,
+ Slang::List<const char*> additionalSearchPaths,
+ gfx::IDevice::ShaderCacheDesc shaderCache)
+{
+ Slang::ComPtr<gfx::IDevice> device;
+ gfx::IDevice::Desc deviceDesc = {};
+ switch (api)
{
- Slang::ComPtr<gfx::IDevice> device;
- gfx::IDevice::Desc deviceDesc = {};
- switch (api)
- {
- case Slang::RenderApiFlag::D3D11:
- deviceDesc.deviceType = gfx::DeviceType::DirectX11;
- break;
- case Slang::RenderApiFlag::D3D12:
- deviceDesc.deviceType = gfx::DeviceType::DirectX12;
- break;
- case Slang::RenderApiFlag::Vulkan:
- deviceDesc.deviceType = gfx::DeviceType::Vulkan;
- break;
- case Slang::RenderApiFlag::CPU:
- deviceDesc.deviceType = gfx::DeviceType::CPU;
- break;
- case Slang::RenderApiFlag::CUDA:
- deviceDesc.deviceType = gfx::DeviceType::CUDA;
- break;
- default:
- SLANG_IGNORE_TEST
- }
- deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
- Slang::List<const char*> searchPaths = getSlangSearchPaths();
- searchPaths.addRange(additionalSearchPaths);
- deviceDesc.slang.searchPaths = searchPaths.getBuffer();
- deviceDesc.slang.searchPathCount = (gfx::GfxCount)searchPaths.getCount();
- deviceDesc.shaderCache = shaderCache;
-
- gfx::D3D12DeviceExtendedDesc extDesc = {};
- extDesc.rootParameterShaderAttributeName = "root";
-
- gfx::SlangSessionExtendedDesc slangExtDesc = {};
- Slang::List<slang::CompilerOptionEntry> entries;
- slang::CompilerOptionEntry emitSpirvDirectlyEntry;
- emitSpirvDirectlyEntry.name = slang::CompilerOptionName::EmitSpirvDirectly;
- emitSpirvDirectlyEntry.value.intValue0 = 1;
- entries.add(emitSpirvDirectlyEntry);
+ case Slang::RenderApiFlag::D3D11: deviceDesc.deviceType = gfx::DeviceType::DirectX11; break;
+ case Slang::RenderApiFlag::D3D12: deviceDesc.deviceType = gfx::DeviceType::DirectX12; break;
+ case Slang::RenderApiFlag::Vulkan: deviceDesc.deviceType = gfx::DeviceType::Vulkan; break;
+ case Slang::RenderApiFlag::CPU: deviceDesc.deviceType = gfx::DeviceType::CPU; break;
+ case Slang::RenderApiFlag::CUDA: deviceDesc.deviceType = gfx::DeviceType::CUDA; break;
+ default: SLANG_IGNORE_TEST
+ }
+ deviceDesc.slang.slangGlobalSession = context->slangGlobalSession;
+ Slang::List<const char*> searchPaths = getSlangSearchPaths();
+ searchPaths.addRange(additionalSearchPaths);
+ deviceDesc.slang.searchPaths = searchPaths.getBuffer();
+ deviceDesc.slang.searchPathCount = (gfx::GfxCount)searchPaths.getCount();
+ deviceDesc.shaderCache = shaderCache;
+
+ gfx::D3D12DeviceExtendedDesc extDesc = {};
+ extDesc.rootParameterShaderAttributeName = "root";
+
+ gfx::SlangSessionExtendedDesc slangExtDesc = {};
+ Slang::List<slang::CompilerOptionEntry> entries;
+ slang::CompilerOptionEntry emitSpirvDirectlyEntry;
+ emitSpirvDirectlyEntry.name = slang::CompilerOptionName::EmitSpirvDirectly;
+ emitSpirvDirectlyEntry.value.intValue0 = 1;
+ entries.add(emitSpirvDirectlyEntry);
#if GFX_ENABLE_SPIRV_DEBUG
- slang::CompilerOptionEntry debugLevelCompilerOptionEntry;
- debugLevelCompilerOptionEntry.name = slang::CompilerOptionName::DebugInformation;
- debugLevelCompilerOptionEntry.value.intValue0 = SLANG_DEBUG_INFO_LEVEL_STANDARD;
- entries.add(debugLevelCompilerOptionEntry);
+ slang::CompilerOptionEntry debugLevelCompilerOptionEntry;
+ debugLevelCompilerOptionEntry.name = slang::CompilerOptionName::DebugInformation;
+ debugLevelCompilerOptionEntry.value.intValue0 = SLANG_DEBUG_INFO_LEVEL_STANDARD;
+ entries.add(debugLevelCompilerOptionEntry);
#endif
- slangExtDesc.compilerOptionEntries = entries.getBuffer();
- slangExtDesc.compilerOptionEntryCount = (uint32_t)entries.getCount();
+ slangExtDesc.compilerOptionEntries = entries.getBuffer();
+ slangExtDesc.compilerOptionEntryCount = (uint32_t)entries.getCount();
- deviceDesc.extendedDescCount = 2;
- void* extDescPtrs[2] = { &extDesc, &slangExtDesc };
- deviceDesc.extendedDescs = extDescPtrs;
+ deviceDesc.extendedDescCount = 2;
+ void* extDescPtrs[2] = {&extDesc, &slangExtDesc};
+ deviceDesc.extendedDescs = extDescPtrs;
- // TODO: We should also set the debug callback
- // (And in general reduce the differences (and duplication) between
- // here and render-test-main.cpp)
+ // TODO: We should also set the debug callback
+ // (And in general reduce the differences (and duplication) between
+ // here and render-test-main.cpp)
#ifdef _DEBUG
- gfx::gfxEnableDebugLayer();
+ gfx::gfxEnableDebugLayer();
#endif
- auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
- if (SLANG_FAILED(createDeviceResult))
- {
- SLANG_IGNORE_TEST
- }
- return device;
- }
-
- Slang::List<const char*> getSlangSearchPaths()
+ auto createDeviceResult = gfxCreateDevice(&deviceDesc, device.writeRef());
+ if (SLANG_FAILED(createDeviceResult))
{
- Slang::List<const char*> searchPaths;
- searchPaths.add("");
- searchPaths.add("../../tools/gfx-unit-test");
- searchPaths.add("tools/gfx-unit-test");
- return searchPaths;
+ SLANG_IGNORE_TEST
}
+ return device;
+}
+
+Slang::List<const char*> getSlangSearchPaths()
+{
+ Slang::List<const char*> searchPaths;
+ searchPaths.add("");
+ searchPaths.add("../../tools/gfx-unit-test");
+ searchPaths.add("tools/gfx-unit-test");
+ return searchPaths;
+}
#if GFX_ENABLE_RENDERDOC_INTEGRATION
- RENDERDOC_API_1_1_2* rdoc_api = NULL;
- void initializeRenderDoc()
- {
- if (HMODULE mod = GetModuleHandleA("renderdoc.dll"))
- {
- pRENDERDOC_GetAPI RENDERDOC_GetAPI =
- (pRENDERDOC_GetAPI)GetProcAddress(mod, "RENDERDOC_GetAPI");
- int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_1_2, (void**)&rdoc_api);
- assert(ret == 1);
- }
- }
- void renderDocBeginFrame()
- {
- if (!rdoc_api) initializeRenderDoc();
- if (rdoc_api) rdoc_api->StartFrameCapture(nullptr, nullptr);
- }
- void renderDocEndFrame()
+RENDERDOC_API_1_1_2* rdoc_api = NULL;
+void initializeRenderDoc()
+{
+ if (HMODULE mod = GetModuleHandleA("renderdoc.dll"))
{
- if (rdoc_api)
- rdoc_api->EndFrameCapture(nullptr, nullptr);
- _fgetchar();
+ pRENDERDOC_GetAPI RENDERDOC_GetAPI =
+ (pRENDERDOC_GetAPI)GetProcAddress(mod, "RENDERDOC_GetAPI");
+ int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_1_2, (void**)&rdoc_api);
+ assert(ret == 1);
}
+}
+void renderDocBeginFrame()
+{
+ if (!rdoc_api)
+ initializeRenderDoc();
+ if (rdoc_api)
+ rdoc_api->StartFrameCapture(nullptr, nullptr);
+}
+void renderDocEndFrame()
+{
+ if (rdoc_api)
+ rdoc_api->EndFrameCapture(nullptr, nullptr);
+ _fgetchar();
+}
#else
- void initializeRenderDoc() {}
- void renderDocBeginFrame() {}
- void renderDocEndFrame() {}
+void initializeRenderDoc() {}
+void renderDocBeginFrame() {}
+void renderDocEndFrame() {}
#endif
-}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/gfx-test-util.h b/tools/gfx-unit-test/gfx-test-util.h
index 643830413..51b1feb1f 100644
--- a/tools/gfx-unit-test/gfx-test-util.h
+++ b/tools/gfx-unit-test/gfx-test-util.h
@@ -7,137 +7,143 @@
namespace gfx_test
{
- /// Helper function for print out diagnostic messages output by Slang compiler.
- void diagnoseIfNeeded(slang::IBlob* diagnosticsBlob);
-
- /// Loads a compute shader module and produces a `gfx::IShaderProgram`.
- Slang::Result loadComputeProgram(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- const char* shaderModuleName,
- const char* entryPointName,
- slang::ProgramLayout*& slangReflection);
-
- Slang::Result loadComputeProgram(
- gfx::IDevice* device,
- slang::ISession* slangSession,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- const char* shaderModuleName,
- const char* entryPointName,
- slang::ProgramLayout*& slangReflection);
-
- Slang::Result loadComputeProgramFromSource(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- Slang::String source);
-
- Slang::Result loadGraphicsProgram(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- const char* shaderModuleName,
- const char* vertexEntryPointName,
- const char* fragmentEntryPointName,
- slang::ProgramLayout*& slangReflection);
-
- /// Reads back the content of `buffer` and compares it against `expectedResult`.
- void compareComputeResult(
- gfx::IDevice* device,
- gfx::IBufferResource* buffer,
- size_t offset,
- const void* expectedResult,
- size_t expectedBufferSize);
-
- /// Reads back the content of `texture` and compares it against `expectedResult`.
- void compareComputeResult(
- gfx::IDevice* device,
- gfx::ITextureResource* texture,
- gfx::ResourceState state,
- void* expectedResult,
- size_t expectedResultRowPitch,
- size_t rowCount);
-
- void compareComputeResultFuzzy(
- const float* result,
- float* expectedResult,
- size_t expectedBufferSize);
-
- /// Reads back the content of `buffer` and compares it against `expectedResult` with a set tolerance.
- void compareComputeResultFuzzy(
- gfx::IDevice* device,
- gfx::IBufferResource* buffer,
- float* expectedResult,
- size_t expectedBufferSize);
-
- template<typename T, Slang::Index count>
- void compareComputeResult(
- gfx::IDevice* device,
- gfx::IBufferResource* buffer,
- Slang::Array<T, count> expectedResult)
+/// Helper function for print out diagnostic messages output by Slang compiler.
+void diagnoseIfNeeded(slang::IBlob* diagnosticsBlob);
+
+/// Loads a compute shader module and produces a `gfx::IShaderProgram`.
+Slang::Result loadComputeProgram(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ const char* shaderModuleName,
+ const char* entryPointName,
+ slang::ProgramLayout*& slangReflection);
+
+Slang::Result loadComputeProgram(
+ gfx::IDevice* device,
+ slang::ISession* slangSession,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ const char* shaderModuleName,
+ const char* entryPointName,
+ slang::ProgramLayout*& slangReflection);
+
+Slang::Result loadComputeProgramFromSource(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ Slang::String source);
+
+Slang::Result loadGraphicsProgram(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ const char* shaderModuleName,
+ const char* vertexEntryPointName,
+ const char* fragmentEntryPointName,
+ slang::ProgramLayout*& slangReflection);
+
+/// Reads back the content of `buffer` and compares it against `expectedResult`.
+void compareComputeResult(
+ gfx::IDevice* device,
+ gfx::IBufferResource* buffer,
+ size_t offset,
+ const void* expectedResult,
+ size_t expectedBufferSize);
+
+/// Reads back the content of `texture` and compares it against `expectedResult`.
+void compareComputeResult(
+ gfx::IDevice* device,
+ gfx::ITextureResource* texture,
+ gfx::ResourceState state,
+ void* expectedResult,
+ size_t expectedResultRowPitch,
+ size_t rowCount);
+
+void compareComputeResultFuzzy(
+ const float* result,
+ float* expectedResult,
+ size_t expectedBufferSize);
+
+/// Reads back the content of `buffer` and compares it against `expectedResult` with a set
+/// tolerance.
+void compareComputeResultFuzzy(
+ gfx::IDevice* device,
+ gfx::IBufferResource* buffer,
+ float* expectedResult,
+ size_t expectedBufferSize);
+
+template<typename T, Slang::Index count>
+void compareComputeResult(
+ gfx::IDevice* device,
+ gfx::IBufferResource* buffer,
+ Slang::Array<T, count> expectedResult)
+{
+ Slang::List<uint8_t> expectedBuffer;
+ size_t bufferSize = sizeof(T) * count;
+ expectedBuffer.setCount(bufferSize);
+ memcpy(expectedBuffer.getBuffer(), expectedResult.begin(), bufferSize);
+ if (std::is_same<T, float>::value)
+ return compareComputeResultFuzzy(
+ device,
+ buffer,
+ (float*)expectedBuffer.getBuffer(),
+ bufferSize);
+ return compareComputeResult(device, buffer, 0, expectedBuffer.getBuffer(), bufferSize);
+}
+
+Slang::ComPtr<gfx::IDevice> createTestingDevice(
+ UnitTestContext* context,
+ Slang::RenderApiFlag::Enum api,
+ Slang::List<const char*> additionalSearchPaths = {},
+ gfx::IDevice::ShaderCacheDesc shaderCache = {});
+
+Slang::List<const char*> getSlangSearchPaths();
+
+void initializeRenderDoc();
+void renderDocBeginFrame();
+void renderDocEndFrame();
+
+template<typename ImplFunc>
+void runTestImpl(
+ const ImplFunc& f,
+ UnitTestContext* context,
+ Slang::RenderApiFlag::Enum api,
+ Slang::List<const char*> searchPaths = {},
+ gfx::IDevice::ShaderCacheDesc shaderCache = {})
+{
+ if ((api & context->enabledApis) == 0)
{
- Slang::List<uint8_t> expectedBuffer;
- size_t bufferSize = sizeof(T) * count;
- expectedBuffer.setCount(bufferSize);
- memcpy(expectedBuffer.getBuffer(), expectedResult.begin(), bufferSize);
- if (std::is_same<T, float>::value) return compareComputeResultFuzzy(device, buffer, (float*)expectedBuffer.getBuffer(), bufferSize);
- return compareComputeResult(device, buffer, 0, expectedBuffer.getBuffer(), bufferSize);
+ SLANG_IGNORE_TEST
}
-
- Slang::ComPtr<gfx::IDevice> createTestingDevice(
- UnitTestContext* context,
- Slang::RenderApiFlag::Enum api,
- Slang::List<const char*> additionalSearchPaths = {},
- gfx::IDevice::ShaderCacheDesc shaderCache = {});
-
- Slang::List<const char*> getSlangSearchPaths();
-
- void initializeRenderDoc();
- void renderDocBeginFrame();
- void renderDocEndFrame();
-
- template<typename ImplFunc>
- void runTestImpl(
- const ImplFunc& f,
- UnitTestContext* context,
- Slang::RenderApiFlag::Enum api,
- Slang::List<const char*> searchPaths = {},
- gfx::IDevice::ShaderCacheDesc shaderCache = {})
+ auto device = createTestingDevice(context, api, searchPaths, shaderCache);
+ if (!device)
{
- if ((api & context->enabledApis) == 0)
- {
- SLANG_IGNORE_TEST
- }
- auto device = createTestingDevice(context, api, searchPaths, shaderCache);
- if (!device)
- {
- SLANG_IGNORE_TEST
- }
+ SLANG_IGNORE_TEST
+ }
#if SLANG_WIN32
- // Skip d3d12 tests on x86 now since dxc doesn't function correctly there on Windows 11.
- if (api == Slang::RenderApiFlag::D3D12)
- {
- SLANG_IGNORE_TEST
- }
+ // Skip d3d12 tests on x86 now since dxc doesn't function correctly there on Windows 11.
+ if (api == Slang::RenderApiFlag::D3D12)
+ {
+ SLANG_IGNORE_TEST
+ }
#endif
- // Skip d3d11 tests when we don't have DXBC support as they're bound to
- // fail without a backend compiler
- if (api == Slang::RenderApiFlag::D3D11 && !SLANG_ENABLE_DXBC_SUPPORT)
- {
- SLANG_IGNORE_TEST
- }
- try
- {
- renderDocBeginFrame();
- f(device, context);
- }
- catch (AbortTestException& e)
- {
- renderDocEndFrame();
- throw e;
- }
+ // Skip d3d11 tests when we don't have DXBC support as they're bound to
+ // fail without a backend compiler
+ if (api == Slang::RenderApiFlag::D3D11 && !SLANG_ENABLE_DXBC_SUPPORT)
+ {
+ SLANG_IGNORE_TEST
+ }
+ try
+ {
+ renderDocBeginFrame();
+ f(device, context);
+ }
+ catch (AbortTestException& e)
+ {
renderDocEndFrame();
+ throw e;
}
+ renderDocEndFrame();
+}
#define GFX_CHECK_CALL(x) SLANG_CHECK(!SLANG_FAILED(x))
#define GFX_CHECK_CALL_ABORT(x) SLANG_CHECK_ABORT(!SLANG_FAILED(x))
-}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/instanced-draw-tests.cpp b/tools/gfx-unit-test/instanced-draw-tests.cpp
index 6491e8944..adb1a1df1 100644
--- a/tools/gfx-unit-test/instanced-draw-tests.cpp
+++ b/tools/gfx-unit-test/instanced-draw-tests.cpp
@@ -1,550 +1,604 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- struct Vertex
- {
- float position[3];
- };
-
- struct Instance
- {
- float position[3];
- float color[3];
- };
+struct Vertex
+{
+ float position[3];
+};
- static const int kVertexCount = 6;
- static const Vertex kVertexData[kVertexCount] =
- {
- // Triangle 1
- { 0, 0, 0.5 },
- { 1, 0, 0.5 },
- { 0, 1, 0.5 },
-
- // Triangle 2
- { -1, 0, 0.5 },
- { 0, 0, 0.5 },
- { -1, 1, 0.5 },
- };
+struct Instance
+{
+ float position[3];
+ float color[3];
+};
+
+static const int kVertexCount = 6;
+static const Vertex kVertexData[kVertexCount] = {
+ // Triangle 1
+ {0, 0, 0.5},
+ {1, 0, 0.5},
+ {0, 1, 0.5},
+
+ // Triangle 2
+ {-1, 0, 0.5},
+ {0, 0, 0.5},
+ {-1, 1, 0.5},
+};
+
+static const int kInstanceCount = 2;
+static const Instance kInstanceData[kInstanceCount] = {
+ {{0, 0, 0}, {1, 0, 0}},
+ {{0, -1, 0}, {0, 0, 1}},
+};
+
+static const int kIndexCount = 6;
+static const uint32_t kIndexData[kIndexCount] = {
+ 0,
+ 2,
+ 5,
+ 0,
+ 1,
+ 2,
+};
+
+const int kWidth = 256;
+const int kHeight = 256;
+const Format format = Format::R32G32B32A32_FLOAT;
+
+ComPtr<IBufferResource> createVertexBuffer(IDevice* device)
+{
+ IBufferResource::Desc vertexBufferDesc;
+ vertexBufferDesc.type = IResource::Type::Buffer;
+ vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
+ vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
+ vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
+ ComPtr<IBufferResource> vertexBuffer =
+ device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
+ SLANG_CHECK_ABORT(vertexBuffer != nullptr);
+ return vertexBuffer;
+}
- static const int kInstanceCount = 2;
- static const Instance kInstanceData[kInstanceCount] =
- {
- { { 0, 0, 0 }, { 1, 0, 0 } },
- { { 0, -1, 0 }, { 0, 0, 1 } },
- };
+ComPtr<IBufferResource> createInstanceBuffer(IDevice* device)
+{
+ IBufferResource::Desc instanceBufferDesc;
+ instanceBufferDesc.type = IResource::Type::Buffer;
+ instanceBufferDesc.sizeInBytes = kInstanceCount * sizeof(Instance);
+ instanceBufferDesc.defaultState = ResourceState::VertexBuffer;
+ instanceBufferDesc.allowedStates = ResourceState::VertexBuffer;
+ ComPtr<IBufferResource> instanceBuffer =
+ device->createBufferResource(instanceBufferDesc, &kInstanceData[0]);
+ SLANG_CHECK_ABORT(instanceBuffer != nullptr);
+ return instanceBuffer;
+}
- static const int kIndexCount = 6;
- static const uint32_t kIndexData[kIndexCount] =
- {
- 0, 2, 5,
- 0, 1, 2,
- };
+ComPtr<IBufferResource> createIndexBuffer(IDevice* device)
+{
+ IBufferResource::Desc indexBufferDesc;
+ indexBufferDesc.type = IResource::Type::Buffer;
+ indexBufferDesc.sizeInBytes = kIndexCount * sizeof(uint32_t);
+ indexBufferDesc.defaultState = ResourceState::IndexBuffer;
+ indexBufferDesc.allowedStates = ResourceState::IndexBuffer;
+ ComPtr<IBufferResource> indexBuffer =
+ device->createBufferResource(indexBufferDesc, &kIndexData[0]);
+ SLANG_CHECK_ABORT(indexBuffer != nullptr);
+ return indexBuffer;
+}
- const int kWidth = 256;
- const int kHeight = 256;
- const Format format = Format::R32G32B32A32_FLOAT;
+ComPtr<ITextureResource> createColorBuffer(IDevice* device)
+{
+ gfx::ITextureResource::Desc colorBufferDesc;
+ colorBufferDesc.type = IResource::Type::Texture2D;
+ colorBufferDesc.size.width = kWidth;
+ colorBufferDesc.size.height = kHeight;
+ colorBufferDesc.size.depth = 1;
+ colorBufferDesc.numMipLevels = 1;
+ colorBufferDesc.format = format;
+ colorBufferDesc.defaultState = ResourceState::RenderTarget;
+ colorBufferDesc.allowedStates = {ResourceState::RenderTarget, ResourceState::CopySource};
+ ComPtr<ITextureResource> colorBuffer = device->createTextureResource(colorBufferDesc, nullptr);
+ SLANG_CHECK_ABORT(colorBuffer != nullptr);
+ return colorBuffer;
+}
- ComPtr<IBufferResource> createVertexBuffer(IDevice* device)
- {
- IBufferResource::Desc vertexBufferDesc;
- vertexBufferDesc.type = IResource::Type::Buffer;
- vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
- vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
- vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
- ComPtr<IBufferResource> vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
- SLANG_CHECK_ABORT(vertexBuffer != nullptr);
- return vertexBuffer;
- }
+class BaseDrawTest
+{
+public:
+ ComPtr<IDevice> device;
+ UnitTestContext* context;
- ComPtr<IBufferResource> createInstanceBuffer(IDevice* device)
- {
- IBufferResource::Desc instanceBufferDesc;
- instanceBufferDesc.type = IResource::Type::Buffer;
- instanceBufferDesc.sizeInBytes = kInstanceCount * sizeof(Instance);
- instanceBufferDesc.defaultState = ResourceState::VertexBuffer;
- instanceBufferDesc.allowedStates = ResourceState::VertexBuffer;
- ComPtr<IBufferResource> instanceBuffer = device->createBufferResource(instanceBufferDesc, &kInstanceData[0]);
- SLANG_CHECK_ABORT(instanceBuffer != nullptr);
- return instanceBuffer;
- }
+ ComPtr<ITransientResourceHeap> transientHeap;
+ ComPtr<IPipelineState> pipelineState;
+ ComPtr<IRenderPassLayout> renderPass;
+ ComPtr<IFramebuffer> framebuffer;
- ComPtr<IBufferResource> createIndexBuffer(IDevice* device)
- {
- IBufferResource::Desc indexBufferDesc;
- indexBufferDesc.type = IResource::Type::Buffer;
- indexBufferDesc.sizeInBytes = kIndexCount * sizeof(uint32_t);
- indexBufferDesc.defaultState = ResourceState::IndexBuffer;
- indexBufferDesc.allowedStates = ResourceState::IndexBuffer;
- ComPtr<IBufferResource> indexBuffer = device->createBufferResource(indexBufferDesc, &kIndexData[0]);
- SLANG_CHECK_ABORT(indexBuffer != nullptr);
- return indexBuffer;
- }
+ ComPtr<IBufferResource> vertexBuffer;
+ ComPtr<IBufferResource> instanceBuffer;
+ ComPtr<ITextureResource> colorBuffer;
- ComPtr<ITextureResource> createColorBuffer(IDevice* device)
+ void init(IDevice* device, UnitTestContext* context)
{
- gfx::ITextureResource::Desc colorBufferDesc;
- colorBufferDesc.type = IResource::Type::Texture2D;
- colorBufferDesc.size.width = kWidth;
- colorBufferDesc.size.height = kHeight;
- colorBufferDesc.size.depth = 1;
- colorBufferDesc.numMipLevels = 1;
- colorBufferDesc.format = format;
- colorBufferDesc.defaultState = ResourceState::RenderTarget;
- colorBufferDesc.allowedStates = { ResourceState::RenderTarget, ResourceState::CopySource };
- ComPtr<ITextureResource> colorBuffer = device->createTextureResource(colorBufferDesc, nullptr);
- SLANG_CHECK_ABORT(colorBuffer != nullptr);
- return colorBuffer;
+ this->device = device;
+ this->context = context;
}
- class BaseDrawTest
+ void createRequiredResources()
{
- public:
- ComPtr<IDevice> device;
- UnitTestContext* context;
-
- ComPtr<ITransientResourceHeap> transientHeap;
- ComPtr<IPipelineState> pipelineState;
- ComPtr<IRenderPassLayout> renderPass;
- ComPtr<IFramebuffer> framebuffer;
+ VertexStreamDesc vertexStreams[] = {
+ {sizeof(Vertex), InputSlotClass::PerVertex, 0},
+ {sizeof(Instance), InputSlotClass::PerInstance, 1},
+ };
- ComPtr<IBufferResource> vertexBuffer;
- ComPtr<IBufferResource> instanceBuffer;
- ComPtr<ITextureResource> colorBuffer;
+ InputElementDesc inputElements[] = {
+ // Vertex buffer data
+ {"POSITIONA", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0},
- void init(IDevice* device, UnitTestContext* context)
- {
- this->device = device;
- this->context = context;
- }
-
- void createRequiredResources()
- {
- VertexStreamDesc vertexStreams[] = {
- { sizeof(Vertex), InputSlotClass::PerVertex, 0 },
- { sizeof(Instance), InputSlotClass::PerInstance, 1 },
- };
-
- InputElementDesc inputElements[] = {
- // Vertex buffer data
- { "POSITIONA", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0 },
-
- // Instance buffer data
- { "POSITIONB", 0, Format::R32G32B32_FLOAT, offsetof(Instance, position), 1 },
- { "COLOR", 0, Format::R32G32B32_FLOAT, offsetof(Instance, color), 1 },
- };
- IInputLayout::Desc inputLayoutDesc = {};
- inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
- inputLayoutDesc.inputElements = inputElements;
- inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
- inputLayoutDesc.vertexStreams = vertexStreams;
- auto inputLayout = device->createInputLayout(inputLayoutDesc);
- SLANG_CHECK_ABORT(inputLayout != nullptr);
-
- vertexBuffer = createVertexBuffer(device);
- instanceBuffer = createInstanceBuffer(device);
- colorBuffer = createColorBuffer(device);
-
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadGraphicsProgram(device, shaderProgram, "graphics-smoke", "vertexMain", "fragmentMain", slangReflection));
-
- IFramebufferLayout::TargetLayout targetLayout;
- targetLayout.format = format;
- targetLayout.sampleCount = 1;
-
- IFramebufferLayout::Desc framebufferLayoutDesc;
- framebufferLayoutDesc.renderTargetCount = 1;
- framebufferLayoutDesc.renderTargets = &targetLayout;
- ComPtr<gfx::IFramebufferLayout> framebufferLayout = device->createFramebufferLayout(framebufferLayoutDesc);
- SLANG_CHECK_ABORT(framebufferLayout != nullptr);
-
- GraphicsPipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- pipelineDesc.inputLayout = inputLayout;
- pipelineDesc.framebufferLayout = framebufferLayout;
- pipelineDesc.depthStencil.depthTestEnable = false;
- pipelineDesc.depthStencil.depthWriteEnable = false;
- GFX_CHECK_CALL_ABORT(
- device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
-
- IRenderPassLayout::Desc renderPassDesc = {};
- renderPassDesc.framebufferLayout = framebufferLayout;
- renderPassDesc.renderTargetCount = 1;
- IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
- renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
- renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
- renderTargetAccess.initialState = ResourceState::RenderTarget;
- renderTargetAccess.finalState = ResourceState::CopySource;
- renderPassDesc.renderTargetAccess = &renderTargetAccess;
- GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
-
- gfx::IResourceView::Desc colorBufferViewDesc;
- memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
- colorBufferViewDesc.format = format;
- colorBufferViewDesc.renderTarget.shape = gfx::IResource::Type::Texture2D;
- colorBufferViewDesc.type = gfx::IResourceView::Type::RenderTarget;
- auto rtv = device->createTextureView(colorBuffer, colorBufferViewDesc);
-
- gfx::IFramebuffer::Desc framebufferDesc;
- framebufferDesc.renderTargetCount = 1;
- framebufferDesc.depthStencilView = nullptr;
- framebufferDesc.renderTargetViews = rtv.readRef();
- framebufferDesc.layout = framebufferLayout;
- GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
- }
+ // Instance buffer data
+ {"POSITIONB", 0, Format::R32G32B32_FLOAT, offsetof(Instance, position), 1},
+ {"COLOR", 0, Format::R32G32B32_FLOAT, offsetof(Instance, color), 1},
+ };
+ IInputLayout::Desc inputLayoutDesc = {};
+ inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
+ inputLayoutDesc.inputElements = inputElements;
+ inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
+ inputLayoutDesc.vertexStreams = vertexStreams;
+ auto inputLayout = device->createInputLayout(inputLayoutDesc);
+ SLANG_CHECK_ABORT(inputLayout != nullptr);
+
+ vertexBuffer = createVertexBuffer(device);
+ instanceBuffer = createInstanceBuffer(device);
+ colorBuffer = createColorBuffer(device);
+
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadGraphicsProgram(
+ device,
+ shaderProgram,
+ "graphics-smoke",
+ "vertexMain",
+ "fragmentMain",
+ slangReflection));
+
+ IFramebufferLayout::TargetLayout targetLayout;
+ targetLayout.format = format;
+ targetLayout.sampleCount = 1;
+
+ IFramebufferLayout::Desc framebufferLayoutDesc;
+ framebufferLayoutDesc.renderTargetCount = 1;
+ framebufferLayoutDesc.renderTargets = &targetLayout;
+ ComPtr<gfx::IFramebufferLayout> framebufferLayout =
+ device->createFramebufferLayout(framebufferLayoutDesc);
+ SLANG_CHECK_ABORT(framebufferLayout != nullptr);
+
+ GraphicsPipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ pipelineDesc.inputLayout = inputLayout;
+ pipelineDesc.framebufferLayout = framebufferLayout;
+ pipelineDesc.depthStencil.depthTestEnable = false;
+ pipelineDesc.depthStencil.depthWriteEnable = false;
+ GFX_CHECK_CALL_ABORT(
+ device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ IRenderPassLayout::Desc renderPassDesc = {};
+ renderPassDesc.framebufferLayout = framebufferLayout;
+ renderPassDesc.renderTargetCount = 1;
+ IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
+ renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
+ renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
+ renderTargetAccess.initialState = ResourceState::RenderTarget;
+ renderTargetAccess.finalState = ResourceState::CopySource;
+ renderPassDesc.renderTargetAccess = &renderTargetAccess;
+ GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
+
+ gfx::IResourceView::Desc colorBufferViewDesc;
+ memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
+ colorBufferViewDesc.format = format;
+ colorBufferViewDesc.renderTarget.shape = gfx::IResource::Type::Texture2D;
+ colorBufferViewDesc.type = gfx::IResourceView::Type::RenderTarget;
+ auto rtv = device->createTextureView(colorBuffer, colorBufferViewDesc);
+
+ gfx::IFramebuffer::Desc framebufferDesc;
+ framebufferDesc.renderTargetCount = 1;
+ framebufferDesc.depthStencilView = nullptr;
+ framebufferDesc.renderTargetViews = rtv.readRef();
+ framebufferDesc.layout = framebufferLayout;
+ GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
+ }
- void checkTestResults(int pixelCount, int channelCount, const int* testXCoords, const int* testYCoords, float* testResults)
+ void checkTestResults(
+ int pixelCount,
+ int channelCount,
+ const int* testXCoords,
+ const int* testYCoords,
+ float* testResults)
+ {
+ // Read texture values back from four specific pixels located within the triangles
+ // and compare against expected values (because testing every single pixel will be too long
+ // and tedious and requires maintaining reference images).
+ ComPtr<ISlangBlob> resultBlob;
+ size_t rowPitch = 0;
+ size_t pixelSize = 0;
+ GFX_CHECK_CALL_ABORT(device->readTextureResource(
+ colorBuffer,
+ ResourceState::CopySource,
+ resultBlob.writeRef(),
+ &rowPitch,
+ &pixelSize));
+ auto result = (float*)resultBlob->getBufferPointer();
+
+ int cursor = 0;
+ for (int i = 0; i < pixelCount; ++i)
{
- // Read texture values back from four specific pixels located within the triangles
- // and compare against expected values (because testing every single pixel will be too long and tedious
- // and requires maintaining reference images).
- ComPtr<ISlangBlob> resultBlob;
- size_t rowPitch = 0;
- size_t pixelSize = 0;
- GFX_CHECK_CALL_ABORT(device->readTextureResource(
- colorBuffer, ResourceState::CopySource, resultBlob.writeRef(), &rowPitch, &pixelSize));
- auto result = (float*)resultBlob->getBufferPointer();
-
- int cursor = 0;
- for (int i = 0; i < pixelCount; ++i)
+ auto x = testXCoords[i];
+ auto y = testYCoords[i];
+ auto pixelPtr = result + x * channelCount + y * rowPitch / sizeof(float);
+ for (int j = 0; j < channelCount; ++j)
{
- auto x = testXCoords[i];
- auto y = testYCoords[i];
- auto pixelPtr = result + x * channelCount + y * rowPitch / sizeof(float);
- for (int j = 0; j < channelCount; ++j)
- {
- testResults[cursor] = pixelPtr[j];
- cursor++;
- }
+ testResults[cursor] = pixelPtr[j];
+ cursor++;
}
-
- float expectedResult[] = { 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f };
- compareComputeResultFuzzy(testResults, expectedResult, sizeof(expectedResult));
}
- };
- struct DrawInstancedTest : BaseDrawTest
+ float expectedResult[] = {
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f};
+ compareComputeResultFuzzy(testResults, expectedResult, sizeof(expectedResult));
+ }
+};
+
+struct DrawInstancedTest : BaseDrawTest
+{
+ void setUpAndDraw()
{
- void setUpAndDraw()
- {
- createRequiredResources();
+ createRequiredResources();
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+ auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
- auto rootObject = encoder->bindPipeline(pipelineState);
+ auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
+ auto rootObject = encoder->bindPipeline(pipelineState);
- gfx::Viewport viewport = {};
- viewport.maxZ = 1.0f;
- viewport.extentX = kWidth;
- viewport.extentY = kHeight;
- encoder->setViewportAndScissor(viewport);
+ gfx::Viewport viewport = {};
+ viewport.maxZ = 1.0f;
+ viewport.extentX = kWidth;
+ viewport.extentY = kHeight;
+ encoder->setViewportAndScissor(viewport);
- uint32_t startVertex = 0;
- uint32_t startInstanceLocation = 0;
+ uint32_t startVertex = 0;
+ uint32_t startInstanceLocation = 0;
- encoder->setVertexBuffer(0, vertexBuffer);
- encoder->setVertexBuffer(1, instanceBuffer);
- encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
+ encoder->setVertexBuffer(0, vertexBuffer);
+ encoder->setVertexBuffer(1, instanceBuffer);
+ encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
- encoder->drawInstanced(kVertexCount, kInstanceCount, startVertex, startInstanceLocation);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ encoder->drawInstanced(kVertexCount, kInstanceCount, startVertex, startInstanceLocation);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- void run()
- {
- setUpAndDraw();
+ void run()
+ {
+ setUpAndDraw();
- const int kPixelCount = 4;
- const int kChannelCount = 4;
- int testXCoords[kPixelCount] = { 64, 192, 64, 192 };
- int testYCoords[kPixelCount] = { 100, 100, 250, 250 };
- float testResults[kPixelCount * kChannelCount];
+ const int kPixelCount = 4;
+ const int kChannelCount = 4;
+ int testXCoords[kPixelCount] = {64, 192, 64, 192};
+ int testYCoords[kPixelCount] = {100, 100, 250, 250};
+ float testResults[kPixelCount * kChannelCount];
- checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
- }
- };
+ checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
+ }
+};
+
+struct DrawIndexedInstancedTest : BaseDrawTest
+{
+ ComPtr<IBufferResource> indexBuffer;
- struct DrawIndexedInstancedTest : BaseDrawTest
+ void setUpAndDraw()
{
- ComPtr<IBufferResource> indexBuffer;
+ createRequiredResources();
+
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+
+ auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ gfx::Viewport viewport = {};
+ viewport.maxZ = 1.0f;
+ viewport.extentX = kWidth;
+ viewport.extentY = kHeight;
+ encoder->setViewportAndScissor(viewport);
+
+ uint32_t startIndex = 0;
+ int32_t startVertex = 0;
+ uint32_t startInstanceLocation = 0;
+
+ encoder->setVertexBuffer(0, vertexBuffer);
+ encoder->setVertexBuffer(1, instanceBuffer);
+ encoder->setIndexBuffer(indexBuffer, Format::R32_UINT);
+ encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
+
+ encoder->drawIndexedInstanced(
+ kIndexCount,
+ kInstanceCount,
+ startIndex,
+ startVertex,
+ startInstanceLocation);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- void setUpAndDraw()
- {
- createRequiredResources();
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
-
- auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- gfx::Viewport viewport = {};
- viewport.maxZ = 1.0f;
- viewport.extentX = kWidth;
- viewport.extentY = kHeight;
- encoder->setViewportAndScissor(viewport);
-
- uint32_t startIndex = 0;
- int32_t startVertex = 0;
- uint32_t startInstanceLocation = 0;
-
- encoder->setVertexBuffer(0, vertexBuffer);
- encoder->setVertexBuffer(1, instanceBuffer);
- encoder->setIndexBuffer(indexBuffer, Format::R32_UINT);
- encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
-
- encoder->drawIndexedInstanced(kIndexCount, kInstanceCount, startIndex, startVertex, startInstanceLocation);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ void run()
+ {
+ indexBuffer = createIndexBuffer(device);
- void run()
- {
- indexBuffer = createIndexBuffer(device);
+ setUpAndDraw();
- setUpAndDraw();
+ const int kPixelCount = 4;
+ const int kChannelCount = 4;
+ int testXCoords[kPixelCount] = {64, 192, 64, 192};
+ int testYCoords[kPixelCount] = {32, 100, 150, 250};
+ float testResults[kPixelCount * kChannelCount];
- const int kPixelCount = 4;
- const int kChannelCount = 4;
- int testXCoords[kPixelCount] = { 64, 192, 64, 192 };
- int testYCoords[kPixelCount] = { 32, 100, 150, 250 };
- float testResults[kPixelCount * kChannelCount];
+ checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
+ }
+};
- checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
- }
- };
+struct DrawIndirectTest : BaseDrawTest
+{
+ ComPtr<IBufferResource> indirectBuffer;
- struct DrawIndirectTest : BaseDrawTest
+ struct IndirectArgData
{
- ComPtr<IBufferResource> indirectBuffer;
+ float padding; // Ensure args and count don't start at 0 offset for testing purposes
+ IndirectDrawArguments args;
+ };
- struct IndirectArgData
- {
- float padding; // Ensure args and count don't start at 0 offset for testing purposes
- IndirectDrawArguments args;
+ ComPtr<IBufferResource> createIndirectBuffer(IDevice* device)
+ {
+ static const IndirectArgData kIndirectData = {
+ 42.0f, // padding
+ {6, 2, 0, 0}, // args
};
- ComPtr<IBufferResource> createIndirectBuffer(IDevice* device)
- {
- static const IndirectArgData kIndirectData =
- {
- 42.0f, // padding
- {6, 2, 0, 0}, // args
- };
-
- IBufferResource::Desc indirectBufferDesc;
- indirectBufferDesc.type = IResource::Type::Buffer;
- indirectBufferDesc.sizeInBytes = sizeof(IndirectArgData);
- indirectBufferDesc.defaultState = ResourceState::IndirectArgument;
- indirectBufferDesc.allowedStates = ResourceState::IndirectArgument;
- ComPtr<IBufferResource> indirectBuffer = device->createBufferResource(indirectBufferDesc, &kIndirectData);
- SLANG_CHECK_ABORT(indirectBuffer != nullptr);
- return indirectBuffer;
- }
-
- void setUpAndDraw()
- {
- createRequiredResources();
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
+ IBufferResource::Desc indirectBufferDesc;
+ indirectBufferDesc.type = IResource::Type::Buffer;
+ indirectBufferDesc.sizeInBytes = sizeof(IndirectArgData);
+ indirectBufferDesc.defaultState = ResourceState::IndirectArgument;
+ indirectBufferDesc.allowedStates = ResourceState::IndirectArgument;
+ ComPtr<IBufferResource> indirectBuffer =
+ device->createBufferResource(indirectBufferDesc, &kIndirectData);
+ SLANG_CHECK_ABORT(indirectBuffer != nullptr);
+ return indirectBuffer;
+ }
- auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
- auto rootObject = encoder->bindPipeline(pipelineState);
+ void setUpAndDraw()
+ {
+ createRequiredResources();
- gfx::Viewport viewport = {};
- viewport.maxZ = 1.0f;
- viewport.extentX = kWidth;
- viewport.extentY = kHeight;
- encoder->setViewportAndScissor(viewport);
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+ auto commandBuffer = transientHeap->createCommandBuffer();
- encoder->setVertexBuffer(0, vertexBuffer);
- encoder->setVertexBuffer(1, instanceBuffer);
- encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
+ auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
+ auto rootObject = encoder->bindPipeline(pipelineState);
- uint32_t maxDrawCount = 1;
- Offset argOffset = offsetof(IndirectArgData, args);
+ gfx::Viewport viewport = {};
+ viewport.maxZ = 1.0f;
+ viewport.extentX = kWidth;
+ viewport.extentY = kHeight;
+ encoder->setViewportAndScissor(viewport);
- encoder->drawIndirect(maxDrawCount, indirectBuffer, argOffset);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- void run()
- {
- indirectBuffer = createIndirectBuffer(device);
+ encoder->setVertexBuffer(0, vertexBuffer);
+ encoder->setVertexBuffer(1, instanceBuffer);
+ encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
- setUpAndDraw();
+ uint32_t maxDrawCount = 1;
+ Offset argOffset = offsetof(IndirectArgData, args);
- const int kPixelCount = 4;
- const int kChannelCount = 4;
- int testXCoords[kPixelCount] = { 64, 192, 64, 192 };
- int testYCoords[kPixelCount] = { 100, 100, 250, 250 };
- float testResults[kPixelCount * kChannelCount];
-
- checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
- }
- };
+ encoder->drawIndirect(maxDrawCount, indirectBuffer, argOffset);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- struct DrawIndexedIndirectTest : BaseDrawTest
+ void run()
{
- ComPtr<IBufferResource> indexBuffer;
- ComPtr<IBufferResource> indirectBuffer;
-
- struct IndexedIndirectArgData
- {
- float padding; // Ensure args and count don't start at 0 offset for testing purposes
- IndirectDrawIndexedArguments args;
- };
-
- ComPtr<IBufferResource> createIndirectBuffer(IDevice* device)
- {
- static const IndexedIndirectArgData kIndexedIndirectData =
- {
- 42.0f, // padding
- {6, 2, 0, 0, 0}, // args
- };
-
- IBufferResource::Desc indirectBufferDesc;
- indirectBufferDesc.type = IResource::Type::Buffer;
- indirectBufferDesc.sizeInBytes = sizeof(IndexedIndirectArgData);
- indirectBufferDesc.defaultState = ResourceState::IndirectArgument;
- indirectBufferDesc.allowedStates = ResourceState::IndirectArgument;
- ComPtr<IBufferResource> indexBuffer = device->createBufferResource(indirectBufferDesc, &kIndexedIndirectData);
- SLANG_CHECK_ABORT(indexBuffer != nullptr);
- return indexBuffer;
- }
+ indirectBuffer = createIndirectBuffer(device);
- void setUpAndDraw()
- {
- createRequiredResources();
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
-
- auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- gfx::Viewport viewport = {};
- viewport.maxZ = 1.0f;
- viewport.extentX = kWidth;
- viewport.extentY = kHeight;
- encoder->setViewportAndScissor(viewport);
-
- encoder->setVertexBuffer(0, vertexBuffer);
- encoder->setVertexBuffer(1, instanceBuffer);
- encoder->setIndexBuffer(indexBuffer, Format::R32_UINT);
- encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
-
- uint32_t maxDrawCount = 1;
- Offset argOffset = offsetof(IndexedIndirectArgData, args);
-
- encoder->drawIndexedIndirect(maxDrawCount, indirectBuffer, argOffset);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ setUpAndDraw();
- void run()
- {
- indexBuffer = createIndexBuffer(device);
- indirectBuffer = createIndirectBuffer(device);
+ const int kPixelCount = 4;
+ const int kChannelCount = 4;
+ int testXCoords[kPixelCount] = {64, 192, 64, 192};
+ int testYCoords[kPixelCount] = {100, 100, 250, 250};
+ float testResults[kPixelCount * kChannelCount];
- setUpAndDraw();
+ checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
+ }
+};
- const int kPixelCount = 4;
- const int kChannelCount = 4;
- int testXCoords[kPixelCount] = { 64, 192, 64, 192 };
- int testYCoords[kPixelCount] = { 32, 100, 150, 250 };
- float testResults[kPixelCount * kChannelCount];
+struct DrawIndexedIndirectTest : BaseDrawTest
+{
+ ComPtr<IBufferResource> indexBuffer;
+ ComPtr<IBufferResource> indirectBuffer;
- checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
- }
+ struct IndexedIndirectArgData
+ {
+ float padding; // Ensure args and count don't start at 0 offset for testing purposes
+ IndirectDrawIndexedArguments args;
};
- template <typename T>
- void drawTestImpl(IDevice* device, UnitTestContext* context)
+ ComPtr<IBufferResource> createIndirectBuffer(IDevice* device)
{
- T test;
- test.init(device, context);
- test.run();
- }
+ static const IndexedIndirectArgData kIndexedIndirectData = {
+ 42.0f, // padding
+ {6, 2, 0, 0, 0}, // args
+ };
- SLANG_UNIT_TEST(drawInstancedD3D11)
- {
- runTestImpl(drawTestImpl<DrawInstancedTest>, unitTestContext, Slang::RenderApiFlag::D3D11);
+ IBufferResource::Desc indirectBufferDesc;
+ indirectBufferDesc.type = IResource::Type::Buffer;
+ indirectBufferDesc.sizeInBytes = sizeof(IndexedIndirectArgData);
+ indirectBufferDesc.defaultState = ResourceState::IndirectArgument;
+ indirectBufferDesc.allowedStates = ResourceState::IndirectArgument;
+ ComPtr<IBufferResource> indexBuffer =
+ device->createBufferResource(indirectBufferDesc, &kIndexedIndirectData);
+ SLANG_CHECK_ABORT(indexBuffer != nullptr);
+ return indexBuffer;
}
- SLANG_UNIT_TEST(drawIndexedInstancedD3D11)
+ void setUpAndDraw()
{
- runTestImpl(drawTestImpl<DrawIndexedInstancedTest>, unitTestContext, Slang::RenderApiFlag::D3D11);
+ createRequiredResources();
+
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+
+ auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ gfx::Viewport viewport = {};
+ viewport.maxZ = 1.0f;
+ viewport.extentX = kWidth;
+ viewport.extentY = kHeight;
+ encoder->setViewportAndScissor(viewport);
+
+ encoder->setVertexBuffer(0, vertexBuffer);
+ encoder->setVertexBuffer(1, instanceBuffer);
+ encoder->setIndexBuffer(indexBuffer, Format::R32_UINT);
+ encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
+
+ uint32_t maxDrawCount = 1;
+ Offset argOffset = offsetof(IndexedIndirectArgData, args);
+
+ encoder->drawIndexedIndirect(maxDrawCount, indirectBuffer, argOffset);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(drawInstancedD3D12)
+ void run()
{
- runTestImpl(drawTestImpl<DrawInstancedTest>, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ indexBuffer = createIndexBuffer(device);
+ indirectBuffer = createIndirectBuffer(device);
- SLANG_UNIT_TEST(drawIndexedInstancedD3D12)
- {
- runTestImpl(drawTestImpl<DrawIndexedInstancedTest>, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ setUpAndDraw();
- SLANG_UNIT_TEST(drawIndirectD3D12)
- {
- runTestImpl(drawTestImpl<DrawIndirectTest>, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ const int kPixelCount = 4;
+ const int kChannelCount = 4;
+ int testXCoords[kPixelCount] = {64, 192, 64, 192};
+ int testYCoords[kPixelCount] = {32, 100, 150, 250};
+ float testResults[kPixelCount * kChannelCount];
- SLANG_UNIT_TEST(drawIndexedIndirectD3D12)
- {
- runTestImpl(drawTestImpl<DrawIndexedIndirectTest>, unitTestContext, Slang::RenderApiFlag::D3D12);
+ checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
}
+};
- SLANG_UNIT_TEST(drawInstancedVulkan)
- {
- runTestImpl(drawTestImpl<DrawInstancedTest>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+template<typename T>
+void drawTestImpl(IDevice* device, UnitTestContext* context)
+{
+ T test;
+ test.init(device, context);
+ test.run();
+}
- SLANG_UNIT_TEST(drawIndexedInstancedVulkan)
- {
- runTestImpl(drawTestImpl<DrawIndexedInstancedTest>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(drawInstancedD3D11)
+{
+ runTestImpl(drawTestImpl<DrawInstancedTest>, unitTestContext, Slang::RenderApiFlag::D3D11);
+}
- SLANG_UNIT_TEST(drawIndirectVulkan)
- {
- runTestImpl(drawTestImpl<DrawIndirectTest>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(drawIndexedInstancedD3D11)
+{
+ runTestImpl(
+ drawTestImpl<DrawIndexedInstancedTest>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D11);
+}
- SLANG_UNIT_TEST(drawIndexedIndirectVulkan)
- {
- runTestImpl(drawTestImpl<DrawIndexedIndirectTest>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(drawInstancedD3D12)
+{
+ runTestImpl(drawTestImpl<DrawInstancedTest>, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(drawIndexedInstancedD3D12)
+{
+ runTestImpl(
+ drawTestImpl<DrawIndexedInstancedTest>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(drawIndirectD3D12)
+{
+ runTestImpl(drawTestImpl<DrawIndirectTest>, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(drawIndexedIndirectD3D12)
+{
+ runTestImpl(
+ drawTestImpl<DrawIndexedIndirectTest>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(drawInstancedVulkan)
+{
+ runTestImpl(drawTestImpl<DrawInstancedTest>, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(drawIndexedInstancedVulkan)
+{
+ runTestImpl(
+ drawTestImpl<DrawIndexedInstancedTest>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(drawIndirectVulkan)
+{
+ runTestImpl(drawTestImpl<DrawIndirectTest>, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(drawIndexedIndirectVulkan)
+{
+ runTestImpl(
+ drawTestImpl<DrawIndexedIndirectTest>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/link-time-constant.cpp b/tools/gfx-unit-test/link-time-constant.cpp
index a80a23c0c..047ecd3bc 100644
--- a/tools/gfx-unit-test/link-time-constant.cpp
+++ b/tools/gfx-unit-test/link-time-constant.cpp
@@ -1,162 +1,163 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
#include "source/core/slang-blob.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- static Slang::Result loadProgram(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- const char* shaderModuleName,
- const char* entryPointName,
- slang::ProgramLayout*& slangReflection,
- const char* additionalModuleSource)
- {
- Slang::ComPtr<slang::ISession> slangSession;
- SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- if (!module)
- return SLANG_FAIL;
-
- auto additionalModuleBlob = Slang::UnownedRawBlob::create(additionalModuleSource, strlen(additionalModuleSource));
- slang::IModule* additionalModule = slangSession->loadModuleFromSource("linkedConstants", "path",
- additionalModuleBlob);
-
- ComPtr<slang::IEntryPoint> computeEntryPoint;
- SLANG_RETURN_ON_FAIL(
- module->findEntryPointByName(entryPointName, computeEntryPoint.writeRef()));
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(module);
- componentTypes.add(computeEntryPoint);
- componentTypes.add(additionalModule);
-
- Slang::ComPtr<slang::IComponentType> composedProgram;
- SlangResult result = slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- composedProgram.writeRef(),
- diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- ComPtr<slang::IComponentType> linkedProgram;
- result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- composedProgram = linkedProgram;
- slangReflection = composedProgram->getLayout();
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = composedProgram.get();
-
- auto shaderProgram = device->createProgram(programDesc);
-
- outShaderProgram = shaderProgram;
- return SLANG_OK;
- }
+static Slang::Result loadProgram(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ const char* shaderModuleName,
+ const char* entryPointName,
+ slang::ProgramLayout*& slangReflection,
+ const char* additionalModuleSource)
+{
+ Slang::ComPtr<slang::ISession> slangSession;
+ SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ if (!module)
+ return SLANG_FAIL;
+
+ auto additionalModuleBlob =
+ Slang::UnownedRawBlob::create(additionalModuleSource, strlen(additionalModuleSource));
+ slang::IModule* additionalModule =
+ slangSession->loadModuleFromSource("linkedConstants", "path", additionalModuleBlob);
+
+ ComPtr<slang::IEntryPoint> computeEntryPoint;
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName(entryPointName, computeEntryPoint.writeRef()));
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(module);
+ componentTypes.add(computeEntryPoint);
+ componentTypes.add(additionalModule);
+
+ Slang::ComPtr<slang::IComponentType> composedProgram;
+ SlangResult result = slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ composedProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ ComPtr<slang::IComponentType> linkedProgram;
+ result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ composedProgram = linkedProgram;
+ slangReflection = composedProgram->getLayout();
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = composedProgram.get();
+
+ auto shaderProgram = device->createProgram(programDesc);
+
+ outShaderProgram = shaderProgram;
+ return SLANG_OK;
+}
- void linkTimeConstantTestImpl(IDevice* device, UnitTestContext* context)
- {
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadProgram(device, shaderProgram, "link-time-constant", "computeMain", slangReflection,
- R"(
+void linkTimeConstantTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadProgram(
+ device,
+ shaderProgram,
+ "link-time-constant",
+ "computeMain",
+ slangReflection,
+ R"(
export static const bool turnOnFeature = true;
export static const float constValue = 2.0;
export static const uint numthread = 2;
export static const int arraySize = 4;
)"));
-
- SlangUInt threadGroupSizes[3];
- slangReflection->findEntryPointByName("computeMain")->getComputeThreadGroupSize(3, threadGroupSizes);
- SLANG_CHECK(threadGroupSizes[0] == 2 && threadGroupSizes[1] == 1 && threadGroupSizes[2] == 1);
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 0.0f, 0.0f, 0.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(2.0));
- }
- SLANG_UNIT_TEST(linkTimeConstantD3D12)
+ SlangUInt threadGroupSizes[3];
+ slangReflection->findEntryPointByName("computeMain")
+ ->getComputeThreadGroupSize(3, threadGroupSizes);
+ SLANG_CHECK(threadGroupSizes[0] == 2 && threadGroupSizes[1] == 1 && threadGroupSizes[2] == 1);
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 0.0f, 0.0f, 0.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- runTestImpl(linkTimeConstantTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- SLANG_UNIT_TEST(linkTimeConstantVulkan)
- {
- runTestImpl(linkTimeConstantTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(2.0));
}
+
+SLANG_UNIT_TEST(linkTimeConstantD3D12)
+{
+ runTestImpl(linkTimeConstantTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(linkTimeConstantVulkan)
+{
+ runTestImpl(linkTimeConstantTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/link-time-default.cpp b/tools/gfx-unit-test/link-time-default.cpp
index be9198b82..d341e5dc0 100644
--- a/tools/gfx-unit-test/link-time-default.cpp
+++ b/tools/gfx-unit-test/link-time-default.cpp
@@ -1,22 +1,21 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
#include "source/core/slang-blob.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- static Slang::Result loadProgram(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- slang::ProgramLayout*& slangReflection,
- bool linkSpecialization = false)
- {
- const char* moduleInterfaceSrc = R"(
+static Slang::Result loadProgram(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ slang::ProgramLayout*& slangReflection,
+ bool linkSpecialization = false)
+{
+ const char* moduleInterfaceSrc = R"(
interface IFoo
{
static const int offset;
@@ -47,7 +46,7 @@ namespace gfx_test
}
};
)";
- const char* module0Src = R"(
+ const char* module0Src = R"(
import ifoo;
extern struct Foo : IFoo = FooImpl;
extern static const float c = 0.0;
@@ -59,179 +58,170 @@ namespace gfx_test
buffer[0] = foo.getValue() + foo.val2 + Foo.offset + c;
}
)";
- const char* module1Src = R"(
+ const char* module1Src = R"(
import ifoo;
export struct Foo : IFoo = BarImpl;
export static const float c = 1.0;
)";
- Slang::ComPtr<slang::ISession> slangSession;
- SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- auto moduleInterfaceBlob = Slang::UnownedRawBlob::create(moduleInterfaceSrc, strlen(moduleInterfaceSrc));
- auto module0Blob = Slang::UnownedRawBlob::create(module0Src, strlen(module0Src));
- auto module1Blob = Slang::UnownedRawBlob::create(module1Src, strlen(module1Src));
- slang::IModule* moduleInterface = slangSession->loadModuleFromSource("ifoo", "ifoo.slang",
- moduleInterfaceBlob);
- slang::IModule* module0 = slangSession->loadModuleFromSource("module0", "path0",
- module0Blob);
- slang::IModule* module1 = slangSession->loadModuleFromSource("module1", "path1",
- module1Blob);
- ComPtr<slang::IEntryPoint> computeEntryPoint;
- SLANG_RETURN_ON_FAIL(
- module0->findEntryPointByName("computeMain", computeEntryPoint.writeRef()));
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(moduleInterface);
- componentTypes.add(module0);
- if (linkSpecialization)
- componentTypes.add(module1);
- componentTypes.add(computeEntryPoint);
-
- Slang::ComPtr<slang::IComponentType> composedProgram;
- SlangResult result = slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- composedProgram.writeRef(),
- diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- ComPtr<slang::IComponentType> linkedProgram;
- result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- composedProgram = linkedProgram;
- slangReflection = composedProgram->getLayout();
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = composedProgram.get();
-
- auto shaderProgram = device->createProgram(programDesc);
-
- outShaderProgram = shaderProgram;
- return SLANG_OK;
- }
+ Slang::ComPtr<slang::ISession> slangSession;
+ SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ auto moduleInterfaceBlob =
+ Slang::UnownedRawBlob::create(moduleInterfaceSrc, strlen(moduleInterfaceSrc));
+ auto module0Blob = Slang::UnownedRawBlob::create(module0Src, strlen(module0Src));
+ auto module1Blob = Slang::UnownedRawBlob::create(module1Src, strlen(module1Src));
+ slang::IModule* moduleInterface =
+ slangSession->loadModuleFromSource("ifoo", "ifoo.slang", moduleInterfaceBlob);
+ slang::IModule* module0 = slangSession->loadModuleFromSource("module0", "path0", module0Blob);
+ slang::IModule* module1 = slangSession->loadModuleFromSource("module1", "path1", module1Blob);
+ ComPtr<slang::IEntryPoint> computeEntryPoint;
+ SLANG_RETURN_ON_FAIL(
+ module0->findEntryPointByName("computeMain", computeEntryPoint.writeRef()));
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(moduleInterface);
+ componentTypes.add(module0);
+ if (linkSpecialization)
+ componentTypes.add(module1);
+ componentTypes.add(computeEntryPoint);
+
+ Slang::ComPtr<slang::IComponentType> composedProgram;
+ SlangResult result = slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ composedProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ ComPtr<slang::IComponentType> linkedProgram;
+ result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ composedProgram = linkedProgram;
+ slangReflection = composedProgram->getLayout();
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = composedProgram.get();
+
+ auto shaderProgram = device->createProgram(programDesc);
+
+ outShaderProgram = shaderProgram;
+ return SLANG_OK;
+}
- void linkTimeDefaultTestImpl(IDevice* device, UnitTestContext* context)
+void linkTimeDefaultTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ // Create pipeline without linking a specialization override module, so we should
+ // see the default value of `extern Foo`.
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadProgram(device, shaderProgram, slangReflection, false));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ // Create pipeline with a specialization override module linked in, so we should
+ // see the result of using `Bar` for `extern Foo`.
+ ComPtr<IShaderProgram> shaderProgram1;
+ GFX_CHECK_CALL_ABORT(loadProgram(device, shaderProgram1, slangReflection, true));
+
+ ComputePipelineStateDesc pipelineDesc1 = {};
+ pipelineDesc1.program = shaderProgram1.get();
+ ComPtr<gfx::IPipelineState> pipelineState1;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc1, pipelineState1.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 0.0f, 0.0f, 0.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- // Create pipeline without linking a specialization override module, so we should
- // see the default value of `extern Foo`.
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadProgram(device, shaderProgram, slangReflection, false));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- // Create pipeline with a specialization override module linked in, so we should
- // see the result of using `Bar` for `extern Foo`.
- ComPtr<IShaderProgram> shaderProgram1;
- GFX_CHECK_CALL_ABORT(loadProgram(device, shaderProgram1, slangReflection, true));
-
- ComputePipelineStateDesc pipelineDesc1 = {};
- pipelineDesc1.program = shaderProgram1.get();
- ComPtr<gfx::IPipelineState> pipelineState1;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc1, pipelineState1.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 0.0f, 0.0f, 0.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(8.0));
-
- // Now run again with the overrided program.
- {
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState1);
-
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(10.0));
- }
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- SLANG_UNIT_TEST(linkTimeDefaultD3D12)
- {
- runTestImpl(linkTimeDefaultTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(linkTimeDefaultVulkan)
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(8.0));
+
+ // Now run again with the overrided program.
{
- runTestImpl(linkTimeDefaultTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState1);
+
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(10.0));
}
+
+SLANG_UNIT_TEST(linkTimeDefaultD3D12)
+{
+ runTestImpl(linkTimeDefaultTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(linkTimeDefaultVulkan)
+{
+ runTestImpl(linkTimeDefaultTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/link-time-options.cpp b/tools/gfx-unit-test/link-time-options.cpp
index f14a918e8..590db576e 100644
--- a/tools/gfx-unit-test/link-time-options.cpp
+++ b/tools/gfx-unit-test/link-time-options.cpp
@@ -1,152 +1,148 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
#include "source/core/slang-blob.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- // In this test,
- // we will run a compute shader that compiles to HLSL with a reference to the macro "DOWNSTREAM_VALUE"
- // that will be provided to dxc through slang's link-time compiler options.
- // The test verifies that `IComponentType2::linkWithOptions()` is able to produce a linked IComponentType
- // with additional compiler options. Here we will specify a DownstreamArg compiler option to define
- // the value of DOWNSTREAM_VALUE when running dxc.
- //
- static Slang::Result loadProgram(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- const char* shaderModuleName,
- const char* entryPointName,
- slang::ProgramLayout*& slangReflection)
- {
- Slang::ComPtr<slang::ISession> slangSession;
- SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- if (!module)
- return SLANG_FAIL;
-
- ComPtr<slang::IEntryPoint> computeEntryPoint;
- SLANG_RETURN_ON_FAIL(
- module->findEntryPointByName(entryPointName, computeEntryPoint.writeRef()));
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(module);
- componentTypes.add(computeEntryPoint);
-
- Slang::ComPtr<slang::IComponentType> composedProgram;
- SlangResult result = slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- composedProgram.writeRef(),
- diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- ComPtr<slang::IComponentType> linkedProgram;
- slang::CompilerOptionEntry entry;
- entry.name = slang::CompilerOptionName::DownstreamArgs;
- entry.value.kind = slang::CompilerOptionValueKind::String;
- entry.value.stringValue0 = "dxc";
- entry.value.stringValue1 = "-DDOWNSTREAM_VALUE=4.0";
- result = composedProgram->linkWithOptions(linkedProgram.writeRef(), 1, &entry, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- composedProgram = linkedProgram;
- slangReflection = composedProgram->getLayout();
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = composedProgram.get();
-
- auto shaderProgram = device->createProgram(programDesc);
-
- outShaderProgram = shaderProgram;
- return SLANG_OK;
- }
+// In this test,
+// we will run a compute shader that compiles to HLSL with a reference to the macro
+// "DOWNSTREAM_VALUE" that will be provided to dxc through slang's link-time compiler options. The
+// test verifies that `IComponentType2::linkWithOptions()` is able to produce a linked
+// IComponentType with additional compiler options. Here we will specify a DownstreamArg compiler
+// option to define the value of DOWNSTREAM_VALUE when running dxc.
+//
+static Slang::Result loadProgram(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ const char* shaderModuleName,
+ const char* entryPointName,
+ slang::ProgramLayout*& slangReflection)
+{
+ Slang::ComPtr<slang::ISession> slangSession;
+ SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ if (!module)
+ return SLANG_FAIL;
+
+ ComPtr<slang::IEntryPoint> computeEntryPoint;
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName(entryPointName, computeEntryPoint.writeRef()));
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(module);
+ componentTypes.add(computeEntryPoint);
+
+ Slang::ComPtr<slang::IComponentType> composedProgram;
+ SlangResult result = slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ composedProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ ComPtr<slang::IComponentType> linkedProgram;
+ slang::CompilerOptionEntry entry;
+ entry.name = slang::CompilerOptionName::DownstreamArgs;
+ entry.value.kind = slang::CompilerOptionValueKind::String;
+ entry.value.stringValue0 = "dxc";
+ entry.value.stringValue1 = "-DDOWNSTREAM_VALUE=4.0";
+ result = composedProgram
+ ->linkWithOptions(linkedProgram.writeRef(), 1, &entry, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ composedProgram = linkedProgram;
+ slangReflection = composedProgram->getLayout();
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = composedProgram.get();
+
+ auto shaderProgram = device->createProgram(programDesc);
+
+ outShaderProgram = shaderProgram;
+ return SLANG_OK;
+}
- void linkTimeOptionTestImpl(IDevice* device, UnitTestContext* context)
+void linkTimeOptionTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(
+ loadProgram(device, shaderProgram, "link-time-options", "computeMain", slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 0.0f, 0.0f, 0.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadProgram(device, shaderProgram, "link-time-options", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 0.0f, 0.0f, 0.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(4.0));
- }
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- SLANG_UNIT_TEST(linkTimeOptionD3D12)
- {
- runTestImpl(linkTimeOptionTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(4.0));
+}
+
+SLANG_UNIT_TEST(linkTimeOptionD3D12)
+{
+ runTestImpl(linkTimeOptionTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/link-time-type.cpp b/tools/gfx-unit-test/link-time-type.cpp
index 39496b3fe..81c738126 100644
--- a/tools/gfx-unit-test/link-time-type.cpp
+++ b/tools/gfx-unit-test/link-time-type.cpp
@@ -1,21 +1,20 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
#include "source/core/slang-blob.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- static Slang::Result loadProgram(
- gfx::IDevice* device,
- Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
- slang::ProgramLayout*& slangReflection)
- {
- const char* moduleInterfaceSrc = R"(
+static Slang::Result loadProgram(
+ gfx::IDevice* device,
+ Slang::ComPtr<gfx::IShaderProgram>& outShaderProgram,
+ slang::ProgramLayout*& slangReflection)
+{
+ const char* moduleInterfaceSrc = R"(
interface IBase : IDifferentiable
{
[Differentiable]
@@ -50,7 +49,7 @@ namespace gfx_test
__init(int x) { val = x; }
};
)";
- const char* module0Src = R"(
+ const char* module0Src = R"(
import ifoo;
extern struct Foo : IFoo;
@@ -62,139 +61,133 @@ namespace gfx_test
buffer[0] = foo.getValue() + foo.val2 + Foo.offset + foo.getBaseValue();
}
)";
- const char* module1Src = R"(
+ const char* module1Src = R"(
import ifoo;
export struct Foo : IFoo = FooImpl;)";
- Slang::ComPtr<slang::ISession> slangSession;
- SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- auto moduleInterfaceBlob = Slang::UnownedRawBlob::create(moduleInterfaceSrc, strlen(moduleInterfaceSrc));
- auto module0Blob = Slang::UnownedRawBlob::create(module0Src, strlen(module0Src));
- auto module1Blob = Slang::UnownedRawBlob::create(module1Src, strlen(module1Src));
- slang::IModule* moduleInterface = slangSession->loadModuleFromSource("ifoo", "ifoo.slang",
- moduleInterfaceBlob);
- slang::IModule* module0 = slangSession->loadModuleFromSource("module0", "path0",
- module0Blob);
- slang::IModule* module1 = slangSession->loadModuleFromSource("module1", "path1",
- module1Blob);
- ComPtr<slang::IEntryPoint> computeEntryPoint;
- SLANG_RETURN_ON_FAIL(
- module0->findEntryPointByName("computeMain", computeEntryPoint.writeRef()));
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(moduleInterface);
- componentTypes.add(module0);
- componentTypes.add(module1);
- componentTypes.add(computeEntryPoint);
-
- Slang::ComPtr<slang::IComponentType> composedProgram;
- SlangResult result = slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- composedProgram.writeRef(),
- diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- ComPtr<slang::IComponentType> linkedProgram;
- result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- SLANG_RETURN_ON_FAIL(result);
-
- composedProgram = linkedProgram;
- slangReflection = composedProgram->getLayout();
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = composedProgram.get();
-
- auto shaderProgram = device->createProgram(programDesc);
-
- outShaderProgram = shaderProgram;
- return SLANG_OK;
- }
+ Slang::ComPtr<slang::ISession> slangSession;
+ SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ auto moduleInterfaceBlob =
+ Slang::UnownedRawBlob::create(moduleInterfaceSrc, strlen(moduleInterfaceSrc));
+ auto module0Blob = Slang::UnownedRawBlob::create(module0Src, strlen(module0Src));
+ auto module1Blob = Slang::UnownedRawBlob::create(module1Src, strlen(module1Src));
+ slang::IModule* moduleInterface =
+ slangSession->loadModuleFromSource("ifoo", "ifoo.slang", moduleInterfaceBlob);
+ slang::IModule* module0 = slangSession->loadModuleFromSource("module0", "path0", module0Blob);
+ slang::IModule* module1 = slangSession->loadModuleFromSource("module1", "path1", module1Blob);
+ ComPtr<slang::IEntryPoint> computeEntryPoint;
+ SLANG_RETURN_ON_FAIL(
+ module0->findEntryPointByName("computeMain", computeEntryPoint.writeRef()));
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(moduleInterface);
+ componentTypes.add(module0);
+ componentTypes.add(module1);
+ componentTypes.add(computeEntryPoint);
+
+ Slang::ComPtr<slang::IComponentType> composedProgram;
+ SlangResult result = slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ composedProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ ComPtr<slang::IComponentType> linkedProgram;
+ result = composedProgram->link(linkedProgram.writeRef(), diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ SLANG_RETURN_ON_FAIL(result);
+
+ composedProgram = linkedProgram;
+ slangReflection = composedProgram->getLayout();
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = composedProgram.get();
+
+ auto shaderProgram = device->createProgram(programDesc);
+
+ outShaderProgram = shaderProgram;
+ return SLANG_OK;
+}
- void linkTimeTypeTestImpl(IDevice* device, UnitTestContext* context)
+void linkTimeTypeTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadProgram(device, shaderProgram, slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 0.0f, 0.0f, 0.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadProgram(device, shaderProgram, slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 0.0f, 0.0f, 0.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(11.0));
- }
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- SLANG_UNIT_TEST(linkTimeTypeD3D12)
- {
- runTestImpl(linkTimeTypeTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- SLANG_UNIT_TEST(linkTimeTypeVulkan)
- {
- runTestImpl(linkTimeTypeTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(11.0));
+}
+
+SLANG_UNIT_TEST(linkTimeTypeD3D12)
+{
+ runTestImpl(linkTimeTypeTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(linkTimeTypeVulkan)
+{
+ runTestImpl(linkTimeTypeTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/mutable-shader-object.cpp b/tools/gfx-unit-test/mutable-shader-object.cpp
index cc9707643..9c91a7ca3 100644
--- a/tools/gfx-unit-test/mutable-shader-object.cpp
+++ b/tools/gfx-unit-test/mutable-shader-object.cpp
@@ -1,136 +1,141 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void mutableShaderObjectTestImpl(IDevice* device, UnitTestContext* context)
+void mutableShaderObjectTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "mutable-shader-object",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ float initialData[] = {0.0f, 1.0f, 2.0f, 3.0f};
+ const int numberCount = SLANG_COUNT_OF(initialData);
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = sizeof(initialData);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "mutable-shader-object", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- float initialData[] = { 0.0f, 1.0f, 2.0f, 3.0f };
- const int numberCount = SLANG_COUNT_OF(initialData);
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = sizeof(initialData);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
+ slang::TypeReflection* addTransformerType =
+ slangReflection->findTypeByName("AddTransformer");
+
+ ComPtr<IShaderObject> transformer;
+ GFX_CHECK_CALL_ABORT(device->createMutableShaderObject(
+ addTransformerType,
+ ShaderObjectContainerType::None,
+ transformer.writeRef()));
+ // Set the `c` field of the `AddTransformer`.
+ float c = 1.0f;
+ ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
+
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ auto entryPointCursor = ShaderCursor(rootObject->getEntryPoint(0));
+
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ // Bind the previously created transformer object to root object.
+ ComPtr<IShaderObject> transformerVersion;
+ transformer->getCurrentVersion(transientHeap, transformerVersion.writeRef());
+ entryPointCursor.getPath("transformer").setObject(transformerVersion);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+
+ auto barrierEncoder = commandBuffer->encodeResourceCommands();
+ barrierEncoder->bufferBarrier(
+ 1,
+ numbersBuffer.readRef(),
ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- {
- slang::TypeReflection* addTransformerType =
- slangReflection->findTypeByName("AddTransformer");
-
- ComPtr<IShaderObject> transformer;
- GFX_CHECK_CALL_ABORT(device->createMutableShaderObject(
- addTransformerType, ShaderObjectContainerType::None, transformer.writeRef()));
- // Set the `c` field of the `AddTransformer`.
- float c = 1.0f;
- ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- auto entryPointCursor = ShaderCursor(rootObject->getEntryPoint(0));
-
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- // Bind the previously created transformer object to root object.
- ComPtr<IShaderObject> transformerVersion;
- transformer->getCurrentVersion(transientHeap, transformerVersion.writeRef());
- entryPointCursor.getPath("transformer").setObject(transformerVersion);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
-
- auto barrierEncoder = commandBuffer->encodeResourceCommands();
- barrierEncoder->bufferBarrier(1, numbersBuffer.readRef(), ResourceState::UnorderedAccess, ResourceState::UnorderedAccess);
- barrierEncoder->endEncoding();
-
- encoder = commandBuffer->encodeComputeCommands();
-
- rootObject = encoder->bindPipeline(pipelineState);
- entryPointCursor = ShaderCursor(rootObject->getEntryPoint(0));
-
- // Mutate `transformer` object and run again.
- c = 2.0f;
- ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
- transformer->getCurrentVersion(transientHeap, transformerVersion.writeRef());
- entryPointCursor.getPath("buffer").setResource(bufferView);
- entryPointCursor.getPath("transformer").setObject(transformerVersion);
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
-
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(3.0f, 4.0f, 5.0f, 6.0f));
+ ResourceState::UnorderedAccess);
+ barrierEncoder->endEncoding();
+
+ encoder = commandBuffer->encodeComputeCommands();
+
+ rootObject = encoder->bindPipeline(pipelineState);
+ entryPointCursor = ShaderCursor(rootObject->getEntryPoint(0));
+
+ // Mutate `transformer` object and run again.
+ c = 2.0f;
+ ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
+ transformer->getCurrentVersion(transientHeap, transformerVersion.writeRef());
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+ entryPointCursor.getPath("transformer").setObject(transformerVersion);
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- //SLANG_UNIT_TEST(mutableShaderObjectCPU)
- //{
- // runTestImpl(mutableShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::CPU);
- //}
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(3.0f, 4.0f, 5.0f, 6.0f));
+}
- SLANG_UNIT_TEST(mutableShaderObjectD3D11)
- {
- runTestImpl(mutableShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::D3D11);
- }
+// SLANG_UNIT_TEST(mutableShaderObjectCPU)
+//{
+// runTestImpl(mutableShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::CPU);
+// }
- SLANG_UNIT_TEST(mutableShaderObjectD3D12)
- {
- runTestImpl(mutableShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+SLANG_UNIT_TEST(mutableShaderObjectD3D11)
+{
+ runTestImpl(mutableShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::D3D11);
+}
- SLANG_UNIT_TEST(mutableShaderObjectVulkan)
- {
- runTestImpl(mutableShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(mutableShaderObjectD3D12)
+{
+ runTestImpl(mutableShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(mutableShaderObjectVulkan)
+{
+ runTestImpl(mutableShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/nested-parameter-block.cpp b/tools/gfx-unit-test/nested-parameter-block.cpp
index 98df615af..e904226ae 100644
--- a/tools/gfx-unit-test/nested-parameter-block.cpp
+++ b/tools/gfx-unit-test/nested-parameter-block.cpp
@@ -1,150 +1,162 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- Slang::ComPtr<IBufferResource> createBuffer(
- IDevice* device, uint32_t data, ResourceState defaultState)
- {
- uint32_t initialData[] = {data, data, data, data};
- const int numberCount = SLANG_COUNT_OF(initialData);
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = sizeof(initialData);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(uint32_t) * 4;
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = defaultState;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(
- device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
- return numbersBuffer;
- }
+Slang::ComPtr<IBufferResource> createBuffer(
+ IDevice* device,
+ uint32_t data,
+ ResourceState defaultState)
+{
+ uint32_t initialData[] = {data, data, data, data};
+ const int numberCount = SLANG_COUNT_OF(initialData);
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = sizeof(initialData);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(uint32_t) * 4;
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = defaultState;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+ return numbersBuffer;
+}
- struct uint4
- {
- uint32_t x, y, z, w;
- };
+struct uint4
+{
+ uint32_t x, y, z, w;
+};
- void nestedParameterBlockTestImpl(IDevice* device, UnitTestContext* context)
+void nestedParameterBlockTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "nested-parameter-block",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ ComPtr<IShaderObject> shaderObject;
+ SLANG_CHECK(SLANG_SUCCEEDED(
+ device->createMutableRootShaderObject(shaderProgram, shaderObject.writeRef())));
+
+ Slang::List<Slang::ComPtr<IBufferResource>> srvBuffers;
+ Slang::List<Slang::ComPtr<IResourceView>> srvs;
+
+ for (uint32_t i = 0; i < 6; i++)
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "nested-parameter-block", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- ComPtr<IShaderObject> shaderObject;
- SLANG_CHECK(SLANG_SUCCEEDED(
- device->createMutableRootShaderObject(shaderProgram, shaderObject.writeRef())));
-
- Slang::List<Slang::ComPtr<IBufferResource>> srvBuffers;
- Slang::List<Slang::ComPtr<IResourceView>> srvs;
-
- for (uint32_t i = 0; i < 6; i++)
- {
- srvBuffers.add(createBuffer(device, i, gfx::ResourceState::ShaderResource));
- IResourceView::Desc srvDesc = {};
- srvDesc.type = IResourceView::Type::ShaderResource;
- srvDesc.format = Format::Unknown;
- srvDesc.bufferRange.offset = 0;
- srvDesc.bufferRange.size = sizeof(uint32_t) * 4;
- srvs.add(device->createBufferView(srvBuffers[i], nullptr, srvDesc));
- }
- Slang::ComPtr<IBufferResource> resultBuffer =
- createBuffer(device, 0, gfx::ResourceState::UnorderedAccess);
- IResourceView::Desc resultBufferViewDesc = {};
- resultBufferViewDesc.type = IResourceView::Type::UnorderedAccess;
- resultBufferViewDesc.format = Format::Unknown;
- resultBufferViewDesc.bufferRange.offset = 0;
- resultBufferViewDesc.bufferRange.size = sizeof(uint32_t) * 4;
- Slang::ComPtr<IResourceView> resultBufferView;
- SLANG_CHECK(SLANG_SUCCEEDED(device->createBufferView(
- resultBuffer, nullptr, resultBufferViewDesc, resultBufferView.writeRef())));
-
- Slang::ComPtr<IShaderObject> materialObject;
- SLANG_CHECK(SLANG_SUCCEEDED(device->createMutableShaderObject(
- slangReflection->findTypeByName("MaterialSystem"),
- ShaderObjectContainerType::None,
- materialObject.writeRef())));
-
- Slang::ComPtr<IShaderObject> sceneObject;
- SLANG_CHECK(SLANG_SUCCEEDED(device->createMutableShaderObject(
- slangReflection->findTypeByName("Scene"),
- ShaderObjectContainerType::None,
- sceneObject.writeRef())));
-
- ShaderCursor cursor(shaderObject);
- cursor["resultBuffer"].setResource(resultBufferView);
- cursor["scene"].setObject(sceneObject);
-
- Slang::ComPtr<IShaderObject> globalCB;
- SLANG_CHECK(SLANG_SUCCEEDED(device->createShaderObject(
- cursor[0].getTypeLayout()->getType(),
- ShaderObjectContainerType::None,
- globalCB.writeRef())));
-
- cursor[0].setObject(globalCB);
- auto initialData = uint4{20, 20, 20, 20};
- globalCB->setData(ShaderOffset(), &initialData, sizeof(initialData));
-
- ShaderCursor sceneCursor(sceneObject);
- sceneCursor["sceneCb"].setData(uint4{100, 100, 100, 100});
- sceneCursor["data"].setResource(srvs[1]);
- sceneCursor["material"].setObject(materialObject);
-
- ShaderCursor materialCursor(materialObject);
- materialCursor["cb"].setData(uint4{1000, 1000, 1000, 1000});
- materialCursor["data"].setResource(srvs[2]);
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- encoder->bindPipelineWithRootObject(pipelineState, shaderObject);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(device, resultBuffer, Slang::makeArray<uint32_t>(1123u, 1123u, 1123u, 1123u));
+ srvBuffers.add(createBuffer(device, i, gfx::ResourceState::ShaderResource));
+ IResourceView::Desc srvDesc = {};
+ srvDesc.type = IResourceView::Type::ShaderResource;
+ srvDesc.format = Format::Unknown;
+ srvDesc.bufferRange.offset = 0;
+ srvDesc.bufferRange.size = sizeof(uint32_t) * 4;
+ srvs.add(device->createBufferView(srvBuffers[i], nullptr, srvDesc));
}
-
- SLANG_UNIT_TEST(nestedParameterBlockTestD3D12)
+ Slang::ComPtr<IBufferResource> resultBuffer =
+ createBuffer(device, 0, gfx::ResourceState::UnorderedAccess);
+ IResourceView::Desc resultBufferViewDesc = {};
+ resultBufferViewDesc.type = IResourceView::Type::UnorderedAccess;
+ resultBufferViewDesc.format = Format::Unknown;
+ resultBufferViewDesc.bufferRange.offset = 0;
+ resultBufferViewDesc.bufferRange.size = sizeof(uint32_t) * 4;
+ Slang::ComPtr<IResourceView> resultBufferView;
+ SLANG_CHECK(SLANG_SUCCEEDED(device->createBufferView(
+ resultBuffer,
+ nullptr,
+ resultBufferViewDesc,
+ resultBufferView.writeRef())));
+
+ Slang::ComPtr<IShaderObject> materialObject;
+ SLANG_CHECK(SLANG_SUCCEEDED(device->createMutableShaderObject(
+ slangReflection->findTypeByName("MaterialSystem"),
+ ShaderObjectContainerType::None,
+ materialObject.writeRef())));
+
+ Slang::ComPtr<IShaderObject> sceneObject;
+ SLANG_CHECK(SLANG_SUCCEEDED(device->createMutableShaderObject(
+ slangReflection->findTypeByName("Scene"),
+ ShaderObjectContainerType::None,
+ sceneObject.writeRef())));
+
+ ShaderCursor cursor(shaderObject);
+ cursor["resultBuffer"].setResource(resultBufferView);
+ cursor["scene"].setObject(sceneObject);
+
+ Slang::ComPtr<IShaderObject> globalCB;
+ SLANG_CHECK(SLANG_SUCCEEDED(device->createShaderObject(
+ cursor[0].getTypeLayout()->getType(),
+ ShaderObjectContainerType::None,
+ globalCB.writeRef())));
+
+ cursor[0].setObject(globalCB);
+ auto initialData = uint4{20, 20, 20, 20};
+ globalCB->setData(ShaderOffset(), &initialData, sizeof(initialData));
+
+ ShaderCursor sceneCursor(sceneObject);
+ sceneCursor["sceneCb"].setData(uint4{100, 100, 100, 100});
+ sceneCursor["data"].setResource(srvs[1]);
+ sceneCursor["material"].setObject(materialObject);
+
+ ShaderCursor materialCursor(materialObject);
+ materialCursor["cb"].setData(uint4{1000, 1000, 1000, 1000});
+ materialCursor["data"].setResource(srvs[2]);
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- runTestImpl(nestedParameterBlockTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- SLANG_UNIT_TEST(nestedParameterBlockTestVulkan)
- {
- runTestImpl(nestedParameterBlockTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ encoder->bindPipelineWithRootObject(pipelineState, shaderObject);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+
+ compareComputeResult(
+ device,
+ resultBuffer,
+ Slang::makeArray<uint32_t>(1123u, 1123u, 1123u, 1123u));
+}
+
+SLANG_UNIT_TEST(nestedParameterBlockTestD3D12)
+{
+ runTestImpl(nestedParameterBlockTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(nestedParameterBlockTestVulkan)
+{
+ runTestImpl(nestedParameterBlockTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/precompiled-module-2.cpp b/tools/gfx-unit-test/precompiled-module-2.cpp
index f997b2a7b..0a5ea3ac0 100644
--- a/tools/gfx-unit-test/precompiled-module-2.cpp
+++ b/tools/gfx-unit-test/precompiled-module-2.cpp
@@ -1,121 +1,125 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
#include "source/core/slang-blob.h"
-#include "source/core/slang-memory-file-system.h"
#include "source/core/slang-io.h"
+#include "source/core/slang-memory-file-system.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- // Test that mixing precompiled and non-precompiled modules is working.
+// Test that mixing precompiled and non-precompiled modules is working.
- static Slang::Result precompileProgram(
- gfx::IDevice* device,
- ISlangMutableFileSystem* fileSys,
- const char* shaderModuleName,
- bool precompileToTarget)
+static Slang::Result precompileProgram(
+ gfx::IDevice* device,
+ ISlangMutableFileSystem* fileSys,
+ const char* shaderModuleName,
+ bool precompileToTarget)
+{
+ Slang::ComPtr<slang::ISession> slangSession;
+ SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
+ slang::SessionDesc sessionDesc = {};
+ auto searchPaths = getSlangSearchPaths();
+ sessionDesc.searchPathCount = searchPaths.getCount();
+ sessionDesc.searchPaths = searchPaths.getBuffer();
+ auto globalSession = slangSession->getGlobalSession();
+ globalSession->createSession(sessionDesc, slangSession.writeRef());
+
+ slang::IModule* module;
{
- Slang::ComPtr<slang::ISession> slangSession;
- SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
- slang::SessionDesc sessionDesc = {};
- auto searchPaths = getSlangSearchPaths();
- sessionDesc.searchPathCount = searchPaths.getCount();
- sessionDesc.searchPaths = searchPaths.getBuffer();
- auto globalSession = slangSession->getGlobalSession();
- globalSession->createSession(sessionDesc, slangSession.writeRef());
-
- slang::IModule* module;
- {
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- }
- if (!module)
- return SLANG_FAIL;
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ }
+ if (!module)
+ return SLANG_FAIL;
- if (precompileToTarget)
+ if (precompileToTarget)
+ {
+ SlangCompileTarget target;
+ switch (device->getDeviceInfo().deviceType)
{
- SlangCompileTarget target;
- switch (device->getDeviceInfo().deviceType)
- {
- case gfx::DeviceType::DirectX12:
- target = SLANG_DXIL;
- break;
- case gfx::DeviceType::Vulkan:
- target = SLANG_SPIRV;
- break;
- default:
- return SLANG_FAIL;
- }
-
- ComPtr<slang::IModulePrecompileService_Experimental> precompileService;
- if (module->queryInterface(slang::SLANG_UUID_IModulePrecompileService_Experimental, (void**)precompileService.writeRef()) == SLANG_OK)
- {
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- precompileService->precompileForTarget(target, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- }
+ case gfx::DeviceType::DirectX12: target = SLANG_DXIL; break;
+ case gfx::DeviceType::Vulkan: target = SLANG_SPIRV; break;
+ default: return SLANG_FAIL;
}
- // Write loaded modules to memory file system.
- for (SlangInt i = 0; i < slangSession->getLoadedModuleCount(); i++)
+ ComPtr<slang::IModulePrecompileService_Experimental> precompileService;
+ if (module->queryInterface(
+ slang::SLANG_UUID_IModulePrecompileService_Experimental,
+ (void**)precompileService.writeRef()) == SLANG_OK)
{
- auto module = slangSession->getLoadedModule(i);
- auto path = module->getFilePath();
- if (path)
- {
- auto name = module->getName();
- ComPtr<ISlangBlob> outBlob;
- module->serialize(outBlob.writeRef());
- fileSys->saveFileBlob((Slang::String(name) + ".slang-module").getBuffer(), outBlob);
- }
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ precompileService->precompileForTarget(target, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
}
- return SLANG_OK;
}
- void precompiledModule2TestImplCommon(IDevice* device, UnitTestContext* context, bool precompileToTarget)
+ // Write loaded modules to memory file system.
+ for (SlangInt i = 0; i < slangSession->getLoadedModuleCount(); i++)
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- // First, load and compile the slang source.
- ComPtr<ISlangMutableFileSystem> memoryFileSystem = ComPtr<ISlangMutableFileSystem>(new Slang::MemoryFileSystem());
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(precompileProgram(device, memoryFileSystem.get(), "precompiled-module-imported", precompileToTarget));
-
- // Next, load the precompiled slang program.
- Slang::ComPtr<slang::ISession> slangSession;
- device->getSlangSession(slangSession.writeRef());
- slang::SessionDesc sessionDesc = {};
- sessionDesc.targetCount = 1;
- slang::TargetDesc targetDesc = {};
- switch (device->getDeviceInfo().deviceType)
+ auto module = slangSession->getLoadedModule(i);
+ auto path = module->getFilePath();
+ if (path)
{
- case gfx::DeviceType::DirectX12:
- targetDesc.format = SLANG_DXIL;
- targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("sm_6_1");
- break;
- case gfx::DeviceType::Vulkan:
- targetDesc.format = SLANG_SPIRV;
- targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("GLSL_460");
- break;
+ auto name = module->getName();
+ ComPtr<ISlangBlob> outBlob;
+ module->serialize(outBlob.writeRef());
+ fileSys->saveFileBlob((Slang::String(name) + ".slang-module").getBuffer(), outBlob);
}
- sessionDesc.targets = &targetDesc;
- sessionDesc.fileSystem = memoryFileSystem.get();
- auto globalSession = slangSession->getGlobalSession();
- globalSession->createSession(sessionDesc, slangSession.writeRef());
+ }
+ return SLANG_OK;
+}
+
+void precompiledModule2TestImplCommon(
+ IDevice* device,
+ UnitTestContext* context,
+ bool precompileToTarget)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ // First, load and compile the slang source.
+ ComPtr<ISlangMutableFileSystem> memoryFileSystem =
+ ComPtr<ISlangMutableFileSystem>(new Slang::MemoryFileSystem());
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(precompileProgram(
+ device,
+ memoryFileSystem.get(),
+ "precompiled-module-imported",
+ precompileToTarget));
+
+ // Next, load the precompiled slang program.
+ Slang::ComPtr<slang::ISession> slangSession;
+ device->getSlangSession(slangSession.writeRef());
+ slang::SessionDesc sessionDesc = {};
+ sessionDesc.targetCount = 1;
+ slang::TargetDesc targetDesc = {};
+ switch (device->getDeviceInfo().deviceType)
+ {
+ case gfx::DeviceType::DirectX12:
+ targetDesc.format = SLANG_DXIL;
+ targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("sm_6_1");
+ break;
+ case gfx::DeviceType::Vulkan:
+ targetDesc.format = SLANG_SPIRV;
+ targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("GLSL_460");
+ break;
+ }
+ sessionDesc.targets = &targetDesc;
+ sessionDesc.fileSystem = memoryFileSystem.get();
+ auto globalSession = slangSession->getGlobalSession();
+ globalSession->createSession(sessionDesc, slangSession.writeRef());
- const char* moduleSrc = R"(
+ const char* moduleSrc = R"(
import "precompiled-module-imported";
// Main entry-point.
@@ -131,99 +135,100 @@ namespace gfx_test
buffer[sv_dispatchThreadID.x] = helperFunc() + helperFunc1();
}
)";
- memoryFileSystem->saveFile("precompiled-module.slang", moduleSrc, strlen(moduleSrc));
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, slangSession, shaderProgram, "precompiled-module", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 0.0f, 0.0f, 0.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
+ memoryFileSystem->saveFile("precompiled-module.slang", moduleSrc, strlen(moduleSrc));
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ slangSession,
+ shaderProgram,
+ "precompiled-module",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 0.0f, 0.0f, 0.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
+ {
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- auto rootObject = encoder->bindPipeline(pipelineState);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
+ auto rootObject = encoder->bindPipeline(pipelineState);
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(3.0f, 3.0f, 3.0f, 3.0f));
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- void precompiledModule2TestImpl(IDevice* device, UnitTestContext* context)
- {
- precompiledModule2TestImplCommon(device, context, false);
- }
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(3.0f, 3.0f, 3.0f, 3.0f));
+}
- void precompiledTargetModule2TestImpl(IDevice* device, UnitTestContext* context)
- {
- precompiledModule2TestImplCommon(device, context, true);
- }
+void precompiledModule2TestImpl(IDevice* device, UnitTestContext* context)
+{
+ precompiledModule2TestImplCommon(device, context, false);
+}
- SLANG_UNIT_TEST(precompiledModule2D3D12)
- {
- runTestImpl(precompiledModule2TestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+void precompiledTargetModule2TestImpl(IDevice* device, UnitTestContext* context)
+{
+ precompiledModule2TestImplCommon(device, context, true);
+}
- SLANG_UNIT_TEST(precompiledTargetModule2D3D12)
- {
- runTestImpl(precompiledTargetModule2TestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+SLANG_UNIT_TEST(precompiledModule2D3D12)
+{
+ runTestImpl(precompiledModule2TestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
- SLANG_UNIT_TEST(precompiledModule2Vulkan)
- {
- runTestImpl(precompiledModule2TestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(precompiledTargetModule2D3D12)
+{
+ runTestImpl(precompiledTargetModule2TestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
- SLANG_UNIT_TEST(precompiledTargetModule2Vulkan)
- {
- runTestImpl(precompiledTargetModule2TestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(precompiledModule2Vulkan)
+{
+ runTestImpl(precompiledModule2TestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+SLANG_UNIT_TEST(precompiledTargetModule2Vulkan)
+{
+ runTestImpl(precompiledTargetModule2TestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/precompiled-module-cache.cpp b/tools/gfx-unit-test/precompiled-module-cache.cpp
index 97d6e1c34..1c10f759b 100644
--- a/tools/gfx-unit-test/precompiled-module-cache.cpp
+++ b/tools/gfx-unit-test/precompiled-module-cache.cpp
@@ -1,95 +1,97 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
#include "source/core/slang-blob.h"
-#include "source/core/slang-memory-file-system.h"
#include "source/core/slang-io.h"
+#include "source/core/slang-memory-file-system.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- // Test that precompiled module cache is working.
+// Test that precompiled module cache is working.
- Slang::ComPtr<slang::ISession> createSession(gfx::IDevice* device, ISlangFileSystemExt* fileSys)
+Slang::ComPtr<slang::ISession> createSession(gfx::IDevice* device, ISlangFileSystemExt* fileSys)
+{
+ Slang::ComPtr<slang::ISession> slangSession;
+ device->getSlangSession(slangSession.writeRef());
+ slang::SessionDesc sessionDesc = {};
+ sessionDesc.searchPathCount = 1;
+ const char* searchPath = "cache/";
+ sessionDesc.searchPaths = &searchPath;
+ sessionDesc.targetCount = 1;
+ sessionDesc.compilerOptionEntryCount = 1;
+ slang::CompilerOptionEntry entry;
+ entry.name = slang::CompilerOptionName::UseUpToDateBinaryModule;
+ entry.value.kind = slang::CompilerOptionValueKind::Int;
+ entry.value.intValue0 = 1;
+ sessionDesc.compilerOptionEntries = &entry;
+ slang::TargetDesc targetDesc = {};
+ switch (device->getDeviceInfo().deviceType)
{
- Slang::ComPtr<slang::ISession> slangSession;
- device->getSlangSession(slangSession.writeRef());
- slang::SessionDesc sessionDesc = {};
- sessionDesc.searchPathCount = 1;
- const char* searchPath = "cache/";
- sessionDesc.searchPaths = &searchPath;
- sessionDesc.targetCount = 1;
- sessionDesc.compilerOptionEntryCount = 1;
- slang::CompilerOptionEntry entry;
- entry.name = slang::CompilerOptionName::UseUpToDateBinaryModule;
- entry.value.kind = slang::CompilerOptionValueKind::Int;
- entry.value.intValue0 = 1;
- sessionDesc.compilerOptionEntries = &entry;
- slang::TargetDesc targetDesc = {};
- switch (device->getDeviceInfo().deviceType)
- {
- case gfx::DeviceType::DirectX12:
- targetDesc.format = SLANG_DXIL;
- targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("sm_6_1");
- break;
- case gfx::DeviceType::Vulkan:
- targetDesc.format = SLANG_SPIRV;
- targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("GLSL_460");
- break;
- }
- sessionDesc.targets = &targetDesc;
- sessionDesc.fileSystem = fileSys;
- auto globalSession = slangSession->getGlobalSession();
- globalSession->createSession(sessionDesc, slangSession.writeRef());
- return slangSession;
+ case gfx::DeviceType::DirectX12:
+ targetDesc.format = SLANG_DXIL;
+ targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("sm_6_1");
+ break;
+ case gfx::DeviceType::Vulkan:
+ targetDesc.format = SLANG_SPIRV;
+ targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("GLSL_460");
+ break;
}
+ sessionDesc.targets = &targetDesc;
+ sessionDesc.fileSystem = fileSys;
+ auto globalSession = slangSession->getGlobalSession();
+ globalSession->createSession(sessionDesc, slangSession.writeRef());
+ return slangSession;
+}
- static Slang::Result precompileProgram(
- gfx::IDevice* device,
- ISlangMutableFileSystem* fileSys,
- const char* shaderModuleName)
- {
- Slang::ComPtr<slang::ISession> slangSession = createSession(device, fileSys);
+static Slang::Result precompileProgram(
+ gfx::IDevice* device,
+ ISlangMutableFileSystem* fileSys,
+ const char* shaderModuleName)
+{
+ Slang::ComPtr<slang::ISession> slangSession = createSession(device, fileSys);
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- if (!module)
- return SLANG_FAIL;
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ if (!module)
+ return SLANG_FAIL;
- // Write loaded modules to memory file system.
- for (SlangInt i = 0; i < slangSession->getLoadedModuleCount(); i++)
+ // Write loaded modules to memory file system.
+ for (SlangInt i = 0; i < slangSession->getLoadedModuleCount(); i++)
+ {
+ auto module = slangSession->getLoadedModule(i);
+ auto path = module->getFilePath();
+ if (path)
{
- auto module = slangSession->getLoadedModule(i);
- auto path = module->getFilePath();
- if (path)
- {
- auto name = module->getName();
- ComPtr<ISlangBlob> outBlob;
- module->serialize(outBlob.writeRef());
- fileSys->saveFileBlob((Slang::String("cache/") + Slang::String(name) + ".slang-module").getBuffer(), outBlob);
- }
+ auto name = module->getName();
+ ComPtr<ISlangBlob> outBlob;
+ module->serialize(outBlob.writeRef());
+ fileSys->saveFileBlob(
+ (Slang::String("cache/") + Slang::String(name) + ".slang-module").getBuffer(),
+ outBlob);
}
- return SLANG_OK;
}
+ return SLANG_OK;
+}
- void precompiledModuleCacheTestImpl(IDevice* device, UnitTestContext* context)
- {
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- // First, Initialize our file system.
- ComPtr<ISlangMutableFileSystem> memoryFileSystem = ComPtr<ISlangMutableFileSystem>(new Slang::MemoryFileSystem());
- memoryFileSystem->createDirectory("cache");
-
- const char* moduleSrc = R"(
+void precompiledModuleCacheTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ // First, Initialize our file system.
+ ComPtr<ISlangMutableFileSystem> memoryFileSystem =
+ ComPtr<ISlangMutableFileSystem>(new Slang::MemoryFileSystem());
+ memoryFileSystem->createDirectory("cache");
+
+ const char* moduleSrc = R"(
import "precompiled-module-imported";
// Main entry-point.
@@ -105,9 +107,9 @@ namespace gfx_test
buffer[sv_dispatchThreadID.x] = helperFunc() + helperFunc1();
}
)";
- memoryFileSystem->saveFile("precompiled-module.slang", moduleSrc, strlen(moduleSrc));
+ memoryFileSystem->saveFile("precompiled-module.slang", moduleSrc, strlen(moduleSrc));
- const char* moduleSrc2 = R"(
+ const char* moduleSrc2 = R"(
module "precompiled-module-imported";
__include "precompiled-module-included.slang";
@@ -120,8 +122,8 @@ namespace gfx_test
}
}
)";
- memoryFileSystem->saveFile("precompiled-module-imported.slang", moduleSrc2, strlen(moduleSrc2));
- const char* moduleSrc3 = R"(
+ memoryFileSystem->saveFile("precompiled-module-imported.slang", moduleSrc2, strlen(moduleSrc2));
+ const char* moduleSrc3 = R"(
implementing "precompiled-module-imported";
namespace ns
@@ -132,85 +134,90 @@ namespace gfx_test
}
}
)";
- memoryFileSystem->saveFile("precompiled-module-included.slang", moduleSrc3, strlen(moduleSrc3));
-
- // Precompile a module.
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(precompileProgram(device, memoryFileSystem.get(), "precompiled-module-imported"));
-
- // Next, load the precompiled slang program.
- Slang::ComPtr<slang::ISession> slangSession = createSession(device, memoryFileSystem);
- ComPtr<ISlangBlob> binaryBlob;
- memoryFileSystem->loadFile("cache/precompiled-module-imported.slang-module", binaryBlob.writeRef());
- auto upToDate = slangSession->isBinaryModuleUpToDate("precompiled-module-imported.slang", binaryBlob);
- SLANG_CHECK(upToDate); // The module should be up-to-date.
-
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, slangSession, shaderProgram, "precompiled-module", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 0.0f, 0.0f, 0.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
+ memoryFileSystem->saveFile("precompiled-module-included.slang", moduleSrc3, strlen(moduleSrc3));
+
+ // Precompile a module.
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(
+ precompileProgram(device, memoryFileSystem.get(), "precompiled-module-imported"));
+
+ // Next, load the precompiled slang program.
+ Slang::ComPtr<slang::ISession> slangSession = createSession(device, memoryFileSystem);
+ ComPtr<ISlangBlob> binaryBlob;
+ memoryFileSystem->loadFile(
+ "cache/precompiled-module-imported.slang-module",
+ binaryBlob.writeRef());
+ auto upToDate =
+ slangSession->isBinaryModuleUpToDate("precompiled-module-imported.slang", binaryBlob);
+ SLANG_CHECK(upToDate); // The module should be up-to-date.
+
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ slangSession,
+ shaderProgram,
+ "precompiled-module",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 0.0f, 0.0f, 0.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
+ {
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- auto rootObject = encoder->bindPipeline(pipelineState);
+ auto rootObject = encoder->bindPipeline(pipelineState);
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(3.0f, 3.0f, 3.0f, 3.0f));
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(3.0f, 3.0f, 3.0f, 3.0f));
- // Now we change the source and check if the precompiled module is still up-to-date.
- const char* moduleSrc4 = R"(
+ // Now we change the source and check if the precompiled module is still up-to-date.
+ const char* moduleSrc4 = R"(
implementing "precompiled-module-imported";
namespace ns {
public int helperFunc1() {
@@ -218,21 +225,22 @@ namespace gfx_test
}
}
)";
- memoryFileSystem->saveFile("precompiled-module-included.slang", moduleSrc4, strlen(moduleSrc4));
-
- slangSession = createSession(device, memoryFileSystem);
- upToDate = slangSession->isBinaryModuleUpToDate("precompiled-module-imported.slang", binaryBlob);
- SLANG_CHECK(!upToDate); // The module should not be up-to-date because the source has changed.
- }
+ memoryFileSystem->saveFile("precompiled-module-included.slang", moduleSrc4, strlen(moduleSrc4));
- SLANG_UNIT_TEST(precompiledModuleCacheD3D12)
- {
- runTestImpl(precompiledModuleCacheTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ slangSession = createSession(device, memoryFileSystem);
+ upToDate =
+ slangSession->isBinaryModuleUpToDate("precompiled-module-imported.slang", binaryBlob);
+ SLANG_CHECK(!upToDate); // The module should not be up-to-date because the source has changed.
+}
- SLANG_UNIT_TEST(precompiledModuleCacheVulkan)
- {
- runTestImpl(precompiledModuleCacheTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(precompiledModuleCacheD3D12)
+{
+ runTestImpl(precompiledModuleCacheTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+SLANG_UNIT_TEST(precompiledModuleCacheVulkan)
+{
+ runTestImpl(precompiledModuleCacheTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/precompiled-module.cpp b/tools/gfx-unit-test/precompiled-module.cpp
index 026575120..2ecc412c4 100644
--- a/tools/gfx-unit-test/precompiled-module.cpp
+++ b/tools/gfx-unit-test/precompiled-module.cpp
@@ -1,160 +1,161 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
#include "source/core/slang-blob.h"
#include "source/core/slang-memory-file-system.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- static Slang::Result precompileProgram(
- gfx::IDevice* device,
- ISlangMutableFileSystem* fileSys,
- const char* shaderModuleName)
+static Slang::Result precompileProgram(
+ gfx::IDevice* device,
+ ISlangMutableFileSystem* fileSys,
+ const char* shaderModuleName)
+{
+ Slang::ComPtr<slang::ISession> slangSession;
+ SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
+ slang::SessionDesc sessionDesc = {};
+ auto searchPaths = getSlangSearchPaths();
+ sessionDesc.searchPathCount = searchPaths.getCount();
+ sessionDesc.searchPaths = searchPaths.getBuffer();
+ auto globalSession = slangSession->getGlobalSession();
+ globalSession->createSession(sessionDesc, slangSession.writeRef());
+
+ Slang::ComPtr<slang::IBlob> diagnosticsBlob;
+ slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
+ diagnoseIfNeeded(diagnosticsBlob);
+ if (!module)
+ return SLANG_FAIL;
+
+ // Write loaded modules to memory file system.
+ for (SlangInt i = 0; i < slangSession->getLoadedModuleCount(); i++)
{
- Slang::ComPtr<slang::ISession> slangSession;
- SLANG_RETURN_ON_FAIL(device->getSlangSession(slangSession.writeRef()));
- slang::SessionDesc sessionDesc = {};
- auto searchPaths = getSlangSearchPaths();
- sessionDesc.searchPathCount = searchPaths.getCount();
- sessionDesc.searchPaths = searchPaths.getBuffer();
- auto globalSession = slangSession->getGlobalSession();
- globalSession->createSession(sessionDesc, slangSession.writeRef());
-
- Slang::ComPtr<slang::IBlob> diagnosticsBlob;
- slang::IModule* module = slangSession->loadModule(shaderModuleName, diagnosticsBlob.writeRef());
- diagnoseIfNeeded(diagnosticsBlob);
- if (!module)
- return SLANG_FAIL;
-
- // Write loaded modules to memory file system.
- for (SlangInt i = 0; i < slangSession->getLoadedModuleCount(); i++)
+ auto module = slangSession->getLoadedModule(i);
+ auto path = module->getFilePath();
+ if (path)
{
- auto module = slangSession->getLoadedModule(i);
- auto path = module->getFilePath();
- if (path)
- {
- auto name = module->getName();
- ComPtr<ISlangBlob> outBlob;
- module->serialize(outBlob.writeRef());
- fileSys->saveFileBlob((Slang::String(name) + ".slang-module").getBuffer(), outBlob);
- }
+ auto name = module->getName();
+ ComPtr<ISlangBlob> outBlob;
+ module->serialize(outBlob.writeRef());
+ fileSys->saveFileBlob((Slang::String(name) + ".slang-module").getBuffer(), outBlob);
}
- return SLANG_OK;
}
+ return SLANG_OK;
+}
- void precompiledModuleTestImpl(IDevice* device, UnitTestContext* context)
+void precompiledModuleTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ // First, load and compile the slang source.
+ ComPtr<ISlangMutableFileSystem> memoryFileSystem =
+ ComPtr<ISlangMutableFileSystem>(new Slang::MemoryFileSystem());
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(precompileProgram(device, memoryFileSystem.get(), "precompiled-module"));
+
+ // Next, load the precompiled slang program.
+ Slang::ComPtr<slang::ISession> slangSession;
+ device->getSlangSession(slangSession.writeRef());
+ slang::SessionDesc sessionDesc = {};
+ sessionDesc.targetCount = 1;
+ slang::TargetDesc targetDesc = {};
+ switch (device->getDeviceInfo().deviceType)
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- // First, load and compile the slang source.
- ComPtr<ISlangMutableFileSystem> memoryFileSystem = ComPtr<ISlangMutableFileSystem>(new Slang::MemoryFileSystem());
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(precompileProgram(device, memoryFileSystem.get(), "precompiled-module"));
-
- // Next, load the precompiled slang program.
- Slang::ComPtr<slang::ISession> slangSession;
- device->getSlangSession(slangSession.writeRef());
- slang::SessionDesc sessionDesc = {};
- sessionDesc.targetCount = 1;
- slang::TargetDesc targetDesc = {};
- switch (device->getDeviceInfo().deviceType)
- {
- case gfx::DeviceType::DirectX12:
- targetDesc.format = SLANG_DXIL;
- targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("sm_6_1");
- break;
- case gfx::DeviceType::Vulkan:
- targetDesc.format = SLANG_SPIRV;
- targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("GLSL_460");
- break;
- }
- sessionDesc.targets = &targetDesc;
- sessionDesc.fileSystem = memoryFileSystem.get();
- auto globalSession = slangSession->getGlobalSession();
- globalSession->createSession(sessionDesc, slangSession.writeRef());
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, slangSession, shaderProgram, "precompiled-module", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- float initialData[] = { 0.0f, 0.0f, 0.0f, 0.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
+ case gfx::DeviceType::DirectX12:
+ targetDesc.format = SLANG_DXIL;
+ targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("sm_6_1");
+ break;
+ case gfx::DeviceType::Vulkan:
+ targetDesc.format = SLANG_SPIRV;
+ targetDesc.profile = device->getSlangSession()->getGlobalSession()->findProfile("GLSL_460");
+ break;
+ }
+ sessionDesc.targets = &targetDesc;
+ sessionDesc.fileSystem = memoryFileSystem.get();
+ auto globalSession = slangSession->getGlobalSession();
+ globalSession->createSession(sessionDesc, slangSession.writeRef());
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ slangSession,
+ shaderProgram,
+ "precompiled-module",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 0.0f, 0.0f, 0.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
+ {
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- auto rootObject = encoder->bindPipeline(pipelineState);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- // Bind buffer view to the entry point.
- entryPointCursor.getPath("buffer").setResource(bufferView);
+ auto rootObject = encoder->bindPipeline(pipelineState);
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ // Bind buffer view to the entry point.
+ entryPointCursor.getPath("buffer").setResource(bufferView);
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(3.0f, 3.0f, 3.0f, 3.0f));
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(precompiledModuleD3D12)
- {
- runTestImpl(precompiledModuleTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(3.0f, 3.0f, 3.0f, 3.0f));
+}
- SLANG_UNIT_TEST(precompiledModuleVulkan)
- {
- runTestImpl(precompiledModuleTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(precompiledModuleD3D12)
+{
+ runTestImpl(precompiledModuleTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+SLANG_UNIT_TEST(precompiledModuleVulkan)
+{
+ runTestImpl(precompiledModuleTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/ray-tracing-tests.cpp b/tools/gfx-unit-test/ray-tracing-tests.cpp
index 97a6ad7d1..0e7fd2765 100644
--- a/tools/gfx-unit-test/ray-tracing-tests.cpp
+++ b/tools/gfx-unit-test/ray-tracing-tests.cpp
@@ -1,11 +1,10 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
-#include "gfx-test-util.h"
#include "gfx-test-texture-util.h"
+#include "gfx-test-util.h"
+#include "slang-gfx.h"
+#include "source/core/slang-basic.h"
#include "tools/gfx-util/shader-cursor.h"
#include "tools/platform/vector-math.h"
-#include "source/core/slang-basic.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <chrono>
@@ -14,482 +13,495 @@ using namespace Slang;
namespace gfx_test
{
- struct Vertex
- {
- float position[3];
- };
-
- static const int kVertexCount = 9;
- static const Vertex kVertexData[kVertexCount] =
- {
- // Triangle 1
- { 0, 0, 1 },
- { 4, 0, 1 },
- { 0, 4, 1 },
-
- // Triangle 2
- { -4, 0, 1 },
- { 0, 0, 1 },
- { 0, 4, 1 },
-
- // Triangle 3
- { 0, 0, 1 },
- { 4, 0, 1 },
- { 0, -4, 1 },
- };
- static const int kIndexCount = 9;
- static const uint32_t kIndexData[kIndexCount] =
- {
- 0, 1, 2,
- 3, 4, 5,
- 6, 7, 8,
- };
-
- struct BaseRayTracingTest
+struct Vertex
+{
+ float position[3];
+};
+
+static const int kVertexCount = 9;
+static const Vertex kVertexData[kVertexCount] = {
+ // Triangle 1
+ {0, 0, 1},
+ {4, 0, 1},
+ {0, 4, 1},
+
+ // Triangle 2
+ {-4, 0, 1},
+ {0, 0, 1},
+ {0, 4, 1},
+
+ // Triangle 3
+ {0, 0, 1},
+ {4, 0, 1},
+ {0, -4, 1},
+};
+static const int kIndexCount = 9;
+static const uint32_t kIndexData[kIndexCount] = {
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 8,
+};
+
+struct BaseRayTracingTest
+{
+ IDevice* device;
+ UnitTestContext* context;
+
+ ComPtr<IFramebufferLayout> framebufferLayout;
+ ComPtr<ITransientResourceHeap> transientHeap;
+ ComPtr<ICommandQueue> queue;
+
+ ComPtr<IPipelineState> renderPipelineState;
+ ComPtr<IBufferResource> vertexBuffer;
+ ComPtr<IBufferResource> indexBuffer;
+ ComPtr<IBufferResource> transformBuffer;
+ ComPtr<IBufferResource> instanceBuffer;
+ ComPtr<IBufferResource> BLASBuffer;
+ ComPtr<IAccelerationStructure> BLAS;
+ ComPtr<IBufferResource> TLASBuffer;
+ ComPtr<IAccelerationStructure> TLAS;
+ ComPtr<ITextureResource> resultTexture;
+ ComPtr<IResourceView> resultTextureUAV;
+ ComPtr<IShaderTable> shaderTable;
+
+ uint32_t width = 2;
+ uint32_t height = 2;
+
+ void init(IDevice* device, UnitTestContext* context)
{
- IDevice* device;
- UnitTestContext* context;
-
- ComPtr<IFramebufferLayout> framebufferLayout;
- ComPtr<ITransientResourceHeap> transientHeap;
- ComPtr<ICommandQueue> queue;
-
- ComPtr<IPipelineState> renderPipelineState;
- ComPtr<IBufferResource> vertexBuffer;
- ComPtr<IBufferResource> indexBuffer;
- ComPtr<IBufferResource> transformBuffer;
- ComPtr<IBufferResource> instanceBuffer;
- ComPtr<IBufferResource> BLASBuffer;
- ComPtr<IAccelerationStructure> BLAS;
- ComPtr<IBufferResource> TLASBuffer;
- ComPtr<IAccelerationStructure> TLAS;
- ComPtr<ITextureResource> resultTexture;
- ComPtr<IResourceView> resultTextureUAV;
- ComPtr<IShaderTable> shaderTable;
-
- uint32_t width = 2;
- uint32_t height = 2;
-
- void init(IDevice* device, UnitTestContext* context)
+ if (!device->hasFeature("ray-tracing"))
{
- if (!device->hasFeature("ray-tracing"))
- {
- SLANG_IGNORE_TEST;
- }
-
- this->device = device;
- this->context = context;
+ SLANG_IGNORE_TEST;
}
- // Load and compile shader code from source.
- gfx::Result loadShaderProgram(gfx::IDevice* device, gfx::IShaderProgram** outProgram)
- {
- ComPtr<slang::ISession> slangSession;
- slangSession = device->getSlangSession();
-
- ComPtr<slang::IBlob> diagnosticsBlob;
- slang::IModule* module = slangSession->loadModule("ray-tracing-test-shaders", diagnosticsBlob.writeRef());
- if (!module)
- return SLANG_FAIL;
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(module);
- ComPtr<slang::IEntryPoint> entryPoint;
- SLANG_RETURN_ON_FAIL(module->findEntryPointByName("rayGenShaderA", entryPoint.writeRef()));
- componentTypes.add(entryPoint);
- SLANG_RETURN_ON_FAIL(module->findEntryPointByName("rayGenShaderB", entryPoint.writeRef()));
- componentTypes.add(entryPoint);
- SLANG_RETURN_ON_FAIL(module->findEntryPointByName("missShaderA", entryPoint.writeRef()));
- componentTypes.add(entryPoint);
- SLANG_RETURN_ON_FAIL(module->findEntryPointByName("missShaderB", entryPoint.writeRef()));
- componentTypes.add(entryPoint);
- SLANG_RETURN_ON_FAIL(
- module->findEntryPointByName("closestHitShaderA", entryPoint.writeRef()));
- componentTypes.add(entryPoint);
- SLANG_RETURN_ON_FAIL(
- module->findEntryPointByName("closestHitShaderB", entryPoint.writeRef()));
- componentTypes.add(entryPoint);
-
- ComPtr<slang::IComponentType> linkedProgram;
- SlangResult result = slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- linkedProgram.writeRef(),
- diagnosticsBlob.writeRef());
- SLANG_RETURN_ON_FAIL(result);
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = linkedProgram;
- SLANG_RETURN_ON_FAIL(device->createProgram(programDesc, outProgram));
-
- return SLANG_OK;
- }
+ this->device = device;
+ this->context = context;
+ }
- void createResultTexture()
- {
- ITextureResource::Desc resultTextureDesc = {};
- resultTextureDesc.type = IResource::Type::Texture2D;
- resultTextureDesc.numMipLevels = 1;
- resultTextureDesc.size.width = width;
- resultTextureDesc.size.height = height;
- resultTextureDesc.size.depth = 1;
- resultTextureDesc.defaultState = ResourceState::UnorderedAccess;
- resultTextureDesc.format = Format::R32G32B32A32_FLOAT;
- resultTexture = device->createTextureResource(resultTextureDesc);
- IResourceView::Desc resultUAVDesc = {};
- resultUAVDesc.format = resultTextureDesc.format;
- resultUAVDesc.type = IResourceView::Type::UnorderedAccess;
- resultTextureUAV = device->createTextureView(resultTexture, resultUAVDesc);
- }
+ // Load and compile shader code from source.
+ gfx::Result loadShaderProgram(gfx::IDevice* device, gfx::IShaderProgram** outProgram)
+ {
+ ComPtr<slang::ISession> slangSession;
+ slangSession = device->getSlangSession();
+
+ ComPtr<slang::IBlob> diagnosticsBlob;
+ slang::IModule* module =
+ slangSession->loadModule("ray-tracing-test-shaders", diagnosticsBlob.writeRef());
+ if (!module)
+ return SLANG_FAIL;
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(module);
+ ComPtr<slang::IEntryPoint> entryPoint;
+ SLANG_RETURN_ON_FAIL(module->findEntryPointByName("rayGenShaderA", entryPoint.writeRef()));
+ componentTypes.add(entryPoint);
+ SLANG_RETURN_ON_FAIL(module->findEntryPointByName("rayGenShaderB", entryPoint.writeRef()));
+ componentTypes.add(entryPoint);
+ SLANG_RETURN_ON_FAIL(module->findEntryPointByName("missShaderA", entryPoint.writeRef()));
+ componentTypes.add(entryPoint);
+ SLANG_RETURN_ON_FAIL(module->findEntryPointByName("missShaderB", entryPoint.writeRef()));
+ componentTypes.add(entryPoint);
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName("closestHitShaderA", entryPoint.writeRef()));
+ componentTypes.add(entryPoint);
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName("closestHitShaderB", entryPoint.writeRef()));
+ componentTypes.add(entryPoint);
+
+ ComPtr<slang::IComponentType> linkedProgram;
+ SlangResult result = slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ linkedProgram.writeRef(),
+ diagnosticsBlob.writeRef());
+ SLANG_RETURN_ON_FAIL(result);
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = linkedProgram;
+ SLANG_RETURN_ON_FAIL(device->createProgram(programDesc, outProgram));
+
+ return SLANG_OK;
+ }
- void createRequiredResources()
- {
- ICommandQueue::Desc queueDesc = {};
- queueDesc.type = ICommandQueue::QueueType::Graphics;
- queue = device->createCommandQueue(queueDesc);
-
- IBufferResource::Desc vertexBufferDesc;
- vertexBufferDesc.type = IResource::Type::Buffer;
- vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
- vertexBufferDesc.defaultState = ResourceState::ShaderResource;
- vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
- SLANG_CHECK_ABORT(vertexBuffer != nullptr);
-
- IBufferResource::Desc indexBufferDesc;
- indexBufferDesc.type = IResource::Type::Buffer;
- indexBufferDesc.sizeInBytes = kIndexCount * sizeof(int32_t);
- indexBufferDesc.defaultState = ResourceState::ShaderResource;
- indexBuffer = device->createBufferResource(indexBufferDesc, &kIndexData[0]);
- SLANG_CHECK_ABORT(indexBuffer != nullptr);
-
- IBufferResource::Desc transformBufferDesc;
- transformBufferDesc.type = IResource::Type::Buffer;
- transformBufferDesc.sizeInBytes = sizeof(float) * 12;
- transformBufferDesc.defaultState = ResourceState::ShaderResource;
- float transformData[12] = {
- 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f };
- transformBuffer = device->createBufferResource(transformBufferDesc, &transformData);
- SLANG_CHECK_ABORT(transformBuffer != nullptr);
-
- createResultTexture();
-
- IFramebufferLayout::TargetLayout renderTargetLayout = { Format::R8G8B8A8_UNORM, 1 };
- IFramebufferLayout::TargetLayout depthLayout = { gfx::Format::D32_FLOAT, 1 };
- IFramebufferLayout::Desc framebufferLayoutDesc;
- framebufferLayoutDesc.renderTargetCount = 1;
- framebufferLayoutDesc.renderTargets = &renderTargetLayout;
- framebufferLayoutDesc.depthStencil = &depthLayout;
- GFX_CHECK_CALL_ABORT(
- device->createFramebufferLayout(framebufferLayoutDesc, framebufferLayout.writeRef()));
+ void createResultTexture()
+ {
+ ITextureResource::Desc resultTextureDesc = {};
+ resultTextureDesc.type = IResource::Type::Texture2D;
+ resultTextureDesc.numMipLevels = 1;
+ resultTextureDesc.size.width = width;
+ resultTextureDesc.size.height = height;
+ resultTextureDesc.size.depth = 1;
+ resultTextureDesc.defaultState = ResourceState::UnorderedAccess;
+ resultTextureDesc.format = Format::R32G32B32A32_FLOAT;
+ resultTexture = device->createTextureResource(resultTextureDesc);
+ IResourceView::Desc resultUAVDesc = {};
+ resultUAVDesc.format = resultTextureDesc.format;
+ resultUAVDesc.type = IResourceView::Type::UnorderedAccess;
+ resultTextureUAV = device->createTextureView(resultTexture, resultUAVDesc);
+ }
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096 * 1024;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- // Build bottom level acceleration structure.
- {
- IAccelerationStructure::BuildInputs accelerationStructureBuildInputs;
- IAccelerationStructure::PrebuildInfo accelerationStructurePrebuildInfo;
- accelerationStructureBuildInputs.descCount = 1;
- accelerationStructureBuildInputs.kind = IAccelerationStructure::Kind::BottomLevel;
- accelerationStructureBuildInputs.flags =
- IAccelerationStructure::BuildFlags::AllowCompaction;
- IAccelerationStructure::GeometryDesc geomDesc;
- geomDesc.flags = IAccelerationStructure::GeometryFlags::Opaque;
- geomDesc.type = IAccelerationStructure::GeometryType::Triangles;
- geomDesc.content.triangles.indexCount = kIndexCount;
- geomDesc.content.triangles.indexData = indexBuffer->getDeviceAddress();
- geomDesc.content.triangles.indexFormat = Format::R32_UINT;
- geomDesc.content.triangles.vertexCount = kVertexCount;
- geomDesc.content.triangles.vertexData = vertexBuffer->getDeviceAddress();
- geomDesc.content.triangles.vertexFormat = Format::R32G32B32_FLOAT;
- geomDesc.content.triangles.vertexStride = sizeof(Vertex);
- geomDesc.content.triangles.transform3x4 = transformBuffer->getDeviceAddress();
- accelerationStructureBuildInputs.geometryDescs = &geomDesc;
-
- // Query buffer size for acceleration structure build.
- GFX_CHECK_CALL_ABORT(device->getAccelerationStructurePrebuildInfo(
- accelerationStructureBuildInputs, &accelerationStructurePrebuildInfo));
- // Allocate buffers for acceleration structure.
- IBufferResource::Desc asDraftBufferDesc;
- asDraftBufferDesc.type = IResource::Type::Buffer;
- asDraftBufferDesc.defaultState = ResourceState::AccelerationStructure;
- asDraftBufferDesc.sizeInBytes = (size_t)accelerationStructurePrebuildInfo.resultDataMaxSize;
- ComPtr<IBufferResource> draftBuffer = device->createBufferResource(asDraftBufferDesc);
- IBufferResource::Desc scratchBufferDesc;
- scratchBufferDesc.type = IResource::Type::Buffer;
- scratchBufferDesc.defaultState = ResourceState::UnorderedAccess;
- scratchBufferDesc.sizeInBytes = (size_t)accelerationStructurePrebuildInfo.scratchDataSize;
- ComPtr<IBufferResource> scratchBuffer = device->createBufferResource(scratchBufferDesc);
-
- // Build acceleration structure.
- ComPtr<IQueryPool> compactedSizeQuery;
- IQueryPool::Desc queryPoolDesc;
- queryPoolDesc.count = 1;
- queryPoolDesc.type = QueryType::AccelerationStructureCompactedSize;
- GFX_CHECK_CALL_ABORT(
- device->createQueryPool(queryPoolDesc, compactedSizeQuery.writeRef()));
-
- ComPtr<IAccelerationStructure> draftAS;
- IAccelerationStructure::CreateDesc draftCreateDesc;
- draftCreateDesc.buffer = draftBuffer;
- draftCreateDesc.kind = IAccelerationStructure::Kind::BottomLevel;
- draftCreateDesc.offset = 0;
- draftCreateDesc.size = accelerationStructurePrebuildInfo.resultDataMaxSize;
- GFX_CHECK_CALL_ABORT(
- device->createAccelerationStructure(draftCreateDesc, draftAS.writeRef()));
-
- compactedSizeQuery->reset();
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeRayTracingCommands();
- IAccelerationStructure::BuildDesc buildDesc = {};
- buildDesc.dest = draftAS;
- buildDesc.inputs = accelerationStructureBuildInputs;
- buildDesc.scratchData = scratchBuffer->getDeviceAddress();
- AccelerationStructureQueryDesc compactedSizeQueryDesc = {};
- compactedSizeQueryDesc.queryPool = compactedSizeQuery;
- compactedSizeQueryDesc.queryType = QueryType::AccelerationStructureCompactedSize;
- encoder->buildAccelerationStructure(buildDesc, 1, &compactedSizeQueryDesc);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
-
- uint64_t compactedSize = 0;
- compactedSizeQuery->getResult(0, 1, &compactedSize);
- IBufferResource::Desc asBufferDesc;
- asBufferDesc.type = IResource::Type::Buffer;
- asBufferDesc.defaultState = ResourceState::AccelerationStructure;
- asBufferDesc.sizeInBytes = (size_t)compactedSize;
- BLASBuffer = device->createBufferResource(asBufferDesc);
- IAccelerationStructure::CreateDesc createDesc;
- createDesc.buffer = BLASBuffer;
- createDesc.kind = IAccelerationStructure::Kind::BottomLevel;
- createDesc.offset = 0;
- createDesc.size = (size_t)compactedSize;
- device->createAccelerationStructure(createDesc, BLAS.writeRef());
-
- commandBuffer = transientHeap->createCommandBuffer();
- encoder = commandBuffer->encodeRayTracingCommands();
- encoder->copyAccelerationStructure(BLAS, draftAS, AccelerationStructureCopyMode::Compact);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- // Build top level acceleration structure.
- {
- List<IAccelerationStructure::InstanceDesc> instanceDescs;
- instanceDescs.setCount(1);
- instanceDescs[0].accelerationStructure = BLAS->getDeviceAddress();
- instanceDescs[0].flags =
- IAccelerationStructure::GeometryInstanceFlags::TriangleFacingCullDisable;
- instanceDescs[0].instanceContributionToHitGroupIndex = 0;
- instanceDescs[0].instanceID = 0;
- instanceDescs[0].instanceMask = 0xFF;
- float transformMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f };
- memcpy(&instanceDescs[0].transform[0][0], transformMatrix, sizeof(float) * 12);
-
- IBufferResource::Desc instanceBufferDesc;
- instanceBufferDesc.type = IResource::Type::Buffer;
- instanceBufferDesc.sizeInBytes =
- instanceDescs.getCount() * sizeof(IAccelerationStructure::InstanceDesc);
- instanceBufferDesc.defaultState = ResourceState::ShaderResource;
- instanceBuffer = device->createBufferResource(instanceBufferDesc, instanceDescs.getBuffer());
- SLANG_CHECK_ABORT(instanceBuffer != nullptr);
-
- IAccelerationStructure::BuildInputs accelerationStructureBuildInputs = {};
- IAccelerationStructure::PrebuildInfo accelerationStructurePrebuildInfo = {};
- accelerationStructureBuildInputs.descCount = 1;
- accelerationStructureBuildInputs.kind = IAccelerationStructure::Kind::TopLevel;
- accelerationStructureBuildInputs.instanceDescs = instanceBuffer->getDeviceAddress();
-
- // Query buffer size for acceleration structure build.
- GFX_CHECK_CALL_ABORT(device->getAccelerationStructurePrebuildInfo(
- accelerationStructureBuildInputs, &accelerationStructurePrebuildInfo));
-
- IBufferResource::Desc asBufferDesc;
- asBufferDesc.type = IResource::Type::Buffer;
- asBufferDesc.defaultState = ResourceState::AccelerationStructure;
- asBufferDesc.sizeInBytes = (size_t)accelerationStructurePrebuildInfo.resultDataMaxSize;
- TLASBuffer = device->createBufferResource(asBufferDesc);
-
- IBufferResource::Desc scratchBufferDesc;
- scratchBufferDesc.type = IResource::Type::Buffer;
- scratchBufferDesc.defaultState = ResourceState::UnorderedAccess;
- scratchBufferDesc.sizeInBytes = (size_t)accelerationStructurePrebuildInfo.scratchDataSize;
- ComPtr<IBufferResource> scratchBuffer = device->createBufferResource(scratchBufferDesc);
-
- IAccelerationStructure::CreateDesc createDesc;
- createDesc.buffer = TLASBuffer;
- createDesc.kind = IAccelerationStructure::Kind::TopLevel;
- createDesc.offset = 0;
- createDesc.size = (size_t)accelerationStructurePrebuildInfo.resultDataMaxSize;
- GFX_CHECK_CALL_ABORT(device->createAccelerationStructure(createDesc, TLAS.writeRef()));
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeRayTracingCommands();
- IAccelerationStructure::BuildDesc buildDesc = {};
- buildDesc.dest = TLAS;
- buildDesc.inputs = accelerationStructureBuildInputs;
- buildDesc.scratchData = scratchBuffer->getDeviceAddress();
- encoder->buildAccelerationStructure(buildDesc, 0, nullptr);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- const char* hitgroupNames[] = { "hitgroupA", "hitgroupB"};
-
- ComPtr<IShaderProgram> rayTracingProgram;
+ void createRequiredResources()
+ {
+ ICommandQueue::Desc queueDesc = {};
+ queueDesc.type = ICommandQueue::QueueType::Graphics;
+ queue = device->createCommandQueue(queueDesc);
+
+ IBufferResource::Desc vertexBufferDesc;
+ vertexBufferDesc.type = IResource::Type::Buffer;
+ vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
+ vertexBufferDesc.defaultState = ResourceState::ShaderResource;
+ vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
+ SLANG_CHECK_ABORT(vertexBuffer != nullptr);
+
+ IBufferResource::Desc indexBufferDesc;
+ indexBufferDesc.type = IResource::Type::Buffer;
+ indexBufferDesc.sizeInBytes = kIndexCount * sizeof(int32_t);
+ indexBufferDesc.defaultState = ResourceState::ShaderResource;
+ indexBuffer = device->createBufferResource(indexBufferDesc, &kIndexData[0]);
+ SLANG_CHECK_ABORT(indexBuffer != nullptr);
+
+ IBufferResource::Desc transformBufferDesc;
+ transformBufferDesc.type = IResource::Type::Buffer;
+ transformBufferDesc.sizeInBytes = sizeof(float) * 12;
+ transformBufferDesc.defaultState = ResourceState::ShaderResource;
+ float transformData[12] =
+ {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
+ transformBuffer = device->createBufferResource(transformBufferDesc, &transformData);
+ SLANG_CHECK_ABORT(transformBuffer != nullptr);
+
+ createResultTexture();
+
+ IFramebufferLayout::TargetLayout renderTargetLayout = {Format::R8G8B8A8_UNORM, 1};
+ IFramebufferLayout::TargetLayout depthLayout = {gfx::Format::D32_FLOAT, 1};
+ IFramebufferLayout::Desc framebufferLayoutDesc;
+ framebufferLayoutDesc.renderTargetCount = 1;
+ framebufferLayoutDesc.renderTargets = &renderTargetLayout;
+ framebufferLayoutDesc.depthStencil = &depthLayout;
+ GFX_CHECK_CALL_ABORT(
+ device->createFramebufferLayout(framebufferLayoutDesc, framebufferLayout.writeRef()));
+
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096 * 1024;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ // Build bottom level acceleration structure.
+ {
+ IAccelerationStructure::BuildInputs accelerationStructureBuildInputs;
+ IAccelerationStructure::PrebuildInfo accelerationStructurePrebuildInfo;
+ accelerationStructureBuildInputs.descCount = 1;
+ accelerationStructureBuildInputs.kind = IAccelerationStructure::Kind::BottomLevel;
+ accelerationStructureBuildInputs.flags =
+ IAccelerationStructure::BuildFlags::AllowCompaction;
+ IAccelerationStructure::GeometryDesc geomDesc;
+ geomDesc.flags = IAccelerationStructure::GeometryFlags::Opaque;
+ geomDesc.type = IAccelerationStructure::GeometryType::Triangles;
+ geomDesc.content.triangles.indexCount = kIndexCount;
+ geomDesc.content.triangles.indexData = indexBuffer->getDeviceAddress();
+ geomDesc.content.triangles.indexFormat = Format::R32_UINT;
+ geomDesc.content.triangles.vertexCount = kVertexCount;
+ geomDesc.content.triangles.vertexData = vertexBuffer->getDeviceAddress();
+ geomDesc.content.triangles.vertexFormat = Format::R32G32B32_FLOAT;
+ geomDesc.content.triangles.vertexStride = sizeof(Vertex);
+ geomDesc.content.triangles.transform3x4 = transformBuffer->getDeviceAddress();
+ accelerationStructureBuildInputs.geometryDescs = &geomDesc;
+
+ // Query buffer size for acceleration structure build.
+ GFX_CHECK_CALL_ABORT(device->getAccelerationStructurePrebuildInfo(
+ accelerationStructureBuildInputs,
+ &accelerationStructurePrebuildInfo));
+ // Allocate buffers for acceleration structure.
+ IBufferResource::Desc asDraftBufferDesc;
+ asDraftBufferDesc.type = IResource::Type::Buffer;
+ asDraftBufferDesc.defaultState = ResourceState::AccelerationStructure;
+ asDraftBufferDesc.sizeInBytes =
+ (size_t)accelerationStructurePrebuildInfo.resultDataMaxSize;
+ ComPtr<IBufferResource> draftBuffer = device->createBufferResource(asDraftBufferDesc);
+ IBufferResource::Desc scratchBufferDesc;
+ scratchBufferDesc.type = IResource::Type::Buffer;
+ scratchBufferDesc.defaultState = ResourceState::UnorderedAccess;
+ scratchBufferDesc.sizeInBytes =
+ (size_t)accelerationStructurePrebuildInfo.scratchDataSize;
+ ComPtr<IBufferResource> scratchBuffer = device->createBufferResource(scratchBufferDesc);
+
+ // Build acceleration structure.
+ ComPtr<IQueryPool> compactedSizeQuery;
+ IQueryPool::Desc queryPoolDesc;
+ queryPoolDesc.count = 1;
+ queryPoolDesc.type = QueryType::AccelerationStructureCompactedSize;
GFX_CHECK_CALL_ABORT(
- loadShaderProgram(device, rayTracingProgram.writeRef()));
- RayTracingPipelineStateDesc rtpDesc = {};
- rtpDesc.program = rayTracingProgram;
- rtpDesc.hitGroupCount = 2;
- HitGroupDesc hitGroups[2];
- hitGroups[0].closestHitEntryPoint = "closestHitShaderA";
- hitGroups[0].hitGroupName = hitgroupNames[0];
- hitGroups[1].closestHitEntryPoint = "closestHitShaderB";
- hitGroups[1].hitGroupName = hitgroupNames[1];
- rtpDesc.hitGroups = hitGroups;
- rtpDesc.maxRayPayloadSize = 64;
- rtpDesc.maxRecursion = 2;
+ device->createQueryPool(queryPoolDesc, compactedSizeQuery.writeRef()));
+
+ ComPtr<IAccelerationStructure> draftAS;
+ IAccelerationStructure::CreateDesc draftCreateDesc;
+ draftCreateDesc.buffer = draftBuffer;
+ draftCreateDesc.kind = IAccelerationStructure::Kind::BottomLevel;
+ draftCreateDesc.offset = 0;
+ draftCreateDesc.size = accelerationStructurePrebuildInfo.resultDataMaxSize;
GFX_CHECK_CALL_ABORT(
- device->createRayTracingPipelineState(rtpDesc, renderPipelineState.writeRef()));
- SLANG_CHECK_ABORT(renderPipelineState != nullptr);
-
- const char* raygenNames[] = { "rayGenShaderA", "rayGenShaderB" };
- const char* missNames[] = { "missShaderA", "missShaderB" };
-
- IShaderTable::Desc shaderTableDesc = {};
- shaderTableDesc.program = rayTracingProgram;
- shaderTableDesc.hitGroupCount = 2;
- shaderTableDesc.hitGroupNames = hitgroupNames;
- shaderTableDesc.rayGenShaderCount = 2;
- shaderTableDesc.rayGenShaderEntryPointNames = raygenNames;
- shaderTableDesc.missShaderCount = 2;
- shaderTableDesc.missShaderEntryPointNames = missNames;
- GFX_CHECK_CALL_ABORT(device->createShaderTable(shaderTableDesc, shaderTable.writeRef()));
- }
-
- void checkTestResults(float* expectedResult, uint32_t count)
- {
- ComPtr<ISlangBlob> resultBlob;
- size_t rowPitch = 0;
- size_t pixelSize = 0;
- auto cmdBuffer = transientHeap->createCommandBuffer();
- auto encoder = cmdBuffer->encodeResourceCommands();
- encoder->textureBarrier(resultTexture.get(), ResourceState::UnorderedAccess, ResourceState::CopySource);
+ device->createAccelerationStructure(draftCreateDesc, draftAS.writeRef()));
+
+ compactedSizeQuery->reset();
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeRayTracingCommands();
+ IAccelerationStructure::BuildDesc buildDesc = {};
+ buildDesc.dest = draftAS;
+ buildDesc.inputs = accelerationStructureBuildInputs;
+ buildDesc.scratchData = scratchBuffer->getDeviceAddress();
+ AccelerationStructureQueryDesc compactedSizeQueryDesc = {};
+ compactedSizeQueryDesc.queryPool = compactedSizeQuery;
+ compactedSizeQueryDesc.queryType = QueryType::AccelerationStructureCompactedSize;
+ encoder->buildAccelerationStructure(buildDesc, 1, &compactedSizeQueryDesc);
encoder->endEncoding();
- cmdBuffer->close();
- queue->executeCommandBuffer(cmdBuffer.get());
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
queue->waitOnHost();
- GFX_CHECK_CALL_ABORT(device->readTextureResource(
- resultTexture, ResourceState::CopySource, resultBlob.writeRef(), &rowPitch, &pixelSize));
-#if 0 // for debugging only
- writeImage("test.hdr", resultBlob, width, height, (uint32_t)rowPitch, (uint32_t)pixelSize);
-#endif
- auto buffer = removePadding(resultBlob, width, height, rowPitch, pixelSize);
- auto actualData = (float*)buffer.getBuffer();
- SLANG_CHECK(memcmp(actualData, expectedResult, count * sizeof(float)) == 0)
- }
- };
-
- struct RayTracingTestA : BaseRayTracingTest
- {
- void renderFrame()
- {
- ComPtr<ICommandBuffer> renderCommandBuffer =
- transientHeap->createCommandBuffer();
- auto renderEncoder = renderCommandBuffer->encodeRayTracingCommands();
- IShaderObject* rootObject = nullptr;
- renderEncoder->bindPipeline(renderPipelineState, &rootObject);
- auto cursor = ShaderCursor(rootObject);
- cursor["resultTexture"].setResource(resultTextureUAV);
- cursor["sceneBVH"].setResource(TLAS);
- renderEncoder->dispatchRays(0, shaderTable, width, height, 1);
- renderEncoder->endEncoding();
- renderCommandBuffer->close();
- queue->executeCommandBuffer(renderCommandBuffer);
+ uint64_t compactedSize = 0;
+ compactedSizeQuery->getResult(0, 1, &compactedSize);
+ IBufferResource::Desc asBufferDesc;
+ asBufferDesc.type = IResource::Type::Buffer;
+ asBufferDesc.defaultState = ResourceState::AccelerationStructure;
+ asBufferDesc.sizeInBytes = (size_t)compactedSize;
+ BLASBuffer = device->createBufferResource(asBufferDesc);
+ IAccelerationStructure::CreateDesc createDesc;
+ createDesc.buffer = BLASBuffer;
+ createDesc.kind = IAccelerationStructure::Kind::BottomLevel;
+ createDesc.offset = 0;
+ createDesc.size = (size_t)compactedSize;
+ device->createAccelerationStructure(createDesc, BLAS.writeRef());
+
+ commandBuffer = transientHeap->createCommandBuffer();
+ encoder = commandBuffer->encodeRayTracingCommands();
+ encoder->copyAccelerationStructure(
+ BLAS,
+ draftAS,
+ AccelerationStructureCopyMode::Compact);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
queue->waitOnHost();
}
- void run()
- {
- createRequiredResources();
- renderFrame();
-
- float expectedResult[16] = { 1, 1, 1, 1,
- 0, 0, 1, 1,
- 0, 1, 0, 1,
- 1, 0, 0, 1 };
- checkTestResults(expectedResult, 16);
- }
- };
-
- struct RayTracingTestB : BaseRayTracingTest
- {
- void renderFrame()
+ // Build top level acceleration structure.
{
- ComPtr<ICommandBuffer> renderCommandBuffer =
- transientHeap->createCommandBuffer();
- auto renderEncoder = renderCommandBuffer->encodeRayTracingCommands();
- IShaderObject* rootObject = nullptr;
- renderEncoder->bindPipeline(renderPipelineState, &rootObject);
- auto cursor = ShaderCursor(rootObject);
- cursor["resultTexture"].setResource(resultTextureUAV);
- cursor["sceneBVH"].setResource(TLAS);
- renderEncoder->dispatchRays(1, shaderTable, width, height, 1);
- renderEncoder->endEncoding();
- renderCommandBuffer->close();
- queue->executeCommandBuffer(renderCommandBuffer);
+ List<IAccelerationStructure::InstanceDesc> instanceDescs;
+ instanceDescs.setCount(1);
+ instanceDescs[0].accelerationStructure = BLAS->getDeviceAddress();
+ instanceDescs[0].flags =
+ IAccelerationStructure::GeometryInstanceFlags::TriangleFacingCullDisable;
+ instanceDescs[0].instanceContributionToHitGroupIndex = 0;
+ instanceDescs[0].instanceID = 0;
+ instanceDescs[0].instanceMask = 0xFF;
+ float transformMatrix[] =
+ {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
+ memcpy(&instanceDescs[0].transform[0][0], transformMatrix, sizeof(float) * 12);
+
+ IBufferResource::Desc instanceBufferDesc;
+ instanceBufferDesc.type = IResource::Type::Buffer;
+ instanceBufferDesc.sizeInBytes =
+ instanceDescs.getCount() * sizeof(IAccelerationStructure::InstanceDesc);
+ instanceBufferDesc.defaultState = ResourceState::ShaderResource;
+ instanceBuffer =
+ device->createBufferResource(instanceBufferDesc, instanceDescs.getBuffer());
+ SLANG_CHECK_ABORT(instanceBuffer != nullptr);
+
+ IAccelerationStructure::BuildInputs accelerationStructureBuildInputs = {};
+ IAccelerationStructure::PrebuildInfo accelerationStructurePrebuildInfo = {};
+ accelerationStructureBuildInputs.descCount = 1;
+ accelerationStructureBuildInputs.kind = IAccelerationStructure::Kind::TopLevel;
+ accelerationStructureBuildInputs.instanceDescs = instanceBuffer->getDeviceAddress();
+
+ // Query buffer size for acceleration structure build.
+ GFX_CHECK_CALL_ABORT(device->getAccelerationStructurePrebuildInfo(
+ accelerationStructureBuildInputs,
+ &accelerationStructurePrebuildInfo));
+
+ IBufferResource::Desc asBufferDesc;
+ asBufferDesc.type = IResource::Type::Buffer;
+ asBufferDesc.defaultState = ResourceState::AccelerationStructure;
+ asBufferDesc.sizeInBytes = (size_t)accelerationStructurePrebuildInfo.resultDataMaxSize;
+ TLASBuffer = device->createBufferResource(asBufferDesc);
+
+ IBufferResource::Desc scratchBufferDesc;
+ scratchBufferDesc.type = IResource::Type::Buffer;
+ scratchBufferDesc.defaultState = ResourceState::UnorderedAccess;
+ scratchBufferDesc.sizeInBytes =
+ (size_t)accelerationStructurePrebuildInfo.scratchDataSize;
+ ComPtr<IBufferResource> scratchBuffer = device->createBufferResource(scratchBufferDesc);
+
+ IAccelerationStructure::CreateDesc createDesc;
+ createDesc.buffer = TLASBuffer;
+ createDesc.kind = IAccelerationStructure::Kind::TopLevel;
+ createDesc.offset = 0;
+ createDesc.size = (size_t)accelerationStructurePrebuildInfo.resultDataMaxSize;
+ GFX_CHECK_CALL_ABORT(device->createAccelerationStructure(createDesc, TLAS.writeRef()));
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeRayTracingCommands();
+ IAccelerationStructure::BuildDesc buildDesc = {};
+ buildDesc.dest = TLAS;
+ buildDesc.inputs = accelerationStructureBuildInputs;
+ buildDesc.scratchData = scratchBuffer->getDeviceAddress();
+ encoder->buildAccelerationStructure(buildDesc, 0, nullptr);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
queue->waitOnHost();
}
- void run()
- {
- createRequiredResources();
- renderFrame();
-
- float expectedResult[16] = { 0, 0, 0, 1,
- 1, 1, 0, 1,
- 1, 0, 1, 1,
- 0, 1, 1, 1 };
- checkTestResults(expectedResult, 16);
- }
- };
+ const char* hitgroupNames[] = {"hitgroupA", "hitgroupB"};
+
+ ComPtr<IShaderProgram> rayTracingProgram;
+ GFX_CHECK_CALL_ABORT(loadShaderProgram(device, rayTracingProgram.writeRef()));
+ RayTracingPipelineStateDesc rtpDesc = {};
+ rtpDesc.program = rayTracingProgram;
+ rtpDesc.hitGroupCount = 2;
+ HitGroupDesc hitGroups[2];
+ hitGroups[0].closestHitEntryPoint = "closestHitShaderA";
+ hitGroups[0].hitGroupName = hitgroupNames[0];
+ hitGroups[1].closestHitEntryPoint = "closestHitShaderB";
+ hitGroups[1].hitGroupName = hitgroupNames[1];
+ rtpDesc.hitGroups = hitGroups;
+ rtpDesc.maxRayPayloadSize = 64;
+ rtpDesc.maxRecursion = 2;
+ GFX_CHECK_CALL_ABORT(
+ device->createRayTracingPipelineState(rtpDesc, renderPipelineState.writeRef()));
+ SLANG_CHECK_ABORT(renderPipelineState != nullptr);
+
+ const char* raygenNames[] = {"rayGenShaderA", "rayGenShaderB"};
+ const char* missNames[] = {"missShaderA", "missShaderB"};
+
+ IShaderTable::Desc shaderTableDesc = {};
+ shaderTableDesc.program = rayTracingProgram;
+ shaderTableDesc.hitGroupCount = 2;
+ shaderTableDesc.hitGroupNames = hitgroupNames;
+ shaderTableDesc.rayGenShaderCount = 2;
+ shaderTableDesc.rayGenShaderEntryPointNames = raygenNames;
+ shaderTableDesc.missShaderCount = 2;
+ shaderTableDesc.missShaderEntryPointNames = missNames;
+ GFX_CHECK_CALL_ABORT(device->createShaderTable(shaderTableDesc, shaderTable.writeRef()));
+ }
- template <typename T>
- void rayTracingTestImpl(IDevice* device, UnitTestContext* context)
+ void checkTestResults(float* expectedResult, uint32_t count)
{
- T test;
- test.init(device, context);
- test.run();
+ ComPtr<ISlangBlob> resultBlob;
+ size_t rowPitch = 0;
+ size_t pixelSize = 0;
+ auto cmdBuffer = transientHeap->createCommandBuffer();
+ auto encoder = cmdBuffer->encodeResourceCommands();
+ encoder->textureBarrier(
+ resultTexture.get(),
+ ResourceState::UnorderedAccess,
+ ResourceState::CopySource);
+ encoder->endEncoding();
+ cmdBuffer->close();
+ queue->executeCommandBuffer(cmdBuffer.get());
+ queue->waitOnHost();
+
+ GFX_CHECK_CALL_ABORT(device->readTextureResource(
+ resultTexture,
+ ResourceState::CopySource,
+ resultBlob.writeRef(),
+ &rowPitch,
+ &pixelSize));
+#if 0 // for debugging only
+ writeImage("test.hdr", resultBlob, width, height, (uint32_t)rowPitch, (uint32_t)pixelSize);
+#endif
+ auto buffer = removePadding(resultBlob, width, height, rowPitch, pixelSize);
+ auto actualData = (float*)buffer.getBuffer();
+ SLANG_CHECK(memcmp(actualData, expectedResult, count * sizeof(float)) == 0)
}
+};
- SLANG_UNIT_TEST(RayTracingTestAD3D12)
+struct RayTracingTestA : BaseRayTracingTest
+{
+ void renderFrame()
{
- runTestImpl(rayTracingTestImpl<RayTracingTestA>, unitTestContext, Slang::RenderApiFlag::D3D12);
+ ComPtr<ICommandBuffer> renderCommandBuffer = transientHeap->createCommandBuffer();
+ auto renderEncoder = renderCommandBuffer->encodeRayTracingCommands();
+ IShaderObject* rootObject = nullptr;
+ renderEncoder->bindPipeline(renderPipelineState, &rootObject);
+ auto cursor = ShaderCursor(rootObject);
+ cursor["resultTexture"].setResource(resultTextureUAV);
+ cursor["sceneBVH"].setResource(TLAS);
+ renderEncoder->dispatchRays(0, shaderTable, width, height, 1);
+ renderEncoder->endEncoding();
+ renderCommandBuffer->close();
+ queue->executeCommandBuffer(renderCommandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(RayTracingTestAVulkan)
+ void run()
{
- runTestImpl(rayTracingTestImpl<RayTracingTestA>, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ createRequiredResources();
+ renderFrame();
+
+ float expectedResult[16] = {1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1};
+ checkTestResults(expectedResult, 16);
}
+};
- SLANG_UNIT_TEST(RayTracingTestBD3D12)
+struct RayTracingTestB : BaseRayTracingTest
+{
+ void renderFrame()
{
- runTestImpl(rayTracingTestImpl<RayTracingTestB>, unitTestContext, Slang::RenderApiFlag::D3D12);
+ ComPtr<ICommandBuffer> renderCommandBuffer = transientHeap->createCommandBuffer();
+ auto renderEncoder = renderCommandBuffer->encodeRayTracingCommands();
+ IShaderObject* rootObject = nullptr;
+ renderEncoder->bindPipeline(renderPipelineState, &rootObject);
+ auto cursor = ShaderCursor(rootObject);
+ cursor["resultTexture"].setResource(resultTextureUAV);
+ cursor["sceneBVH"].setResource(TLAS);
+ renderEncoder->dispatchRays(1, shaderTable, width, height, 1);
+ renderEncoder->endEncoding();
+ renderCommandBuffer->close();
+ queue->executeCommandBuffer(renderCommandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(RayTracingTestBVulkan)
+ void run()
{
- runTestImpl(rayTracingTestImpl<RayTracingTestB>, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ createRequiredResources();
+ renderFrame();
+
+ float expectedResult[16] = {0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1};
+ checkTestResults(expectedResult, 16);
}
+};
+
+template<typename T>
+void rayTracingTestImpl(IDevice* device, UnitTestContext* context)
+{
+ T test;
+ test.init(device, context);
+ test.run();
+}
+
+SLANG_UNIT_TEST(RayTracingTestAD3D12)
+{
+ runTestImpl(rayTracingTestImpl<RayTracingTestA>, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(RayTracingTestAVulkan)
+{
+ runTestImpl(rayTracingTestImpl<RayTracingTestA>, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(RayTracingTestBD3D12)
+{
+ runTestImpl(rayTracingTestImpl<RayTracingTestB>, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(RayTracingTestBVulkan)
+{
+ runTestImpl(rayTracingTestImpl<RayTracingTestB>, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/resolve-resource-tests.cpp b/tools/gfx-unit-test/resolve-resource-tests.cpp
index af2bf68e9..ea25b609f 100644
--- a/tools/gfx-unit-test/resolve-resource-tests.cpp
+++ b/tools/gfx-unit-test/resolve-resource-tests.cpp
@@ -1,9 +1,8 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
@@ -14,320 +13,356 @@ using namespace gfx;
namespace
{
- using namespace gfx_test;
+using namespace gfx_test;
- struct Vertex
- {
- float position[3];
- float color[3];
- };
+struct Vertex
+{
+ float position[3];
+ float color[3];
+};
+
+static const int kVertexCount = 12;
+static const Vertex kVertexData[kVertexCount] = {
+ // Triangle 1
+ {{0, 0, 0.5}, {1, 0, 0}},
+ {{1, 1, 0.5}, {1, 0, 0}},
+ {{-1, 1, 0.5}, {1, 0, 0}},
+
+ // Triangle 2
+ {{-1, 1, 0.5}, {0, 1, 0}},
+ {{0, 0, 0.5}, {0, 1, 0}},
+ {{-1, -1, 0.5}, {0, 1, 0}},
+
+ // Triangle 3
+ {{-1, -1, 0.5}, {0, 0, 1}},
+ {{0, 0, 0.5}, {0, 0, 1}},
+ {{1, -1, 0.5}, {0, 0, 1}},
+
+ // Triangle 4
+ {{1, -1, 0.5}, {0, 0, 0}},
+ {{0, 0, 0.5}, {0, 0, 0}},
+ {{1, 1, 0.5}, {0, 0, 0}},
+};
+
+const int kWidth = 256;
+const int kHeight = 256;
+Format format = Format::R32G32B32A32_FLOAT;
+
+ComPtr<IBufferResource> createVertexBuffer(IDevice* device)
+{
+ IBufferResource::Desc vertexBufferDesc;
+ vertexBufferDesc.type = IResource::Type::Buffer;
+ vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
+ vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
+ vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
+ ComPtr<IBufferResource> vertexBuffer =
+ device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
+ SLANG_CHECK_ABORT(vertexBuffer != nullptr);
+ return vertexBuffer;
+}
+
+struct BaseResolveResourceTest
+{
+ IDevice* device;
+ UnitTestContext* context;
+
+ ComPtr<ITextureResource> msaaTexture;
+ ComPtr<ITextureResource> dstTexture;
+
+ ComPtr<ITransientResourceHeap> transientHeap;
+ ComPtr<IPipelineState> pipelineState;
+ ComPtr<IRenderPassLayout> renderPass;
+ ComPtr<IFramebuffer> framebuffer;
+
+ ComPtr<IBufferResource> vertexBuffer;
- static const int kVertexCount = 12;
- static const Vertex kVertexData[kVertexCount] =
+ struct TextureInfo
{
- // Triangle 1
- { { 0, 0, 0.5 }, { 1, 0, 0 } },
- { { 1, 1, 0.5 }, { 1, 0, 0 } },
- { { -1, 1, 0.5 }, { 1, 0, 0 } },
-
- // Triangle 2
- { { -1, 1, 0.5 }, { 0, 1, 0 } },
- { { 0, 0, 0.5 }, { 0, 1, 0 } },
- { { -1, -1, 0.5 }, { 0, 1, 0 } },
-
- // Triangle 3
- { { -1, -1, 0.5 }, { 0, 0, 1 } },
- { { 0, 0, 0.5 }, { 0, 0, 1 } },
- { { 1, -1, 0.5 }, { 0, 0, 1 } },
-
- // Triangle 4
- { { 1, -1, 0.5 }, { 0, 0, 0 } },
- { { 0, 0, 0.5 }, { 0, 0, 0 } },
- { { 1, 1, 0.5 }, { 0, 0, 0 } },
+ ITextureResource::Extents extent;
+ int numMipLevels;
+ int arraySize;
+ ITextureResource::SubresourceData const* initData;
};
- const int kWidth = 256;
- const int kHeight = 256;
- Format format = Format::R32G32B32A32_FLOAT;
-
- ComPtr<IBufferResource> createVertexBuffer(IDevice* device)
+ void init(IDevice* device, UnitTestContext* context)
{
- IBufferResource::Desc vertexBufferDesc;
- vertexBufferDesc.type = IResource::Type::Buffer;
- vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
- vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
- vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
- ComPtr<IBufferResource> vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
- SLANG_CHECK_ABORT(vertexBuffer != nullptr);
- return vertexBuffer;
+ this->device = device;
+ this->context = context;
}
- struct BaseResolveResourceTest
+ void createRequiredResources(
+ TextureInfo msaaTextureInfo,
+ TextureInfo dstTextureInfo,
+ Format format)
{
- IDevice* device;
- UnitTestContext* context;
-
- ComPtr<ITextureResource> msaaTexture;
- ComPtr<ITextureResource> dstTexture;
-
- ComPtr<ITransientResourceHeap> transientHeap;
- ComPtr<IPipelineState> pipelineState;
- ComPtr<IRenderPassLayout> renderPass;
- ComPtr<IFramebuffer> framebuffer;
-
- ComPtr<IBufferResource> vertexBuffer;
-
- struct TextureInfo
- {
- ITextureResource::Extents extent;
- int numMipLevels;
- int arraySize;
- ITextureResource::SubresourceData const* initData;
+ VertexStreamDesc vertexStreams[] = {
+ {sizeof(Vertex), InputSlotClass::PerVertex, 0},
};
- void init(IDevice* device, UnitTestContext* context)
- {
- this->device = device;
- this->context = context;
- }
+ InputElementDesc inputElements[] = {
+ // Vertex buffer data
+ {"POSITION", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0},
+ {"COLOR", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, color), 0},
+ };
- void createRequiredResources(TextureInfo msaaTextureInfo, TextureInfo dstTextureInfo, Format format)
- {
- VertexStreamDesc vertexStreams[] = {
- { sizeof(Vertex), InputSlotClass::PerVertex, 0 },
- };
-
- InputElementDesc inputElements[] = {
- // Vertex buffer data
- { "POSITION", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0 },
- { "COLOR", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, color), 0 },
- };
-
- ITextureResource::Desc msaaTexDesc = {};
- msaaTexDesc.type = IResource::Type::Texture2D;
- msaaTexDesc.numMipLevels = dstTextureInfo.numMipLevels;
- msaaTexDesc.arraySize = dstTextureInfo.arraySize;
- msaaTexDesc.size = dstTextureInfo.extent;
- msaaTexDesc.defaultState = ResourceState::RenderTarget;
- msaaTexDesc.allowedStates = ResourceStateSet(
- ResourceState::RenderTarget,
- ResourceState::ResolveSource);
- msaaTexDesc.format = format;
- msaaTexDesc.sampleDesc.numSamples = 4;
-
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- msaaTexDesc,
- msaaTextureInfo.initData,
- msaaTexture.writeRef()));
-
- ITextureResource::Desc dstTexDesc = {};
- dstTexDesc.type = IResource::Type::Texture2D;
- dstTexDesc.numMipLevels = dstTextureInfo.numMipLevels;
- dstTexDesc.arraySize = dstTextureInfo.arraySize;
- dstTexDesc.size = dstTextureInfo.extent;
- dstTexDesc.defaultState = ResourceState::ResolveDestination;
- dstTexDesc.allowedStates = ResourceStateSet(
- ResourceState::ResolveDestination,
- ResourceState::CopySource);
- dstTexDesc.format = format;
-
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- dstTexDesc,
- dstTextureInfo.initData,
- dstTexture.writeRef()));
-
- IInputLayout::Desc inputLayoutDesc = {};
- inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
- inputLayoutDesc.inputElements = inputElements;
- inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
- inputLayoutDesc.vertexStreams = vertexStreams;
- auto inputLayout = device->createInputLayout(inputLayoutDesc);
- SLANG_CHECK_ABORT(inputLayout != nullptr);
-
- vertexBuffer = createVertexBuffer(device);
-
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadGraphicsProgram(device, shaderProgram, "resolve-resource-shader", "vertexMain", "fragmentMain", slangReflection));
-
- IFramebufferLayout::TargetLayout targetLayout;
- targetLayout.format = format;
- targetLayout.sampleCount = 4;
-
- IFramebufferLayout::Desc framebufferLayoutDesc;
- framebufferLayoutDesc.renderTargetCount = 1;
- framebufferLayoutDesc.renderTargets = &targetLayout;
- ComPtr<gfx::IFramebufferLayout> framebufferLayout = device->createFramebufferLayout(framebufferLayoutDesc);
- SLANG_CHECK_ABORT(framebufferLayout != nullptr);
-
- GraphicsPipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- pipelineDesc.inputLayout = inputLayout;
- pipelineDesc.framebufferLayout = framebufferLayout;
- pipelineDesc.depthStencil.depthTestEnable = false;
- pipelineDesc.depthStencil.depthWriteEnable = false;
- GFX_CHECK_CALL_ABORT(
- device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
-
- IRenderPassLayout::Desc renderPassDesc = {};
- renderPassDesc.framebufferLayout = framebufferLayout;
- renderPassDesc.renderTargetCount = 1;
- IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
- renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
- renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
- renderTargetAccess.initialState = ResourceState::RenderTarget;
- renderTargetAccess.finalState = ResourceState::ResolveSource;
- renderPassDesc.renderTargetAccess = &renderTargetAccess;
- GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
-
- gfx::IResourceView::Desc colorBufferViewDesc;
- memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
- colorBufferViewDesc.format = format;
- colorBufferViewDesc.renderTarget.shape = gfx::IResource::Type::Texture2D;
- colorBufferViewDesc.type = gfx::IResourceView::Type::RenderTarget;
- auto rtv = device->createTextureView(msaaTexture, colorBufferViewDesc);
-
- gfx::IFramebuffer::Desc framebufferDesc;
- framebufferDesc.renderTargetCount = 1;
- framebufferDesc.depthStencilView = nullptr;
- framebufferDesc.renderTargetViews = rtv.readRef();
- framebufferDesc.layout = framebufferLayout;
- GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
- }
+ ITextureResource::Desc msaaTexDesc = {};
+ msaaTexDesc.type = IResource::Type::Texture2D;
+ msaaTexDesc.numMipLevels = dstTextureInfo.numMipLevels;
+ msaaTexDesc.arraySize = dstTextureInfo.arraySize;
+ msaaTexDesc.size = dstTextureInfo.extent;
+ msaaTexDesc.defaultState = ResourceState::RenderTarget;
+ msaaTexDesc.allowedStates =
+ ResourceStateSet(ResourceState::RenderTarget, ResourceState::ResolveSource);
+ msaaTexDesc.format = format;
+ msaaTexDesc.sampleDesc.numSamples = 4;
+
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(
+ msaaTexDesc,
+ msaaTextureInfo.initData,
+ msaaTexture.writeRef()));
+
+ ITextureResource::Desc dstTexDesc = {};
+ dstTexDesc.type = IResource::Type::Texture2D;
+ dstTexDesc.numMipLevels = dstTextureInfo.numMipLevels;
+ dstTexDesc.arraySize = dstTextureInfo.arraySize;
+ dstTexDesc.size = dstTextureInfo.extent;
+ dstTexDesc.defaultState = ResourceState::ResolveDestination;
+ dstTexDesc.allowedStates =
+ ResourceStateSet(ResourceState::ResolveDestination, ResourceState::CopySource);
+ dstTexDesc.format = format;
+
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(
+ dstTexDesc,
+ dstTextureInfo.initData,
+ dstTexture.writeRef()));
+
+ IInputLayout::Desc inputLayoutDesc = {};
+ inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
+ inputLayoutDesc.inputElements = inputElements;
+ inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
+ inputLayoutDesc.vertexStreams = vertexStreams;
+ auto inputLayout = device->createInputLayout(inputLayoutDesc);
+ SLANG_CHECK_ABORT(inputLayout != nullptr);
+
+ vertexBuffer = createVertexBuffer(device);
+
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadGraphicsProgram(
+ device,
+ shaderProgram,
+ "resolve-resource-shader",
+ "vertexMain",
+ "fragmentMain",
+ slangReflection));
+
+ IFramebufferLayout::TargetLayout targetLayout;
+ targetLayout.format = format;
+ targetLayout.sampleCount = 4;
+
+ IFramebufferLayout::Desc framebufferLayoutDesc;
+ framebufferLayoutDesc.renderTargetCount = 1;
+ framebufferLayoutDesc.renderTargets = &targetLayout;
+ ComPtr<gfx::IFramebufferLayout> framebufferLayout =
+ device->createFramebufferLayout(framebufferLayoutDesc);
+ SLANG_CHECK_ABORT(framebufferLayout != nullptr);
+
+ GraphicsPipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ pipelineDesc.inputLayout = inputLayout;
+ pipelineDesc.framebufferLayout = framebufferLayout;
+ pipelineDesc.depthStencil.depthTestEnable = false;
+ pipelineDesc.depthStencil.depthWriteEnable = false;
+ GFX_CHECK_CALL_ABORT(
+ device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ IRenderPassLayout::Desc renderPassDesc = {};
+ renderPassDesc.framebufferLayout = framebufferLayout;
+ renderPassDesc.renderTargetCount = 1;
+ IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
+ renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
+ renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
+ renderTargetAccess.initialState = ResourceState::RenderTarget;
+ renderTargetAccess.finalState = ResourceState::ResolveSource;
+ renderPassDesc.renderTargetAccess = &renderTargetAccess;
+ GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
+
+ gfx::IResourceView::Desc colorBufferViewDesc;
+ memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
+ colorBufferViewDesc.format = format;
+ colorBufferViewDesc.renderTarget.shape = gfx::IResource::Type::Texture2D;
+ colorBufferViewDesc.type = gfx::IResourceView::Type::RenderTarget;
+ auto rtv = device->createTextureView(msaaTexture, colorBufferViewDesc);
+
+ gfx::IFramebuffer::Desc framebufferDesc;
+ framebufferDesc.renderTargetCount = 1;
+ framebufferDesc.depthStencilView = nullptr;
+ framebufferDesc.renderTargetViews = rtv.readRef();
+ framebufferDesc.layout = framebufferLayout;
+ GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
+ }
- void submitGPUWork(SubresourceRange msaaSubresource, SubresourceRange dstSubresource, ITextureResource::Extents extent)
- {
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto renderEncoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
- auto rootObject = renderEncoder->bindPipeline(pipelineState);
-
- gfx::Viewport viewport = {};
- viewport.maxZ = 1.0f;
- viewport.extentX = kWidth;
- viewport.extentY = kHeight;
- renderEncoder->setViewportAndScissor(viewport);
-
- renderEncoder->setVertexBuffer(0, vertexBuffer);
- renderEncoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
- renderEncoder->draw(kVertexCount, 0);
- renderEncoder->endEncoding();
-
- auto resourceEncoder = commandBuffer->encodeResourceCommands();
-
- resourceEncoder->resolveResource(msaaTexture, ResourceState::ResolveSource, msaaSubresource, dstTexture, ResourceState::ResolveDestination, dstSubresource);
- resourceEncoder->textureSubresourceBarrier(dstTexture, dstSubresource, ResourceState::ResolveDestination, ResourceState::CopySource);
- resourceEncoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ void submitGPUWork(
+ SubresourceRange msaaSubresource,
+ SubresourceRange dstSubresource,
+ ITextureResource::Extents extent)
+ {
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto renderEncoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
+ auto rootObject = renderEncoder->bindPipeline(pipelineState);
+
+ gfx::Viewport viewport = {};
+ viewport.maxZ = 1.0f;
+ viewport.extentX = kWidth;
+ viewport.extentY = kHeight;
+ renderEncoder->setViewportAndScissor(viewport);
+
+ renderEncoder->setVertexBuffer(0, vertexBuffer);
+ renderEncoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
+ renderEncoder->draw(kVertexCount, 0);
+ renderEncoder->endEncoding();
+
+ auto resourceEncoder = commandBuffer->encodeResourceCommands();
+
+ resourceEncoder->resolveResource(
+ msaaTexture,
+ ResourceState::ResolveSource,
+ msaaSubresource,
+ dstTexture,
+ ResourceState::ResolveDestination,
+ dstSubresource);
+ resourceEncoder->textureSubresourceBarrier(
+ dstTexture,
+ dstSubresource,
+ ResourceState::ResolveDestination,
+ ResourceState::CopySource);
+ resourceEncoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- void checkTestResults(int pixelCount, int channelCount, const int* testXCoords, const int* testYCoords, float* testResults)
+ void checkTestResults(
+ int pixelCount,
+ int channelCount,
+ const int* testXCoords,
+ const int* testYCoords,
+ float* testResults)
+ {
+ // Read texture values back from four specific pixels located within the triangles
+ // and compare against expected values (because testing every single pixel will be too long
+ // and tedious and requires maintaining reference images).
+ ComPtr<ISlangBlob> resultBlob;
+ size_t rowPitch = 0;
+ size_t pixelSize = 0;
+ GFX_CHECK_CALL_ABORT(device->readTextureResource(
+ dstTexture,
+ ResourceState::CopySource,
+ resultBlob.writeRef(),
+ &rowPitch,
+ &pixelSize));
+ auto result = (float*)resultBlob->getBufferPointer();
+
+ int cursor = 0;
+ for (int i = 0; i < pixelCount; ++i)
{
- // Read texture values back from four specific pixels located within the triangles
- // and compare against expected values (because testing every single pixel will be too long and tedious
- // and requires maintaining reference images).
- ComPtr<ISlangBlob> resultBlob;
- size_t rowPitch = 0;
- size_t pixelSize = 0;
- GFX_CHECK_CALL_ABORT(device->readTextureResource(
- dstTexture, ResourceState::CopySource, resultBlob.writeRef(), &rowPitch, &pixelSize));
- auto result = (float*)resultBlob->getBufferPointer();
-
- int cursor = 0;
- for (int i = 0; i < pixelCount; ++i)
+ auto x = testXCoords[i];
+ auto y = testYCoords[i];
+ auto pixelPtr = result + x * channelCount + y * rowPitch / sizeof(float);
+ for (int j = 0; j < channelCount; ++j)
{
- auto x = testXCoords[i];
- auto y = testYCoords[i];
- auto pixelPtr = result + x * channelCount + y * rowPitch / sizeof(float);
- for (int j = 0; j < channelCount; ++j)
- {
- testResults[cursor] = pixelPtr[j];
- cursor++;
- }
+ testResults[cursor] = pixelPtr[j];
+ cursor++;
}
-
- float expectedResult[] = { 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 0.0f, 1.0f,
- 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
- 0.0f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.5f, 1.0f };
- SLANG_CHECK(memcmp(testResults, expectedResult, 128) == 0);
}
- };
- // TODO: Add more tests?
+ float expectedResult[] = {0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 0.0f,
+ 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f,
+ 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.5f, 1.0f};
+ SLANG_CHECK(memcmp(testResults, expectedResult, 128) == 0);
+ }
+};
- struct ResolveResourceSimple : BaseResolveResourceTest
- {
- void run()
- {
- ITextureResource::Extents extent = {};
- extent.width = kWidth;
- extent.height = kHeight;
- extent.depth = 1;
-
- TextureInfo msaaTextureInfo = { extent, 1, 1, nullptr };
- TextureInfo dstTextureInfo = { extent, 1, 1, nullptr };
-
- createRequiredResources(msaaTextureInfo, dstTextureInfo, format);
-
- SubresourceRange msaaSubresource = {};
- msaaSubresource.aspectMask = TextureAspect::Color;
- msaaSubresource.mipLevel = 0;
- msaaSubresource.mipLevelCount = 1;
- msaaSubresource.baseArrayLayer = 0;
- msaaSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = TextureAspect::Color;
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- submitGPUWork(msaaSubresource, dstSubresource, extent);
-
- const int kPixelCount = 8;
- const int kChannelCount = 4;
- int testXCoords[kPixelCount] = { 64, 127, 191, 64, 191, 64, 127, 191 };
- int testYCoords[kPixelCount] = { 64, 64, 64, 127, 127, 191, 191, 191 };
- float testResults[kPixelCount * kChannelCount];
-
- checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
- }
- };
+// TODO: Add more tests?
- template<typename T>
- void resolveResourceTestImpl(IDevice* device, UnitTestContext* context)
+struct ResolveResourceSimple : BaseResolveResourceTest
+{
+ void run()
{
- T test;
- test.init(device, context);
- test.run();
+ ITextureResource::Extents extent = {};
+ extent.width = kWidth;
+ extent.height = kHeight;
+ extent.depth = 1;
+
+ TextureInfo msaaTextureInfo = {extent, 1, 1, nullptr};
+ TextureInfo dstTextureInfo = {extent, 1, 1, nullptr};
+
+ createRequiredResources(msaaTextureInfo, dstTextureInfo, format);
+
+ SubresourceRange msaaSubresource = {};
+ msaaSubresource.aspectMask = TextureAspect::Color;
+ msaaSubresource.mipLevel = 0;
+ msaaSubresource.mipLevelCount = 1;
+ msaaSubresource.baseArrayLayer = 0;
+ msaaSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = TextureAspect::Color;
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ submitGPUWork(msaaSubresource, dstSubresource, extent);
+
+ const int kPixelCount = 8;
+ const int kChannelCount = 4;
+ int testXCoords[kPixelCount] = {64, 127, 191, 64, 191, 64, 127, 191};
+ int testYCoords[kPixelCount] = {64, 64, 64, 127, 127, 191, 191, 191};
+ float testResults[kPixelCount * kChannelCount];
+
+ checkTestResults(kPixelCount, kChannelCount, testXCoords, testYCoords, testResults);
}
+};
+
+template<typename T>
+void resolveResourceTestImpl(IDevice* device, UnitTestContext* context)
+{
+ T test;
+ test.init(device, context);
+ test.run();
}
+} // namespace
namespace gfx_test
{
- SLANG_UNIT_TEST(resolveResourceSimpleD3D12)
- {
- runTestImpl(resolveResourceTestImpl<ResolveResourceSimple>, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+SLANG_UNIT_TEST(resolveResourceSimpleD3D12)
+{
+ runTestImpl(
+ resolveResourceTestImpl<ResolveResourceSimple>,
+ unitTestContext,
+ Slang::RenderApiFlag::D3D12);
+}
- SLANG_UNIT_TEST(resolveResourceSimpleVulkan)
- {
- runTestImpl(resolveResourceTestImpl<ResolveResourceSimple>, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(resolveResourceSimpleVulkan)
+{
+ runTestImpl(
+ resolveResourceTestImpl<ResolveResourceSimple>,
+ unitTestContext,
+ Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/root-mutable-shader-object.cpp b/tools/gfx-unit-test/root-mutable-shader-object.cpp
index 1d489786e..fce4cc0da 100644
--- a/tools/gfx-unit-test/root-mutable-shader-object.cpp
+++ b/tools/gfx-unit-test/root-mutable-shader-object.cpp
@@ -1,119 +1,123 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void mutableRootShaderObjectTestImpl(IDevice* device, UnitTestContext* context)
+void mutableRootShaderObjectTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "mutable-shader-object",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ float initialData[] = {0.0f, 1.0f, 2.0f, 3.0f};
+ const int numberCount = SLANG_COUNT_OF(initialData);
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = sizeof(initialData);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ ComPtr<IShaderObject> rootObject;
+ device->createMutableRootShaderObject(shaderProgram, rootObject.writeRef());
+ auto entryPointCursor = ShaderCursor(rootObject->getEntryPoint(0));
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+
+ slang::TypeReflection* addTransformerType = slangReflection->findTypeByName("AddTransformer");
+ ComPtr<IShaderObject> transformer;
+ GFX_CHECK_CALL_ABORT(device->createMutableShaderObject(
+ addTransformerType,
+ ShaderObjectContainerType::None,
+ transformer.writeRef()));
+ entryPointCursor.getPath("transformer").setObject(transformer);
+
+ // Set the `c` field of the `AddTransformer`.
+ float c = 1.0f;
+ ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
+
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "mutable-shader-object", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- float initialData[] = { 0.0f, 1.0f, 2.0f, 3.0f };
- const int numberCount = SLANG_COUNT_OF(initialData);
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = sizeof(initialData);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ {
+ auto encoder = commandBuffer->encodeComputeCommands();
+ encoder->bindPipelineWithRootObject(pipelineState, rootObject);
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ }
+
+ auto barrierEncoder = commandBuffer->encodeResourceCommands();
+ barrierEncoder->bufferBarrier(
+ 1,
+ numbersBuffer.readRef(),
ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- ComPtr<IShaderObject> rootObject;
- device->createMutableRootShaderObject(shaderProgram, rootObject.writeRef());
- auto entryPointCursor = ShaderCursor(rootObject->getEntryPoint(0));
- entryPointCursor.getPath("buffer").setResource(bufferView);
-
- slang::TypeReflection* addTransformerType =
- slangReflection->findTypeByName("AddTransformer");
- ComPtr<IShaderObject> transformer;
- GFX_CHECK_CALL_ABORT(device->createMutableShaderObject(
- addTransformerType, ShaderObjectContainerType::None, transformer.writeRef()));
- entryPointCursor.getPath("transformer").setObject(transformer);
-
- // Set the `c` field of the `AddTransformer`.
- float c = 1.0f;
- ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
+ ResourceState::UnorderedAccess);
+ barrierEncoder->endEncoding();
+ // Mutate `transformer` object and run again.
+ c = 2.0f;
+ ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
{
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- {
- auto encoder = commandBuffer->encodeComputeCommands();
- encoder->bindPipelineWithRootObject(pipelineState, rootObject);
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- }
-
- auto barrierEncoder = commandBuffer->encodeResourceCommands();
- barrierEncoder->bufferBarrier(1, numbersBuffer.readRef(), ResourceState::UnorderedAccess, ResourceState::UnorderedAccess);
- barrierEncoder->endEncoding();
-
- // Mutate `transformer` object and run again.
- c = 2.0f;
- ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
- {
- auto encoder = commandBuffer->encodeComputeCommands();
- encoder->bindPipelineWithRootObject(pipelineState, rootObject);
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- }
-
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
+ auto encoder = commandBuffer->encodeComputeCommands();
+ encoder->bindPipelineWithRootObject(pipelineState, rootObject);
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
}
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<float>(3.0f, 4.0f, 5.0f, 6.0f));
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(mutableRootShaderObjectD3D12)
- {
- runTestImpl(mutableRootShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<float>(3.0f, 4.0f, 5.0f, 6.0f));
+}
- /*SLANG_UNIT_TEST(mutableRootShaderObjectVulkan)
- {
- runTestImpl(mutableRootShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }*/
+SLANG_UNIT_TEST(mutableRootShaderObjectD3D12)
+{
+ runTestImpl(mutableRootShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
}
+
+/*SLANG_UNIT_TEST(mutableRootShaderObjectVulkan)
+{
+ runTestImpl(mutableRootShaderObjectTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}*/
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/root-shader-parameter.cpp b/tools/gfx-unit-test/root-shader-parameter.cpp
index 1a7be91c4..f933ec48a 100644
--- a/tools/gfx-unit-test/root-shader-parameter.cpp
+++ b/tools/gfx-unit-test/root-shader-parameter.cpp
@@ -1,139 +1,151 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- static ComPtr<IBufferResource> createBuffer(IDevice* device, uint32_t content)
+static ComPtr<IBufferResource> createBuffer(IDevice* device, uint32_t content)
+{
+ ComPtr<IBufferResource> buffer;
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = sizeof(uint32_t);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)&content, buffer.writeRef()));
+
+ return buffer;
+}
+void rootShaderParameterTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "root-shader-parameter",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ Slang::List<ComPtr<IBufferResource>> buffers;
+ Slang::List<ComPtr<IResourceView>> srvs, uavs;
+
+ for (uint32_t i = 0; i < 9; i++)
{
- ComPtr<IBufferResource> buffer;
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = sizeof(uint32_t);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(
- device->createBufferResource(bufferDesc, (void*)&content, buffer.writeRef()));
+ buffers.add(createBuffer(device, i == 0 ? 10 : i));
- return buffer;
- }
- void rootShaderParameterTestImpl(IDevice* device, UnitTestContext* context)
- {
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "root-shader-parameter", "computeMain", slangReflection));
+ device->createBufferView(buffers[i], nullptr, viewDesc, bufferView.writeRef()));
+ uavs.add(bufferView);
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
+ viewDesc.type = IResourceView::Type::ShaderResource;
+ viewDesc.format = Format::Unknown;
GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- Slang::List<ComPtr<IBufferResource>> buffers;
- Slang::List<ComPtr<IResourceView>> srvs, uavs;
-
- for (uint32_t i = 0; i < 9; i++)
- {
- buffers.add(createBuffer(device, i == 0 ? 10 : i));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(buffers[i], nullptr, viewDesc, bufferView.writeRef()));
- uavs.add(bufferView);
-
- viewDesc.type = IResourceView::Type::ShaderResource;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(buffers[i], nullptr, viewDesc, bufferView.writeRef()));
- srvs.add(bufferView);
- }
+ device->createBufferView(buffers[i], nullptr, viewDesc, bufferView.writeRef()));
+ srvs.add(bufferView);
+ }
- ComPtr<IShaderObject> rootObject;
- device->createMutableRootShaderObject(shaderProgram, rootObject.writeRef());
+ ComPtr<IShaderObject> rootObject;
+ device->createMutableRootShaderObject(shaderProgram, rootObject.writeRef());
+
+ ComPtr<IShaderObject> g, s1, s2;
+ device->createMutableShaderObject(
+ slangReflection->findTypeByName("S0"),
+ ShaderObjectContainerType::None,
+ g.writeRef());
+ device->createMutableShaderObject(
+ slangReflection->findTypeByName("S1"),
+ ShaderObjectContainerType::None,
+ s1.writeRef());
+ device->createMutableShaderObject(
+ slangReflection->findTypeByName("S1"),
+ ShaderObjectContainerType::None,
+ s2.writeRef());
- ComPtr<IShaderObject> g, s1, s2;
- device->createMutableShaderObject(
- slangReflection->findTypeByName("S0"), ShaderObjectContainerType::None, g.writeRef());
- device->createMutableShaderObject(
- slangReflection->findTypeByName("S1"), ShaderObjectContainerType::None, s1.writeRef());
- device->createMutableShaderObject(
- slangReflection->findTypeByName("S1"), ShaderObjectContainerType::None, s2.writeRef());
+ {
+ auto cursor = ShaderCursor(s1);
+ cursor["c0"].setResource(srvs[2]);
+ cursor["c1"].setResource(uavs[3]);
+ cursor["c2"].setResource(srvs[4]);
+ }
+ {
+ auto cursor = ShaderCursor(s2);
+ cursor["c0"].setResource(srvs[5]);
+ cursor["c1"].setResource(uavs[6]);
+ cursor["c2"].setResource(srvs[7]);
+ }
+ {
+ auto cursor = ShaderCursor(g);
+ cursor["b0"].setResource(srvs[0]);
+ cursor["b1"].setResource(srvs[1]);
+ cursor["s1"].setObject(s1);
+ cursor["s2"].setObject(s2);
+ }
+ {
+ auto cursor = ShaderCursor(rootObject);
+ cursor["g"].setObject(g);
+ cursor["buffer"].setResource(uavs[8]);
+ }
- {
- auto cursor = ShaderCursor(s1);
- cursor["c0"].setResource(srvs[2]);
- cursor["c1"].setResource(uavs[3]);
- cursor["c2"].setResource(srvs[4]);
- }
- {
- auto cursor = ShaderCursor(s2);
- cursor["c0"].setResource(srvs[5]);
- cursor["c1"].setResource(uavs[6]);
- cursor["c2"].setResource(srvs[7]);
- }
- {
- auto cursor = ShaderCursor(g);
- cursor["b0"].setResource(srvs[0]);
- cursor["b1"].setResource(srvs[1]);
- cursor["s1"].setObject(s1);
- cursor["s2"].setObject(s2);
- }
- {
- auto cursor = ShaderCursor(rootObject);
- cursor["g"].setObject(g);
- cursor["buffer"].setResource(uavs[8]);
- }
+ {
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+ auto commandBuffer = transientHeap->createCommandBuffer();
{
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- {
- auto encoder = commandBuffer->encodeComputeCommands();
- encoder->bindPipelineWithRootObject(pipelineState, rootObject);
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- }
-
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
+ auto encoder = commandBuffer->encodeComputeCommands();
+ encoder->bindPipelineWithRootObject(pipelineState, rootObject);
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
}
- compareComputeResult(
- device, buffers[8], Slang::makeArray<uint32_t>(10 - 1 + 2 - 3 + 4 + 5 - 6 + 7));
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(rootShaderParameterD3D12)
- {
- runTestImpl(rootShaderParameterTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ compareComputeResult(
+ device,
+ buffers[8],
+ Slang::makeArray<uint32_t>(10 - 1 + 2 - 3 + 4 + 5 - 6 + 7));
+}
- SLANG_UNIT_TEST(rootShaderParameterVulkan)
- {
- runTestImpl(rootShaderParameterTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(rootShaderParameterD3D12)
+{
+ runTestImpl(rootShaderParameterTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(rootShaderParameterVulkan)
+{
+ runTestImpl(rootShaderParameterTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/sampler-array.cpp b/tools/gfx-unit-test/sampler-array.cpp
index 945c31b07..720aa0a2c 100644
--- a/tools/gfx-unit-test/sampler-array.cpp
+++ b/tools/gfx-unit-test/sampler-array.cpp
@@ -1,159 +1,160 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- static ComPtr<IBufferResource> createBuffer(IDevice* device, uint32_t content)
- {
- ComPtr<IBufferResource> buffer;
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = sizeof(uint32_t);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(
- device->createBufferResource(bufferDesc, (void*)&content, buffer.writeRef()));
+static ComPtr<IBufferResource> createBuffer(IDevice* device, uint32_t content)
+{
+ ComPtr<IBufferResource> buffer;
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = sizeof(uint32_t);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)&content, buffer.writeRef()));
+
+ return buffer;
+}
+void samplerArrayTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(
+ loadComputeProgram(device, shaderProgram, "sampler-array", "computeMain", slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ Slang::List<ComPtr<ISamplerState>> samplers;
+ Slang::List<ComPtr<IResourceView>> srvs;
+ ComPtr<IResourceView> uav;
+ ComPtr<ITextureResource> texture;
+ ComPtr<IBufferResource> buffer = createBuffer(device, 0);
- return buffer;
+ {
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(device->createBufferView(buffer, nullptr, viewDesc, uav.writeRef()));
}
- void samplerArrayTestImpl(IDevice* device, UnitTestContext* context)
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
+ ITextureResource::Desc textureDesc = {};
+ textureDesc.type = IResource::Type::Texture2D;
+ textureDesc.format = Format::R8G8B8A8_UNORM;
+ textureDesc.size.width = 2;
+ textureDesc.size.height = 2;
+ textureDesc.size.depth = 1;
+ textureDesc.numMipLevels = 2;
+ textureDesc.memoryType = MemoryType::DeviceLocal;
+ textureDesc.defaultState = ResourceState::ShaderResource;
+ textureDesc.allowedStates.add(ResourceState::CopyDestination);
+ uint32_t data[] = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF};
+ ITextureResource::SubresourceData subResourceData[2] = {{data, 8, 16}, {data, 8, 16}};
GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+ device->createTextureResource(textureDesc, subResourceData, texture.writeRef()));
+ }
+ for (uint32_t i = 0; i < 32; i++)
+ {
+ ComPtr<IResourceView> srv;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::ShaderResource;
+ viewDesc.format = Format::R8G8B8A8_UNORM;
+ viewDesc.subresourceRange.layerCount = 1;
+ viewDesc.subresourceRange.mipLevelCount = 1;
+ GFX_CHECK_CALL_ABORT(device->createTextureView(texture, viewDesc, srv.writeRef()));
+ srvs.add(srv);
+ }
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "sampler-array", "computeMain", slangReflection));
+ for (uint32_t i = 0; i < 32; i++)
+ {
+ ISamplerState::Desc desc = {};
+ ComPtr<ISamplerState> sampler;
+ GFX_CHECK_CALL_ABORT(device->createSamplerState(desc, sampler.writeRef()));
+ samplers.add(sampler);
+ }
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+ ComPtr<IShaderObject> rootObject;
+ device->createMutableRootShaderObject(shaderProgram, rootObject.writeRef());
- Slang::List<ComPtr<ISamplerState>> samplers;
- Slang::List<ComPtr<IResourceView>> srvs;
- ComPtr<IResourceView> uav;
- ComPtr<ITextureResource> texture;
- ComPtr<IBufferResource> buffer = createBuffer(device, 0);
+ ComPtr<IShaderObject> g;
+ device->createMutableShaderObject(
+ slangReflection->findTypeByName("S0"),
+ ShaderObjectContainerType::None,
+ g.writeRef());
- {
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(buffer, nullptr, viewDesc, uav.writeRef()));
- }
- {
- ITextureResource::Desc textureDesc = {};
- textureDesc.type = IResource::Type::Texture2D;
- textureDesc.format = Format::R8G8B8A8_UNORM;
- textureDesc.size.width = 2;
- textureDesc.size.height = 2;
- textureDesc.size.depth = 1;
- textureDesc.numMipLevels = 2;
- textureDesc.memoryType = MemoryType::DeviceLocal;
- textureDesc.defaultState = ResourceState::ShaderResource;
- textureDesc.allowedStates.add(ResourceState::CopyDestination);
- uint32_t data[] = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF};
- ITextureResource::SubresourceData subResourceData[2] = {{data, 8, 16}, {data, 8, 16}};
- GFX_CHECK_CALL_ABORT(
- device->createTextureResource(textureDesc, subResourceData, texture.writeRef()));
- }
- for (uint32_t i = 0; i < 32; i++)
- {
- ComPtr<IResourceView> srv;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::ShaderResource;
- viewDesc.format = Format::R8G8B8A8_UNORM;
- viewDesc.subresourceRange.layerCount = 1;
- viewDesc.subresourceRange.mipLevelCount = 1;
- GFX_CHECK_CALL_ABORT(
- device->createTextureView(texture, viewDesc, srv.writeRef()));
- srvs.add(srv);
- }
+ ComPtr<IShaderObject> s1;
+ device->createMutableShaderObject(
+ slangReflection->findTypeByName("S1"),
+ ShaderObjectContainerType::None,
+ s1.writeRef());
+ {
+ auto cursor = ShaderCursor(s1);
for (uint32_t i = 0; i < 32; i++)
{
- ISamplerState::Desc desc = {};
- ComPtr<ISamplerState> sampler;
- GFX_CHECK_CALL_ABORT(device->createSamplerState(desc, sampler.writeRef()));
- samplers.add(sampler);
+ cursor["samplers"][i].setSampler(samplers[i]);
+ cursor["tex"][i].setResource(srvs[i]);
}
+ cursor["data"].setData(1.0f);
+ }
- ComPtr<IShaderObject> rootObject;
- device->createMutableRootShaderObject(shaderProgram, rootObject.writeRef());
-
- ComPtr<IShaderObject> g;
- device->createMutableShaderObject(
- slangReflection->findTypeByName("S0"), ShaderObjectContainerType::None, g.writeRef());
-
- ComPtr<IShaderObject> s1;
- device->createMutableShaderObject(
- slangReflection->findTypeByName("S1"), ShaderObjectContainerType::None, s1.writeRef());
-
- {
- auto cursor = ShaderCursor(s1);
- for (uint32_t i = 0; i < 32; i++)
- {
- cursor["samplers"][i].setSampler(samplers[i]);
- cursor["tex"][i].setResource(srvs[i]);
- }
- cursor["data"].setData(1.0f);
- }
+ {
+ auto cursor = ShaderCursor(g);
+ cursor["s"].setObject(s1);
+ cursor["data"].setData(2.0f);
+ }
- {
- auto cursor = ShaderCursor(g);
- cursor["s"].setObject(s1);
- cursor["data"].setData(2.0f);
- }
+ {
+ auto cursor = ShaderCursor(rootObject);
+ cursor["g"].setObject(g);
+ cursor["buffer"].setResource(uav);
+ }
- {
- auto cursor = ShaderCursor(rootObject);
- cursor["g"].setObject(g);
- cursor["buffer"].setResource(uav);
- }
+ {
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+ auto commandBuffer = transientHeap->createCommandBuffer();
{
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- {
- auto encoder = commandBuffer->encodeComputeCommands();
- encoder->bindPipelineWithRootObject(pipelineState, rootObject);
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- }
-
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
+ auto encoder = commandBuffer->encodeComputeCommands();
+ encoder->bindPipelineWithRootObject(pipelineState, rootObject);
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
}
- compareComputeResult(
- device, buffer, Slang::makeArray<float>(4.0f));
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(samplerArrayVulkan)
- {
- runTestImpl(samplerArrayTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+ compareComputeResult(device, buffer, Slang::makeArray<float>(4.0f));
+}
+
+SLANG_UNIT_TEST(samplerArrayVulkan)
+{
+ runTestImpl(samplerArrayTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/shader-cache-tests.cpp b/tools/gfx-unit-test/shader-cache-tests.cpp
index 4477c4f56..8ee8d9015 100644
--- a/tools/gfx-unit-test/shader-cache-tests.cpp
+++ b/tools/gfx-unit-test/shader-cache-tests.cpp
@@ -1,44 +1,43 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
+#include "gfx-test-texture-util.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
-#include "source/core/slang-string-util.h"
-#include "source/core/slang-io.h"
#include "source/core/slang-file-system.h"
+#include "source/core/slang-io.h"
#include "source/core/slang-process.h"
-#include "gfx-test-texture-util.h"
+#include "source/core/slang-string-util.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
using namespace Slang;
namespace gfx_test
{
- // Base class for shader cache tests.
- // Slang currently does not allow reloading shaders from modified sources.
- // Because of this, the tests recreate a GFX device for each test step,
- // allowing to modify shader sources in between.
- struct ShaderCacheTest
- {
- UnitTestContext* context;
- Slang::RenderApiFlag::Enum api;
+// Base class for shader cache tests.
+// Slang currently does not allow reloading shaders from modified sources.
+// Because of this, the tests recreate a GFX device for each test step,
+// allowing to modify shader sources in between.
+struct ShaderCacheTest
+{
+ UnitTestContext* context;
+ Slang::RenderApiFlag::Enum api;
- String testDirectory;
- String cacheDirectory;
+ String testDirectory;
+ String cacheDirectory;
- ComPtr<ISlangMutableFileSystem> diskFileSystem;
+ ComPtr<ISlangMutableFileSystem> diskFileSystem;
- IDevice::ShaderCacheDesc shaderCacheDesc = {};
+ IDevice::ShaderCacheDesc shaderCacheDesc = {};
- ComPtr<IDevice> device;
- ComPtr<IShaderCache> shaderCache;
- ComPtr<IPipelineState> pipelineState;
- ComPtr<IBufferResource> bufferResource;
- ComPtr<IResourceView> bufferView;
+ ComPtr<IDevice> device;
+ ComPtr<IShaderCache> shaderCache;
+ ComPtr<IPipelineState> pipelineState;
+ ComPtr<IBufferResource> bufferResource;
+ ComPtr<IResourceView> bufferView;
- String computeShaderA = String(
- R"(
+ String computeShaderA = String(
+ R"(
[shader("compute")]
[numthreads(4, 1, 1)]
void main(
@@ -48,10 +47,10 @@ namespace gfx_test
var input = buffer[sv_dispatchThreadID.x];
buffer[sv_dispatchThreadID.x] = input + 1.0f;
}
- )");
+ )");
- String computeShaderB = String(
- R"(
+ String computeShaderB = String(
+ R"(
[shader("compute")]
[numthreads(4, 1, 1)]
void main(
@@ -63,8 +62,8 @@ namespace gfx_test
}
)");
- String computeShaderC = String(
- R"(
+ String computeShaderC = String(
+ R"(
[shader("compute")]
[numthreads(4, 1, 1)]
void main(
@@ -77,359 +76,383 @@ namespace gfx_test
)");
- void removeDirectory(const String& directory)
- {
- auto osFileSystem = OSFileSystem::getMutableSingleton();
-
- struct Context
- {
- ISlangMutableFileSystem *fileSystem;
- const String& directory;
- } context { osFileSystem, directory };
-
- osFileSystem->enumeratePathContents(
- directory.getBuffer(),
- [](SlangPathType pathType, const char* fileName, void* userData)
- {
- struct Context* context = static_cast<Context *>(userData);
- if (pathType == SlangPathType::SLANG_PATH_TYPE_FILE)
- {
- String path = Path::simplify(context->directory + "/" + fileName);
- context->fileSystem->remove(path.getBuffer());
- }
- },
- &context);
-
- osFileSystem->remove(directory.getBuffer());
- }
-
- void writeShader(const String& source, const String& fileName)
- {
- diskFileSystem->saveFile(fileName.getBuffer(), source.getBuffer(), source.getLength());
- }
-
- void init(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
- {
- this->context = context;
- this->api = api;
- testDirectory = Path::simplify(Path::getParentDirectory(Path::getExecutablePath()) + "/shader-cache-test" + String(Process::getId()));
- cacheDirectory = Path::simplify(testDirectory + "/cache" + String(Process::getId()));
-
- // Cleanup if there are stale files from a previously aborted test.
- removeDirectory(cacheDirectory);
- removeDirectory(testDirectory);
-
- Path::createDirectory(testDirectory);
- diskFileSystem = new RelativeFileSystem(OSFileSystem::getMutableSingleton(), testDirectory);
- shaderCacheDesc.shaderCachePath = cacheDirectory.getBuffer();
- }
-
- void cleanup()
- {
- removeDirectory(cacheDirectory);
- removeDirectory(testDirectory);
- }
+ void removeDirectory(const String& directory)
+ {
+ auto osFileSystem = OSFileSystem::getMutableSingleton();
- template<typename Func>
- void runStep(Func func)
+ struct Context
{
- List<const char*> additionalSearchPaths;
- additionalSearchPaths.add(testDirectory.getBuffer());
+ ISlangMutableFileSystem* fileSystem;
+ const String& directory;
+ } context{osFileSystem, directory};
- runTestImpl(
- [this, func] (IDevice* device, UnitTestContext* ctx)
+ osFileSystem->enumeratePathContents(
+ directory.getBuffer(),
+ [](SlangPathType pathType, const char* fileName, void* userData)
+ {
+ struct Context* context = static_cast<Context*>(userData);
+ if (pathType == SlangPathType::SLANG_PATH_TYPE_FILE)
{
- this->device = device;
- SLANG_CHECK_ABORT(SLANG_SUCCEEDED(
- device->queryInterface(SLANG_UUID_IShaderCache, (void**)this->shaderCache.writeRef())));
- func();
- this->device = nullptr;
- this->shaderCache = nullptr;
- },
- context, api, additionalSearchPaths, shaderCacheDesc);
- }
-
- void createComputeResources()
- {
- const int numberCount = 4;
- float initialData[] = { 0.0f, 1.0f, 2.0f, 3.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- bufferResource.writeRef()));
-
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(bufferResource, nullptr, viewDesc, bufferView.writeRef()));
- }
-
- void freeComputeResources()
- {
- bufferResource = nullptr;
- bufferView = nullptr;
- pipelineState = nullptr;
- }
-
- void createComputePipeline(const char* moduleName, const char* entryPointName)
- {
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, moduleName, entryPointName, slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
- }
-
- void createComputePipeline(Slang::String shaderSource)
- {
- ComPtr<IShaderProgram> shaderProgram;
- GFX_CHECK_CALL_ABORT(loadComputeProgramFromSource(device, shaderProgram, shaderSource));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
- }
+ String path = Path::simplify(context->directory + "/" + fileName);
+ context->fileSystem->remove(path.getBuffer());
+ }
+ },
+ &context);
- void dispatchComputePipeline()
- {
- ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+ osFileSystem->remove(directory.getBuffer());
+ }
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
+ void writeShader(const String& source, const String& fileName)
+ {
+ diskFileSystem->saveFile(fileName.getBuffer(), source.getBuffer(), source.getLength());
+ }
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
+ void init(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+ {
+ this->context = context;
+ this->api = api;
+ testDirectory = Path::simplify(
+ Path::getParentDirectory(Path::getExecutablePath()) + "/shader-cache-test" +
+ String(Process::getId()));
+ cacheDirectory = Path::simplify(testDirectory + "/cache" + String(Process::getId()));
+
+ // Cleanup if there are stale files from a previously aborted test.
+ removeDirectory(cacheDirectory);
+ removeDirectory(testDirectory);
+
+ Path::createDirectory(testDirectory);
+ diskFileSystem = new RelativeFileSystem(OSFileSystem::getMutableSingleton(), testDirectory);
+ shaderCacheDesc.shaderCachePath = cacheDirectory.getBuffer();
+ }
- auto rootObject = encoder->bindPipeline(pipelineState);
+ void cleanup()
+ {
+ removeDirectory(cacheDirectory);
+ removeDirectory(testDirectory);
+ }
- // Bind buffer view to the entry point.
- ShaderCursor entryPointCursor(rootObject->getEntryPoint(0));
- entryPointCursor.getPath("buffer").setResource(bufferView);
+ template<typename Func>
+ void runStep(Func func)
+ {
+ List<const char*> additionalSearchPaths;
+ additionalSearchPaths.add(testDirectory.getBuffer());
- encoder->dispatchCompute(4, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ runTestImpl(
+ [this, func](IDevice* device, UnitTestContext* ctx)
+ {
+ this->device = device;
+ SLANG_CHECK_ABORT(SLANG_SUCCEEDED(device->queryInterface(
+ SLANG_UUID_IShaderCache,
+ (void**)this->shaderCache.writeRef())));
+ func();
+ this->device = nullptr;
+ this->shaderCache = nullptr;
+ },
+ context,
+ api,
+ additionalSearchPaths,
+ shaderCacheDesc);
+ }
- bool checkOutput(const List<float>& expectedOutput)
- {
- ComPtr<ISlangBlob> bufferBlob;
- device->readBufferResource(bufferResource, 0, 4 * sizeof(float), bufferBlob.writeRef());
- SLANG_CHECK_ABORT(bufferBlob && bufferBlob->getBufferSize() == expectedOutput.getCount() * sizeof(float));
- return ::memcmp(bufferBlob->getBufferPointer(), expectedOutput.getBuffer(), bufferBlob->getBufferSize()) == 0;
- }
+ void createComputeResources()
+ {
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 1.0f, 2.0f, 3.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ GFX_CHECK_CALL_ABORT(device->createBufferResource(
+ bufferDesc,
+ (void*)initialData,
+ bufferResource.writeRef()));
+
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(bufferResource, nullptr, viewDesc, bufferView.writeRef()));
+ }
- bool runComputePipeline(const char* moduleName, const char* entryPointName, const List<float>& expectedOutput)
- {
- createComputeResources();
- createComputePipeline(moduleName, entryPointName);
- dispatchComputePipeline();
- bool hasExpectedOutput = checkOutput(expectedOutput);
- SLANG_CHECK(hasExpectedOutput);
- freeComputeResources();
- return hasExpectedOutput;
- }
-
- bool runComputePipeline(Slang::String shaderSource, const List<float>& expectedOutput)
- {
- createComputeResources();
- createComputePipeline(shaderSource);
- dispatchComputePipeline();
- bool hasExpectedOutput = checkOutput(expectedOutput);
- SLANG_CHECK(hasExpectedOutput);
- freeComputeResources();
- return hasExpectedOutput;
- }
-
- ShaderCacheStats getStats()
- {
- SLANG_ASSERT(shaderCache);
- ShaderCacheStats stats;
- shaderCache->getShaderCacheStats(&stats);
- return stats;
- }
+ void freeComputeResources()
+ {
+ bufferResource = nullptr;
+ bufferView = nullptr;
+ pipelineState = nullptr;
+ }
- void run(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
- {
- init(context, api);
- runTests();
- cleanup();
- }
+ void createComputePipeline(const char* moduleName, const char* entryPointName)
+ {
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(
+ loadComputeProgram(device, shaderProgram, moduleName, entryPointName, slangReflection));
- virtual void runTests() = 0;
- };
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+ }
- // Basic shader cache test using 3 different shader files stored on disk.
- struct ShaderCacheSourceFile : ShaderCacheTest
+ void createComputePipeline(Slang::String shaderSource)
{
- void runTests()
- {
- // Write shader source files.
- writeShader(computeShaderA, "shader-cache-tmp-a.slang");
- writeShader(computeShaderB, "shader-cache-tmp-b.slang");
- writeShader(computeShaderC, "shader-cache-tmp-c.slang");
-
- // Cache is cold and we expect 3 misses.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-a", "main", { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-b", "main", { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-c", "main", { 3.f, 4.f, 5.f, 6.f }));
-
- SLANG_CHECK(getStats().missCount == 3);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 3);
- }
- );
+ ComPtr<IShaderProgram> shaderProgram;
+ GFX_CHECK_CALL_ABORT(loadComputeProgramFromSource(device, shaderProgram, shaderSource));
- // Cache is hot and we expect 3 hits.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-a", "main", { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-b", "main", { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-c", "main", { 3.f, 4.f, 5.f, 6.f }));
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+ }
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 3);
- SLANG_CHECK(getStats().entryCount == 3);
- }
- );
+ void dispatchComputePipeline()
+ {
+ ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
- // Write shader source files, all rotated by one.
- writeShader(computeShaderA, "shader-cache-tmp-b.slang");
- writeShader(computeShaderB, "shader-cache-tmp-c.slang");
- writeShader(computeShaderC, "shader-cache-tmp-a.slang");
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- // Cache is cold again and we expect 3 misses.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-b", "main", { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-c", "main", { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-a", "main", { 3.f, 4.f, 5.f, 6.f }));
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- SLANG_CHECK(getStats().missCount == 3);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 6);
- }
- );
+ auto rootObject = encoder->bindPipeline(pipelineState);
- // Cache is hot again and we expect 3 hits.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-b", "main", { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-c", "main", { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-a", "main", { 3.f, 4.f, 5.f, 6.f }));
+ // Bind buffer view to the entry point.
+ ShaderCursor entryPointCursor(rootObject->getEntryPoint(0));
+ entryPointCursor.getPath("buffer").setResource(bufferView);
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 3);
- SLANG_CHECK(getStats().entryCount == 6);
- }
- );
- }
- };
+ encoder->dispatchCompute(4, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- // Test caching of shaders that are compiled from source strings instead of files.
- struct ShaderCacheTestSourceString : ShaderCacheTest
+ bool checkOutput(const List<float>& expectedOutput)
{
- void runTests()
- {
- // Cache is cold and we expect 3 misses.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline(computeShaderA, { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline(computeShaderB, { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline(computeShaderC, { 3.f, 4.f, 5.f, 6.f }));
+ ComPtr<ISlangBlob> bufferBlob;
+ device->readBufferResource(bufferResource, 0, 4 * sizeof(float), bufferBlob.writeRef());
+ SLANG_CHECK_ABORT(
+ bufferBlob && bufferBlob->getBufferSize() == expectedOutput.getCount() * sizeof(float));
+ return ::memcmp(
+ bufferBlob->getBufferPointer(),
+ expectedOutput.getBuffer(),
+ bufferBlob->getBufferSize()) == 0;
+ }
- SLANG_CHECK(getStats().missCount == 3);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 3);
- }
- );
+ bool runComputePipeline(
+ const char* moduleName,
+ const char* entryPointName,
+ const List<float>& expectedOutput)
+ {
+ createComputeResources();
+ createComputePipeline(moduleName, entryPointName);
+ dispatchComputePipeline();
+ bool hasExpectedOutput = checkOutput(expectedOutput);
+ SLANG_CHECK(hasExpectedOutput);
+ freeComputeResources();
+ return hasExpectedOutput;
+ }
- // Cache is hot and we expect 3 hits.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline(computeShaderA, { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline(computeShaderB, { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline(computeShaderC, { 3.f, 4.f, 5.f, 6.f }));
+ bool runComputePipeline(Slang::String shaderSource, const List<float>& expectedOutput)
+ {
+ createComputeResources();
+ createComputePipeline(shaderSource);
+ dispatchComputePipeline();
+ bool hasExpectedOutput = checkOutput(expectedOutput);
+ SLANG_CHECK(hasExpectedOutput);
+ freeComputeResources();
+ return hasExpectedOutput;
+ }
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 3);
- SLANG_CHECK(getStats().entryCount == 3);
- }
- );
- }
- };
+ ShaderCacheStats getStats()
+ {
+ SLANG_ASSERT(shaderCache);
+ ShaderCacheStats stats;
+ shaderCache->getShaderCacheStats(&stats);
+ return stats;
+ }
- // Test one shader file on disk with multiple entry points.
- struct ShaderCacheTestEntryPoint : ShaderCacheTest
+ void run(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
{
- void runTests()
- {
- // Cache is cold and we expect 3 misses, one for each entry point.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-multiple-entry-points", "computeA", { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-multiple-entry-points", "computeB", { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-multiple-entry-points", "computeC", { 3.f, 4.f, 5.f, 6.f }));
+ init(context, api);
+ runTests();
+ cleanup();
+ }
- SLANG_CHECK(getStats().missCount == 3);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 3);
- }
- );
+ virtual void runTests() = 0;
+};
- // Cache is hot and we expect 3 hits.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-multiple-entry-points", "computeA", { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-multiple-entry-points", "computeB", { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-multiple-entry-points", "computeC", { 3.f, 4.f, 5.f, 6.f }));
+// Basic shader cache test using 3 different shader files stored on disk.
+struct ShaderCacheSourceFile : ShaderCacheTest
+{
+ void runTests()
+ {
+ // Write shader source files.
+ writeShader(computeShaderA, "shader-cache-tmp-a.slang");
+ writeShader(computeShaderB, "shader-cache-tmp-b.slang");
+ writeShader(computeShaderC, "shader-cache-tmp-c.slang");
+
+ // Cache is cold and we expect 3 misses.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-a", "main", {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-b", "main", {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-c", "main", {3.f, 4.f, 5.f, 6.f}));
+
+ SLANG_CHECK(getStats().missCount == 3);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 3);
+ });
+
+ // Cache is hot and we expect 3 hits.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-a", "main", {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-b", "main", {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-c", "main", {3.f, 4.f, 5.f, 6.f}));
+
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 3);
+ SLANG_CHECK(getStats().entryCount == 3);
+ });
+
+ // Write shader source files, all rotated by one.
+ writeShader(computeShaderA, "shader-cache-tmp-b.slang");
+ writeShader(computeShaderB, "shader-cache-tmp-c.slang");
+ writeShader(computeShaderC, "shader-cache-tmp-a.slang");
+
+ // Cache is cold again and we expect 3 misses.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-b", "main", {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-c", "main", {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-a", "main", {3.f, 4.f, 5.f, 6.f}));
+
+ SLANG_CHECK(getStats().missCount == 3);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 6);
+ });
+
+ // Cache is hot again and we expect 3 hits.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-b", "main", {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-c", "main", {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(runComputePipeline("shader-cache-tmp-a", "main", {3.f, 4.f, 5.f, 6.f}));
+
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 3);
+ SLANG_CHECK(getStats().entryCount == 6);
+ });
+ }
+};
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 3);
- SLANG_CHECK(getStats().entryCount == 3);
- }
- );
- }
- };
+// Test caching of shaders that are compiled from source strings instead of files.
+struct ShaderCacheTestSourceString : ShaderCacheTest
+{
+ void runTests()
+ {
+ // Cache is cold and we expect 3 misses.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(computeShaderA, {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline(computeShaderB, {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(runComputePipeline(computeShaderC, {3.f, 4.f, 5.f, 6.f}));
+
+ SLANG_CHECK(getStats().missCount == 3);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 3);
+ });
+
+ // Cache is hot and we expect 3 hits.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(computeShaderA, {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline(computeShaderB, {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(runComputePipeline(computeShaderC, {3.f, 4.f, 5.f, 6.f}));
+
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 3);
+ SLANG_CHECK(getStats().entryCount == 3);
+ });
+ }
+};
- // Test cache invalidation due to an import/include file being changed on disk.
- struct ShaderCacheTestImportInclude : ShaderCacheTest
+// Test one shader file on disk with multiple entry points.
+struct ShaderCacheTestEntryPoint : ShaderCacheTest
+{
+ void runTests()
{
- String importedContentsA = String(
- R"(
+ // Cache is cold and we expect 3 misses, one for each entry point.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(
+ "shader-cache-multiple-entry-points",
+ "computeA",
+ {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline(
+ "shader-cache-multiple-entry-points",
+ "computeB",
+ {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(runComputePipeline(
+ "shader-cache-multiple-entry-points",
+ "computeC",
+ {3.f, 4.f, 5.f, 6.f}));
+
+ SLANG_CHECK(getStats().missCount == 3);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 3);
+ });
+
+ // Cache is hot and we expect 3 hits.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(
+ "shader-cache-multiple-entry-points",
+ "computeA",
+ {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline(
+ "shader-cache-multiple-entry-points",
+ "computeB",
+ {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(runComputePipeline(
+ "shader-cache-multiple-entry-points",
+ "computeC",
+ {3.f, 4.f, 5.f, 6.f}));
+
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 3);
+ SLANG_CHECK(getStats().entryCount == 3);
+ });
+ }
+};
+
+// Test cache invalidation due to an import/include file being changed on disk.
+struct ShaderCacheTestImportInclude : ShaderCacheTest
+{
+ String importedContentsA = String(
+ R"(
public void processElement(RWStructuredBuffer<float> buffer, uint index)
{
var input = buffer[index];
@@ -437,8 +460,8 @@ namespace gfx_test
}
)");
- String importedContentsB = String(
- R"(
+ String importedContentsB = String(
+ R"(
public void processElement(RWStructuredBuffer<float> buffer, uint index)
{
var input = buffer[index];
@@ -446,8 +469,8 @@ namespace gfx_test
}
)");
- String importFile = String(
- R"(
+ String importFile = String(
+ R"(
import shader_cache_tmp_imported;
[shader("compute")]
@@ -460,8 +483,8 @@ namespace gfx_test
}
)");
- String includeFile = String(
- R"(
+ String includeFile = String(
+ R"(
#include "shader-cache-tmp-imported.slang"
[shader("compute")]
@@ -473,627 +496,635 @@ namespace gfx_test
processElement(buffer, sv_dispatchThreadID.x);
})");
- void runTests()
- {
- // Write shader source files.
- writeShader(importedContentsA, "shader-cache-tmp-imported.slang");
- writeShader(importFile, "shader-cache-tmp-import.slang");
- writeShader(includeFile, "shader-cache-tmp-include.slang");
-
- // Cache is cold and we expect 2 misses.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-import", "main", { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-include", "main", { 1.f, 2.f, 3.f, 4.f }));
-
- SLANG_CHECK(getStats().missCount == 2);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
-
- // Cache is hot and we expect 2 hits.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-import", "main", { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-include", "main", { 1.f, 2.f, 3.f, 4.f }));
-
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 2);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
-
- // Change content of imported/included shader file.
- writeShader(importedContentsB, "shader-cache-tmp-imported.slang");
-
- // Cache is cold and we expect 2 misses.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-import", "main", { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-include", "main", { 2.f, 3.f, 4.f, 5.f }));
-
- SLANG_CHECK(getStats().missCount == 2);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 4);
- }
- );
-
- // Cache is hot and we expect 2 hits.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-import", "main", { 2.f, 3.f, 4.f, 5.f }));
- SLANG_CHECK(runComputePipeline("shader-cache-tmp-include", "main", { 2.f, 3.f, 4.f, 5.f }));
-
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 2);
- SLANG_CHECK(getStats().entryCount == 4);
- }
- );
- }
- };
-
- // One shader featuring multiple kinds of shader objects that can be bound.
- struct ShaderCacheTestSpecialization : ShaderCacheTest
+ void runTests()
{
- slang::ProgramLayout* slangReflection;
-
- void createComputePipeline()
- {
- ComPtr<IShaderProgram> shaderProgram;
-
- GFX_CHECK_CALL_ABORT(
- loadComputeProgram(device, shaderProgram, "shader-cache-specialization", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
- }
-
- void dispatchComputePipeline(const char* transformerTypeName)
- {
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
+ // Write shader source files.
+ writeShader(importedContentsA, "shader-cache-tmp-imported.slang");
+ writeShader(importFile, "shader-cache-tmp-import.slang");
+ writeShader(includeFile, "shader-cache-tmp-include.slang");
+
+ // Cache is cold and we expect 2 misses.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(
+ runComputePipeline("shader-cache-tmp-import", "main", {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(
+ runComputePipeline("shader-cache-tmp-include", "main", {1.f, 2.f, 3.f, 4.f}));
+
+ SLANG_CHECK(getStats().missCount == 2);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
+
+ // Cache is hot and we expect 2 hits.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(
+ runComputePipeline("shader-cache-tmp-import", "main", {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(
+ runComputePipeline("shader-cache-tmp-include", "main", {1.f, 2.f, 3.f, 4.f}));
+
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 2);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
+
+ // Change content of imported/included shader file.
+ writeShader(importedContentsB, "shader-cache-tmp-imported.slang");
+
+ // Cache is cold and we expect 2 misses.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(
+ runComputePipeline("shader-cache-tmp-import", "main", {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(
+ runComputePipeline("shader-cache-tmp-include", "main", {2.f, 3.f, 4.f, 5.f}));
+
+ SLANG_CHECK(getStats().missCount == 2);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 4);
+ });
+
+ // Cache is hot and we expect 2 hits.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(
+ runComputePipeline("shader-cache-tmp-import", "main", {2.f, 3.f, 4.f, 5.f}));
+ SLANG_CHECK(
+ runComputePipeline("shader-cache-tmp-include", "main", {2.f, 3.f, 4.f, 5.f}));
+
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 2);
+ SLANG_CHECK(getStats().entryCount == 4);
+ });
+ }
+};
- Slang::ComPtr<IShaderObject> transformer;
- slang::TypeReflection* transformerType = slangReflection->findTypeByName(transformerTypeName);
- GFX_CHECK_CALL_ABORT(device->createShaderObject(
- transformerType, ShaderObjectContainerType::None, transformer.writeRef()));
+// One shader featuring multiple kinds of shader objects that can be bound.
+struct ShaderCacheTestSpecialization : ShaderCacheTest
+{
+ slang::ProgramLayout* slangReflection;
- float c = 5.f;
- ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
+ void createComputePipeline()
+ {
+ ComPtr<IShaderProgram> shaderProgram;
+
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "shader-cache-specialization",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+ }
- ShaderCursor entryPointCursor(rootObject->getEntryPoint(0));
- entryPointCursor.getPath("buffer").setResource(bufferView);
- entryPointCursor.getPath("transformer").setObject(transformer);
+ void dispatchComputePipeline(const char* transformerTypeName)
+ {
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ Slang::ComPtr<IShaderObject> transformer;
+ slang::TypeReflection* transformerType =
+ slangReflection->findTypeByName(transformerTypeName);
+ GFX_CHECK_CALL_ABORT(device->createShaderObject(
+ transformerType,
+ ShaderObjectContainerType::None,
+ transformer.writeRef()));
+
+ float c = 5.f;
+ ShaderCursor(transformer).getPath("c").setData(&c, sizeof(float));
+
+ ShaderCursor entryPointCursor(rootObject->getEntryPoint(0));
+ entryPointCursor.getPath("buffer").setResource(bufferView);
+ entryPointCursor.getPath("transformer").setObject(transformer);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ bool runComputePipeline(const char* transformerTypeName, const List<float>& expectedOutput)
+ {
+ createComputeResources();
+ createComputePipeline();
+ dispatchComputePipeline(transformerTypeName);
+ bool hasExpectedOutput = checkOutput(expectedOutput);
+ SLANG_CHECK(hasExpectedOutput);
+ freeComputeResources();
+ return hasExpectedOutput;
+ }
- bool runComputePipeline(const char* transformerTypeName, const List<float>& expectedOutput)
- {
- createComputeResources();
- createComputePipeline();
- dispatchComputePipeline(transformerTypeName);
- bool hasExpectedOutput = checkOutput(expectedOutput);
- SLANG_CHECK(hasExpectedOutput);
- freeComputeResources();
- return hasExpectedOutput;
- }
-
- void runTests()
- {
- // Cache is cold and we expect 2 misses.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("AddTransformer", { 5.f, 6.f, 7.f, 8.f }));
- SLANG_CHECK(runComputePipeline("MulTransformer", { 0.f, 5.f, 10.f, 15.f }));
+ void runTests()
+ {
+ // Cache is cold and we expect 2 misses.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline("AddTransformer", {5.f, 6.f, 7.f, 8.f}));
+ SLANG_CHECK(runComputePipeline("MulTransformer", {0.f, 5.f, 10.f, 15.f}));
- SLANG_CHECK(getStats().missCount == 2);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
+ SLANG_CHECK(getStats().missCount == 2);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
- // Cache is hot and we expect 2 hits.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline("AddTransformer", { 5.f, 6.f, 7.f, 8.f }));
- SLANG_CHECK(runComputePipeline("MulTransformer", { 0.f, 5.f, 10.f, 15.f }));
+ // Cache is hot and we expect 2 hits.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline("AddTransformer", {5.f, 6.f, 7.f, 8.f}));
+ SLANG_CHECK(runComputePipeline("MulTransformer", {0.f, 5.f, 10.f, 15.f}));
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 2);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
- }
- };
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 2);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
+ }
+};
- struct ShaderCacheTestEviction : ShaderCacheTest
+struct ShaderCacheTestEviction : ShaderCacheTest
+{
+ void runTests()
{
- void runTests()
- {
- shaderCacheDesc.maxEntryCount = 2;
+ shaderCacheDesc.maxEntryCount = 2;
- // Load shader A & B. Cache is cold and we expect 2 misses.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline(computeShaderA, { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline(computeShaderB, { 2.f, 3.f, 4.f, 5.f }));
-
- SLANG_CHECK(getStats().missCount == 2);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
-
- // Load shader A & B. Cache is hot and we expect 2 hits.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline(computeShaderA, { 1.f, 2.f, 3.f, 4.f }));
- SLANG_CHECK(runComputePipeline(computeShaderB, { 2.f, 3.f, 4.f, 5.f }));
+ // Load shader A & B. Cache is cold and we expect 2 misses.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(computeShaderA, {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline(computeShaderB, {2.f, 3.f, 4.f, 5.f}));
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 2);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
+ SLANG_CHECK(getStats().missCount == 2);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
- // Load shader C. Cache is cold and we expect 1 miss.
- // This will evict the least frequently used entry (shader A).
- // We expect 2 entries in the cache (shader B & C).
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline(computeShaderC, { 3.f, 4.f, 5.f, 6.f }));
+ // Load shader A & B. Cache is hot and we expect 2 hits.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(computeShaderA, {1.f, 2.f, 3.f, 4.f}));
+ SLANG_CHECK(runComputePipeline(computeShaderB, {2.f, 3.f, 4.f, 5.f}));
+
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 2);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
+
+ // Load shader C. Cache is cold and we expect 1 miss.
+ // This will evict the least frequently used entry (shader A).
+ // We expect 2 entries in the cache (shader B & C).
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(computeShaderC, {3.f, 4.f, 5.f, 6.f}));
- SLANG_CHECK(getStats().missCount == 1);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
+ SLANG_CHECK(getStats().missCount == 1);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
- // Load shader C. Cache is hot and we expect 1 hit.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline(computeShaderC, { 3.f, 4.f, 5.f, 6.f }));
+ // Load shader C. Cache is hot and we expect 1 hit.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(computeShaderC, {3.f, 4.f, 5.f, 6.f}));
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 1);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 1);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
- // Load shader B. Cache is hot and we expect 1 hit.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline(computeShaderB, { 2.f, 3.f, 4.f, 5.f }));
+ // Load shader B. Cache is hot and we expect 1 hit.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(computeShaderB, {2.f, 3.f, 4.f, 5.f}));
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 1);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 1);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
- // Load shader A. Cache is cold and we expect 1 miss.
- runStep(
- [this]()
- {
- SLANG_CHECK(runComputePipeline(computeShaderA, { 1.f, 2.f, 3.f, 4.f }));
+ // Load shader A. Cache is cold and we expect 1 miss.
+ runStep(
+ [this]()
+ {
+ SLANG_CHECK(runComputePipeline(computeShaderA, {1.f, 2.f, 3.f, 4.f}));
- SLANG_CHECK(getStats().missCount == 1);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
- }
- };
+ SLANG_CHECK(getStats().missCount == 1);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
+ }
+};
- // Similar to ShaderCacheTestEntryPoint but with a source file containing a vertex and fragment shader.
- struct ShaderCacheTestGraphics : ShaderCacheTest
+// Similar to ShaderCacheTestEntryPoint but with a source file containing a vertex and fragment
+// shader.
+struct ShaderCacheTestGraphics : ShaderCacheTest
+{
+ struct Vertex
{
- struct Vertex
- {
- float position[3];
- };
-
- static const int kWidth = 256;
- static const int kHeight = 256;
- static const Format format = Format::R32G32B32A32_FLOAT;
-
- ComPtr<IBufferResource> vertexBuffer;
- ComPtr<ITextureResource> colorBuffer;
- ComPtr<IInputLayout> inputLayout;
- ComPtr<IFramebufferLayout> framebufferLayout;
- ComPtr<IRenderPassLayout> renderPass;
- ComPtr<IFramebuffer> framebuffer;
-
- ComPtr<IBufferResource> createVertexBuffer(IDevice* device)
- {
- const Vertex vertices[] = {
- { 0, 0, 0.5 },
- { 1, 0, 0.5 },
- { 0, 1, 0.5 },
- };
-
- IBufferResource::Desc vertexBufferDesc;
- vertexBufferDesc.type = IResource::Type::Buffer;
- vertexBufferDesc.sizeInBytes = sizeof(vertices);
- vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
- vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
- ComPtr<IBufferResource> vertexBuffer = device->createBufferResource(vertexBufferDesc, vertices);
- SLANG_CHECK_ABORT(vertexBuffer != nullptr);
- return vertexBuffer;
- }
-
- ComPtr<ITextureResource> createColorBuffer(IDevice* device)
- {
- gfx::ITextureResource::Desc colorBufferDesc;
- colorBufferDesc.type = IResource::Type::Texture2D;
- colorBufferDesc.size.width = kWidth;
- colorBufferDesc.size.height = kHeight;
- colorBufferDesc.size.depth = 1;
- colorBufferDesc.numMipLevels = 1;
- colorBufferDesc.format = format;
- colorBufferDesc.defaultState = ResourceState::RenderTarget;
- colorBufferDesc.allowedStates = { ResourceState::RenderTarget, ResourceState::CopySource };
- ComPtr<ITextureResource> colorBuffer = device->createTextureResource(colorBufferDesc, nullptr);
- SLANG_CHECK_ABORT(colorBuffer != nullptr);
- return colorBuffer;
- }
-
- void createGraphicsResources()
- {
- VertexStreamDesc vertexStreams[] = {
- { sizeof(Vertex), InputSlotClass::PerVertex, 0 },
- };
-
- InputElementDesc inputElements[] = {
- // Vertex buffer data
- { "POSITION", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0 },
- };
- IInputLayout::Desc inputLayoutDesc = {};
- inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
- inputLayoutDesc.inputElements = inputElements;
- inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
- inputLayoutDesc.vertexStreams = vertexStreams;
- inputLayout = device->createInputLayout(inputLayoutDesc);
- SLANG_CHECK_ABORT(inputLayout != nullptr);
-
- vertexBuffer = createVertexBuffer(device);
- colorBuffer = createColorBuffer(device);
-
- IFramebufferLayout::TargetLayout targetLayout;
- targetLayout.format = format;
- targetLayout.sampleCount = 1;
-
- IFramebufferLayout::Desc framebufferLayoutDesc;
- framebufferLayoutDesc.renderTargetCount = 1;
- framebufferLayoutDesc.renderTargets = &targetLayout;
- framebufferLayout = device->createFramebufferLayout(framebufferLayoutDesc);
- SLANG_CHECK_ABORT(framebufferLayout != nullptr);
-
- IRenderPassLayout::Desc renderPassDesc = {};
- renderPassDesc.framebufferLayout = framebufferLayout;
- renderPassDesc.renderTargetCount = 1;
- IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
- renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
- renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
- renderTargetAccess.initialState = ResourceState::RenderTarget;
- renderTargetAccess.finalState = ResourceState::CopySource;
- renderPassDesc.renderTargetAccess = &renderTargetAccess;
- GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
-
- gfx::IResourceView::Desc colorBufferViewDesc;
- memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
- colorBufferViewDesc.format = format;
- colorBufferViewDesc.renderTarget.shape = gfx::IResource::Type::Texture2D;
- colorBufferViewDesc.type = gfx::IResourceView::Type::RenderTarget;
- auto rtv = device->createTextureView(colorBuffer, colorBufferViewDesc);
-
- gfx::IFramebuffer::Desc framebufferDesc;
- framebufferDesc.renderTargetCount = 1;
- framebufferDesc.depthStencilView = nullptr;
- framebufferDesc.renderTargetViews = rtv.readRef();
- framebufferDesc.layout = framebufferLayout;
- GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
- }
-
- void freeGraphicsResources()
- {
- inputLayout = nullptr;
- framebufferLayout = nullptr;
- renderPass = nullptr;
- framebuffer = nullptr;
- vertexBuffer = nullptr;
- colorBuffer = nullptr;
- pipelineState = nullptr;
- }
-
- void createGraphicsPipeline()
- {
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(
- loadGraphicsProgram(device, shaderProgram, "shader-cache-graphics", "vertexMain", "fragmentMain", slangReflection));
-
- GraphicsPipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- pipelineDesc.inputLayout = inputLayout;
- pipelineDesc.framebufferLayout = framebufferLayout;
- pipelineDesc.depthStencil.depthTestEnable = false;
- pipelineDesc.depthStencil.depthWriteEnable = false;
- GFX_CHECK_CALL_ABORT(
- device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
- }
-
- void dispatchGraphicsPipeline()
- {
- ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
-
- auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- gfx::Viewport viewport = {};
- viewport.maxZ = 1.0f;
- viewport.extentX = (float)kWidth;
- viewport.extentY = (float)kHeight;
- encoder->setViewportAndScissor(viewport);
-
- encoder->setVertexBuffer(0, vertexBuffer);
- encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
-
- encoder->draw(3);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- void runGraphicsPipeline()
- {
- createGraphicsResources();
- createGraphicsPipeline();
- dispatchGraphicsPipeline();
- freeGraphicsResources();
- }
-
- void runTests()
- {
- // Cache is cold and we expect 2 misses (2 entry points).
- runStep(
- [this]()
- {
- runGraphicsPipeline();
-
- SLANG_CHECK(getStats().missCount == 2);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
-
- // Cache is hot and we expect 2 hits.
- runStep(
- [this]()
- {
- runGraphicsPipeline();
-
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 2);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
- }
+ float position[3];
};
- // Similar to ShaderCacheTestGraphics but with two separate shader files for the vertex and fragment shaders.
- struct ShaderCacheTestGraphicsSplit : ShaderCacheTestGraphics
- {
- void createGraphicsPipeline()
- {
- ComPtr<slang::ISession> slangSession;
- GFX_CHECK_CALL_ABORT(device->getSlangSession(slangSession.writeRef()));
- slang::IModule* vertexModule = slangSession->loadModule("shader-cache-graphics-vertex");
- SLANG_CHECK_ABORT(vertexModule);
- slang::IModule* fragmentModule = slangSession->loadModule("shader-cache-graphics-fragment");
- SLANG_CHECK_ABORT(fragmentModule);
-
- ComPtr<slang::IEntryPoint> vertexEntryPoint;
- GFX_CHECK_CALL_ABORT(
- vertexModule->findEntryPointByName("main", vertexEntryPoint.writeRef()));
-
- ComPtr<slang::IEntryPoint> fragmentEntryPoint;
- GFX_CHECK_CALL_ABORT(
- fragmentModule->findEntryPointByName("main", fragmentEntryPoint.writeRef()));
-
- Slang::List<slang::IComponentType*> componentTypes;
- componentTypes.add(vertexModule);
- componentTypes.add(fragmentModule);
-
- Slang::ComPtr<slang::IComponentType> composedProgram;
- GFX_CHECK_CALL_ABORT(
- slangSession->createCompositeComponentType(
- componentTypes.getBuffer(),
- componentTypes.getCount(),
- composedProgram.writeRef()));
-
- slang::ProgramLayout* slangReflection = composedProgram->getLayout();
-
- Slang::List<slang::IComponentType*> entryPoints;
- entryPoints.add(vertexEntryPoint);
- entryPoints.add(fragmentEntryPoint);
-
- gfx::IShaderProgram::Desc programDesc = {};
- programDesc.slangGlobalScope = composedProgram.get();
- programDesc.linkingStyle = gfx::IShaderProgram::LinkingStyle::SeparateEntryPointCompilation;
- programDesc.entryPointCount = 2;
- programDesc.slangEntryPoints = entryPoints.getBuffer();
-
- ComPtr<IShaderProgram> shaderProgram = device->createProgram(programDesc);
-
- GraphicsPipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- pipelineDesc.inputLayout = inputLayout;
- pipelineDesc.framebufferLayout = framebufferLayout;
- pipelineDesc.depthStencil.depthTestEnable = false;
- pipelineDesc.depthStencil.depthWriteEnable = false;
- GFX_CHECK_CALL_ABORT(
- device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
- }
-
- void runGraphicsPipeline()
- {
- createGraphicsResources();
- createGraphicsPipeline();
- dispatchGraphicsPipeline();
- freeGraphicsResources();
- }
-
- void runTests()
- {
- // Cache is cold and we expect 2 misses (2 entry points).
- runStep(
- [this]()
- {
- runGraphicsPipeline();
+ static const int kWidth = 256;
+ static const int kHeight = 256;
+ static const Format format = Format::R32G32B32A32_FLOAT;
- SLANG_CHECK(getStats().missCount == 2);
- SLANG_CHECK(getStats().hitCount == 0);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- );
-
- // Cache is hot and we expect 2 hits.
- runStep(
- [this]()
- {
- runGraphicsPipeline();
-
- SLANG_CHECK(getStats().missCount == 0);
- SLANG_CHECK(getStats().hitCount == 2);
- SLANG_CHECK(getStats().entryCount == 2);
- }
- ); }
- };
+ ComPtr<IBufferResource> vertexBuffer;
+ ComPtr<ITextureResource> colorBuffer;
+ ComPtr<IInputLayout> inputLayout;
+ ComPtr<IFramebufferLayout> framebufferLayout;
+ ComPtr<IRenderPassLayout> renderPass;
+ ComPtr<IFramebuffer> framebuffer;
- template<typename T>
- void runTest(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+ ComPtr<IBufferResource> createVertexBuffer(IDevice* device)
{
- T test;
- test.run(context, api);
- }
+ const Vertex vertices[] = {
+ {0, 0, 0.5},
+ {1, 0, 0.5},
+ {0, 1, 0.5},
+ };
- SLANG_UNIT_TEST(shaderCacheSourceFileD3D12)
- {
- runTest<ShaderCacheSourceFile>(unitTestContext, Slang::RenderApiFlag::D3D12);
+ IBufferResource::Desc vertexBufferDesc;
+ vertexBufferDesc.type = IResource::Type::Buffer;
+ vertexBufferDesc.sizeInBytes = sizeof(vertices);
+ vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
+ vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
+ ComPtr<IBufferResource> vertexBuffer =
+ device->createBufferResource(vertexBufferDesc, vertices);
+ SLANG_CHECK_ABORT(vertexBuffer != nullptr);
+ return vertexBuffer;
}
- SLANG_UNIT_TEST(shaderCacheSourceFileVulkan)
+ ComPtr<ITextureResource> createColorBuffer(IDevice* device)
{
- runTest<ShaderCacheSourceFile>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ gfx::ITextureResource::Desc colorBufferDesc;
+ colorBufferDesc.type = IResource::Type::Texture2D;
+ colorBufferDesc.size.width = kWidth;
+ colorBufferDesc.size.height = kHeight;
+ colorBufferDesc.size.depth = 1;
+ colorBufferDesc.numMipLevels = 1;
+ colorBufferDesc.format = format;
+ colorBufferDesc.defaultState = ResourceState::RenderTarget;
+ colorBufferDesc.allowedStates = {ResourceState::RenderTarget, ResourceState::CopySource};
+ ComPtr<ITextureResource> colorBuffer =
+ device->createTextureResource(colorBufferDesc, nullptr);
+ SLANG_CHECK_ABORT(colorBuffer != nullptr);
+ return colorBuffer;
}
- SLANG_UNIT_TEST(shaderCacheSourceStringD3D12)
+ void createGraphicsResources()
{
- runTest<ShaderCacheTestSourceString>(unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ VertexStreamDesc vertexStreams[] = {
+ {sizeof(Vertex), InputSlotClass::PerVertex, 0},
+ };
- SLANG_UNIT_TEST(shaderCacheSourceStringVulkan)
- {
- runTest<ShaderCacheTestSourceString>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ InputElementDesc inputElements[] = {
+ // Vertex buffer data
+ {"POSITION", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0},
+ };
+ IInputLayout::Desc inputLayoutDesc = {};
+ inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
+ inputLayoutDesc.inputElements = inputElements;
+ inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
+ inputLayoutDesc.vertexStreams = vertexStreams;
+ inputLayout = device->createInputLayout(inputLayoutDesc);
+ SLANG_CHECK_ABORT(inputLayout != nullptr);
+
+ vertexBuffer = createVertexBuffer(device);
+ colorBuffer = createColorBuffer(device);
+
+ IFramebufferLayout::TargetLayout targetLayout;
+ targetLayout.format = format;
+ targetLayout.sampleCount = 1;
+
+ IFramebufferLayout::Desc framebufferLayoutDesc;
+ framebufferLayoutDesc.renderTargetCount = 1;
+ framebufferLayoutDesc.renderTargets = &targetLayout;
+ framebufferLayout = device->createFramebufferLayout(framebufferLayoutDesc);
+ SLANG_CHECK_ABORT(framebufferLayout != nullptr);
+
+ IRenderPassLayout::Desc renderPassDesc = {};
+ renderPassDesc.framebufferLayout = framebufferLayout;
+ renderPassDesc.renderTargetCount = 1;
+ IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
+ renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
+ renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
+ renderTargetAccess.initialState = ResourceState::RenderTarget;
+ renderTargetAccess.finalState = ResourceState::CopySource;
+ renderPassDesc.renderTargetAccess = &renderTargetAccess;
+ GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
+
+ gfx::IResourceView::Desc colorBufferViewDesc;
+ memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
+ colorBufferViewDesc.format = format;
+ colorBufferViewDesc.renderTarget.shape = gfx::IResource::Type::Texture2D;
+ colorBufferViewDesc.type = gfx::IResourceView::Type::RenderTarget;
+ auto rtv = device->createTextureView(colorBuffer, colorBufferViewDesc);
+
+ gfx::IFramebuffer::Desc framebufferDesc;
+ framebufferDesc.renderTargetCount = 1;
+ framebufferDesc.depthStencilView = nullptr;
+ framebufferDesc.renderTargetViews = rtv.readRef();
+ framebufferDesc.layout = framebufferLayout;
+ GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
}
- SLANG_UNIT_TEST(shaderCacheEntryPointD3D12)
+ void freeGraphicsResources()
{
- runTest<ShaderCacheTestEntryPoint>(unitTestContext, Slang::RenderApiFlag::D3D12);
+ inputLayout = nullptr;
+ framebufferLayout = nullptr;
+ renderPass = nullptr;
+ framebuffer = nullptr;
+ vertexBuffer = nullptr;
+ colorBuffer = nullptr;
+ pipelineState = nullptr;
}
- SLANG_UNIT_TEST(shaderCacheEntryPointVulkan)
+ void createGraphicsPipeline()
{
- runTest<ShaderCacheTestEntryPoint>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadGraphicsProgram(
+ device,
+ shaderProgram,
+ "shader-cache-graphics",
+ "vertexMain",
+ "fragmentMain",
+ slangReflection));
+
+ GraphicsPipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ pipelineDesc.inputLayout = inputLayout;
+ pipelineDesc.framebufferLayout = framebufferLayout;
+ pipelineDesc.depthStencil.depthTestEnable = false;
+ pipelineDesc.depthStencil.depthWriteEnable = false;
+ GFX_CHECK_CALL_ABORT(
+ device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
}
- SLANG_UNIT_TEST(shaderCacheImportIncludeD3D12)
+ void dispatchGraphicsPipeline()
{
- runTest<ShaderCacheTestImportInclude>(unitTestContext, Slang::RenderApiFlag::D3D12);
+ ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+
+ auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ gfx::Viewport viewport = {};
+ viewport.maxZ = 1.0f;
+ viewport.extentX = (float)kWidth;
+ viewport.extentY = (float)kHeight;
+ encoder->setViewportAndScissor(viewport);
+
+ encoder->setVertexBuffer(0, vertexBuffer);
+ encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
+
+ encoder->draw(3);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- SLANG_UNIT_TEST(shaderCacheImportIncludeVulkan)
+ void runGraphicsPipeline()
{
- runTest<ShaderCacheTestImportInclude>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ createGraphicsResources();
+ createGraphicsPipeline();
+ dispatchGraphicsPipeline();
+ freeGraphicsResources();
}
- SLANG_UNIT_TEST(shaderCacheSpecializationD3D12)
+ void runTests()
{
- runTest<ShaderCacheTestSpecialization>(unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ // Cache is cold and we expect 2 misses (2 entry points).
+ runStep(
+ [this]()
+ {
+ runGraphicsPipeline();
- SLANG_UNIT_TEST(shaderCacheSpecializationVulkan)
- {
- runTest<ShaderCacheTestSpecialization>(unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+ SLANG_CHECK(getStats().missCount == 2);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
- SLANG_UNIT_TEST(shaderCacheEvictionD3D12)
- {
- runTest<ShaderCacheTestEviction>(unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ // Cache is hot and we expect 2 hits.
+ runStep(
+ [this]()
+ {
+ runGraphicsPipeline();
- SLANG_UNIT_TEST(shaderCacheEvictionVulkan)
- {
- runTest<ShaderCacheTestEviction>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 2);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
}
+};
- SLANG_UNIT_TEST(shaderCacheGraphicsD3D12)
+// Similar to ShaderCacheTestGraphics but with two separate shader files for the vertex and fragment
+// shaders.
+struct ShaderCacheTestGraphicsSplit : ShaderCacheTestGraphics
+{
+ void createGraphicsPipeline()
{
- runTest<ShaderCacheTestGraphics>(unitTestContext, Slang::RenderApiFlag::D3D12);
+ ComPtr<slang::ISession> slangSession;
+ GFX_CHECK_CALL_ABORT(device->getSlangSession(slangSession.writeRef()));
+ slang::IModule* vertexModule = slangSession->loadModule("shader-cache-graphics-vertex");
+ SLANG_CHECK_ABORT(vertexModule);
+ slang::IModule* fragmentModule = slangSession->loadModule("shader-cache-graphics-fragment");
+ SLANG_CHECK_ABORT(fragmentModule);
+
+ ComPtr<slang::IEntryPoint> vertexEntryPoint;
+ GFX_CHECK_CALL_ABORT(
+ vertexModule->findEntryPointByName("main", vertexEntryPoint.writeRef()));
+
+ ComPtr<slang::IEntryPoint> fragmentEntryPoint;
+ GFX_CHECK_CALL_ABORT(
+ fragmentModule->findEntryPointByName("main", fragmentEntryPoint.writeRef()));
+
+ Slang::List<slang::IComponentType*> componentTypes;
+ componentTypes.add(vertexModule);
+ componentTypes.add(fragmentModule);
+
+ Slang::ComPtr<slang::IComponentType> composedProgram;
+ GFX_CHECK_CALL_ABORT(slangSession->createCompositeComponentType(
+ componentTypes.getBuffer(),
+ componentTypes.getCount(),
+ composedProgram.writeRef()));
+
+ slang::ProgramLayout* slangReflection = composedProgram->getLayout();
+
+ Slang::List<slang::IComponentType*> entryPoints;
+ entryPoints.add(vertexEntryPoint);
+ entryPoints.add(fragmentEntryPoint);
+
+ gfx::IShaderProgram::Desc programDesc = {};
+ programDesc.slangGlobalScope = composedProgram.get();
+ programDesc.linkingStyle = gfx::IShaderProgram::LinkingStyle::SeparateEntryPointCompilation;
+ programDesc.entryPointCount = 2;
+ programDesc.slangEntryPoints = entryPoints.getBuffer();
+
+ ComPtr<IShaderProgram> shaderProgram = device->createProgram(programDesc);
+
+ GraphicsPipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ pipelineDesc.inputLayout = inputLayout;
+ pipelineDesc.framebufferLayout = framebufferLayout;
+ pipelineDesc.depthStencil.depthTestEnable = false;
+ pipelineDesc.depthStencil.depthWriteEnable = false;
+ GFX_CHECK_CALL_ABORT(
+ device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
}
- SLANG_UNIT_TEST(shaderCacheGraphicsVulkan)
+ void runGraphicsPipeline()
{
- runTest<ShaderCacheTestGraphics>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ createGraphicsResources();
+ createGraphicsPipeline();
+ dispatchGraphicsPipeline();
+ freeGraphicsResources();
}
- SLANG_UNIT_TEST(shaderCacheGraphicsSplitD3D12)
+ void runTests()
{
- runTest<ShaderCacheTestGraphicsSplit>(unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ // Cache is cold and we expect 2 misses (2 entry points).
+ runStep(
+ [this]()
+ {
+ runGraphicsPipeline();
- SLANG_UNIT_TEST(shaderCacheGraphicsSplitVulkan)
- {
- runTest<ShaderCacheTestGraphicsSplit>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+ SLANG_CHECK(getStats().missCount == 2);
+ SLANG_CHECK(getStats().hitCount == 0);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
+
+ // Cache is hot and we expect 2 hits.
+ runStep(
+ [this]()
+ {
+ runGraphicsPipeline();
+
+ SLANG_CHECK(getStats().missCount == 0);
+ SLANG_CHECK(getStats().hitCount == 2);
+ SLANG_CHECK(getStats().entryCount == 2);
+ });
}
+};
+
+template<typename T>
+void runTest(UnitTestContext* context, Slang::RenderApiFlag::Enum api)
+{
+ T test;
+ test.run(context, api);
+}
+
+SLANG_UNIT_TEST(shaderCacheSourceFileD3D12)
+{
+ runTest<ShaderCacheSourceFile>(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(shaderCacheSourceFileVulkan)
+{
+ runTest<ShaderCacheSourceFile>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(shaderCacheSourceStringD3D12)
+{
+ runTest<ShaderCacheTestSourceString>(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(shaderCacheSourceStringVulkan)
+{
+ runTest<ShaderCacheTestSourceString>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(shaderCacheEntryPointD3D12)
+{
+ runTest<ShaderCacheTestEntryPoint>(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(shaderCacheEntryPointVulkan)
+{
+ runTest<ShaderCacheTestEntryPoint>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(shaderCacheImportIncludeD3D12)
+{
+ runTest<ShaderCacheTestImportInclude>(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(shaderCacheImportIncludeVulkan)
+{
+ runTest<ShaderCacheTestImportInclude>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(shaderCacheSpecializationD3D12)
+{
+ runTest<ShaderCacheTestSpecialization>(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(shaderCacheSpecializationVulkan)
+{
+ runTest<ShaderCacheTestSpecialization>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(shaderCacheEvictionD3D12)
+{
+ runTest<ShaderCacheTestEviction>(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(shaderCacheEvictionVulkan)
+{
+ runTest<ShaderCacheTestEviction>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(shaderCacheGraphicsD3D12)
+{
+ runTest<ShaderCacheTestGraphics>(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(shaderCacheGraphicsVulkan)
+{
+ runTest<ShaderCacheTestGraphics>(unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(shaderCacheGraphicsSplitD3D12)
+{
+ runTest<ShaderCacheTestGraphicsSplit>(unitTestContext, Slang::RenderApiFlag::D3D12);
+}
+
+SLANG_UNIT_TEST(shaderCacheGraphicsSplitVulkan)
+{
+ runTest<ShaderCacheTestGraphicsSplit>(unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/shared-buffers-tests.cpp b/tools/gfx-unit-test/shared-buffers-tests.cpp
index ccd223fc0..4355dda99 100644
--- a/tools/gfx-unit-test/shared-buffers-tests.cpp
+++ b/tools/gfx-unit-test/shared-buffers-tests.cpp
@@ -1,124 +1,128 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void sharedBufferTestImpl(IDevice* srcDevice, IDevice* dstDevice, UnitTestContext* context)
+void sharedBufferTestImpl(IDevice* srcDevice, IDevice* dstDevice, UnitTestContext* context)
+{
+ // Create a shareable buffer using srcDevice, get its handle, then create a buffer using the
+ // handle using dstDevice. Read back the buffer and check that its contents are correct.
+ const int numberCount = 4;
+ float initialData[] = {0.0f, 1.0f, 2.0f, 3.0f};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(float);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(float);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+ bufferDesc.isShared = true;
+
+ ComPtr<IBufferResource> srcBuffer;
+ GFX_CHECK_CALL_ABORT(
+ srcDevice->createBufferResource(bufferDesc, (void*)initialData, srcBuffer.writeRef()));
+
+ InteropHandle sharedHandle;
+ GFX_CHECK_CALL_ABORT(srcBuffer->getSharedHandle(&sharedHandle));
+ ComPtr<IBufferResource> dstBuffer;
+ GFX_CHECK_CALL_ABORT(
+ dstDevice->createBufferFromSharedHandle(sharedHandle, bufferDesc, dstBuffer.writeRef()));
+ // Reading back the buffer from srcDevice to make sure it's been filled in before reading
+ // anything back from dstDevice
+ // TODO: Implement actual synchronization (and not this hacky solution)
+ compareComputeResult(srcDevice, srcBuffer, Slang::makeArray<float>(0.0f, 1.0f, 2.0f, 3.0f));
+
+ InteropHandle testHandle;
+ GFX_CHECK_CALL_ABORT(dstBuffer->getNativeResourceHandle(&testHandle));
+ IBufferResource::Desc* testDesc = dstBuffer->getDesc();
+ SLANG_CHECK(testDesc->elementSize == sizeof(float));
+ SLANG_CHECK(testDesc->sizeInBytes == numberCount * sizeof(float));
+ compareComputeResult(dstDevice, dstBuffer, Slang::makeArray<float>(0.0f, 1.0f, 2.0f, 3.0f));
+
+ // Check that dstBuffer can be successfully used in a compute dispatch using dstDevice.
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ dstDevice->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ dstDevice,
+ shaderProgram,
+ "compute-trivial",
+ "computeMain",
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ dstDevice->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ dstDevice->createBufferView(dstBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
{
- // Create a shareable buffer using srcDevice, get its handle, then create a buffer using the handle using
- // dstDevice. Read back the buffer and check that its contents are correct.
- const int numberCount = 4;
- float initialData[] = { 0.0f, 1.0f, 2.0f, 3.0f };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(float);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(float);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
- bufferDesc.isShared = true;
-
- ComPtr<IBufferResource> srcBuffer;
- GFX_CHECK_CALL_ABORT(srcDevice->createBufferResource(
- bufferDesc,
- (void*)initialData,
- srcBuffer.writeRef()));
-
- InteropHandle sharedHandle;
- GFX_CHECK_CALL_ABORT(srcBuffer->getSharedHandle(&sharedHandle));
- ComPtr<IBufferResource> dstBuffer;
- GFX_CHECK_CALL_ABORT(dstDevice->createBufferFromSharedHandle(sharedHandle, bufferDesc, dstBuffer.writeRef()));
- // Reading back the buffer from srcDevice to make sure it's been filled in before reading anything back from dstDevice
- // TODO: Implement actual synchronization (and not this hacky solution)
- compareComputeResult(srcDevice, srcBuffer, Slang::makeArray<float>(0.0f, 1.0f, 2.0f, 3.0f));
-
- InteropHandle testHandle;
- GFX_CHECK_CALL_ABORT(dstBuffer->getNativeResourceHandle(&testHandle));
- IBufferResource::Desc* testDesc = dstBuffer->getDesc();
- SLANG_CHECK(testDesc->elementSize == sizeof(float));
- SLANG_CHECK(testDesc->sizeInBytes == numberCount * sizeof(float));
- compareComputeResult(dstDevice, dstBuffer, Slang::makeArray<float>(0.0f, 1.0f, 2.0f, 3.0f));
-
- // Check that dstBuffer can be successfully used in a compute dispatch using dstDevice.
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- dstDevice->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(dstDevice, shaderProgram, "compute-trivial", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- dstDevice->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- dstDevice->createBufferView(dstBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = dstDevice->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor rootCursor(rootObject);
- // Bind buffer view to the entry point.
- rootCursor.getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- dstDevice,
- dstBuffer,
- Slang::makeArray<float>(1.0f, 2.0f, 3.0f, 4.0f));
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = dstDevice->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
+
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ ShaderCursor rootCursor(rootObject);
+ // Bind buffer view to the entry point.
+ rootCursor.getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
- void sharedBufferTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum srcApi, Slang::RenderApiFlag::Enum dstApi)
+ compareComputeResult(dstDevice, dstBuffer, Slang::makeArray<float>(1.0f, 2.0f, 3.0f, 4.0f));
+}
+
+void sharedBufferTestAPI(
+ UnitTestContext* context,
+ Slang::RenderApiFlag::Enum srcApi,
+ Slang::RenderApiFlag::Enum dstApi)
+{
+ auto srcDevice = createTestingDevice(context, srcApi);
+ auto dstDevice = createTestingDevice(context, dstApi);
+ if (!srcDevice || !dstDevice)
{
- auto srcDevice = createTestingDevice(context, srcApi);
- auto dstDevice = createTestingDevice(context, dstApi);
- if (!srcDevice || !dstDevice)
- {
- SLANG_IGNORE_TEST;
- }
-
- sharedBufferTestImpl(srcDevice, dstDevice, context);
+ SLANG_IGNORE_TEST;
}
+
+ sharedBufferTestImpl(srcDevice, dstDevice, context);
+}
#if SLANG_WIN64
- SLANG_UNIT_TEST(sharedBufferD3D12ToCUDA)
- {
- sharedBufferTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12, Slang::RenderApiFlag::CUDA);
- }
+SLANG_UNIT_TEST(sharedBufferD3D12ToCUDA)
+{
+ sharedBufferTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12, Slang::RenderApiFlag::CUDA);
+}
- SLANG_UNIT_TEST(sharedBufferVulkanToCUDA)
- {
- sharedBufferTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan, Slang::RenderApiFlag::CUDA);
- }
-#endif
+SLANG_UNIT_TEST(sharedBufferVulkanToCUDA)
+{
+ sharedBufferTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan, Slang::RenderApiFlag::CUDA);
}
+#endif
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/shared-textures-tests.cpp b/tools/gfx-unit-test/shared-textures-tests.cpp
index 4afa23546..ee8108c39 100644
--- a/tools/gfx-unit-test/shared-textures-tests.cpp
+++ b/tools/gfx-unit-test/shared-textures-tests.cpp
@@ -1,223 +1,261 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void setUpAndRunShader(
- IDevice* device,
- ComPtr<ITextureResource> tex,
- ComPtr<IResourceView> texView,
- ComPtr<IResourceView> bufferView,
- const char* entryPoint,
- ComPtr<ISamplerState> sampler = nullptr)
+void setUpAndRunShader(
+ IDevice* device,
+ ComPtr<ITextureResource> tex,
+ ComPtr<IResourceView> texView,
+ ComPtr<IResourceView> bufferView,
+ const char* entryPoint,
+ ComPtr<ISamplerState> sampler = nullptr)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(
+ loadComputeProgram(device, shaderProgram, "trivial-copy", entryPoint, slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "trivial-copy", entryPoint, slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
-
- auto& desc = *tex->getDesc();
- entryPointCursor["width"].setData(desc.size.width);
- entryPointCursor["height"].setData(desc.size.height);
-
- // Bind texture view to the entry point
- entryPointCursor["tex"].setResource(texView);
-
- if (sampler) entryPointCursor["sampler"].setSampler(sampler);
-
- // Bind buffer view to the entry point.
- entryPointCursor["buffer"].setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
- }
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- ComPtr<ITextureResource> createTexture(IDevice* device, ITextureResource::Extents extents, gfx::Format format, ITextureResource::SubresourceData* initialData)
- {
- ITextureResource::Desc texDesc = {};
- texDesc.type = IResource::Type::Texture2D;
- texDesc.numMipLevels = 1;
- texDesc.arraySize = 1;
- texDesc.size = extents;
- texDesc.defaultState = ResourceState::UnorderedAccess;
- texDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- texDesc.format = format;
- texDesc.isShared = true;
-
- ComPtr<ITextureResource> inTex;
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- texDesc,
- initialData,
- inTex.writeRef()));
- return inTex;
- }
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- ComPtr<IResourceView> createTexView(IDevice* device, ComPtr<ITextureResource> inTexture)
- {
- ComPtr<IResourceView> texView;
- IResourceView::Desc texViewDesc = {};
- texViewDesc.type = IResourceView::Type::UnorderedAccess;
- texViewDesc.format = inTexture->getDesc()->format; // TODO: Handle typeless formats - gfxIsTypelessFormat(format) ? convertTypelessFormat(format) : format;
- GFX_CHECK_CALL_ABORT(device->createTextureView(inTexture, texViewDesc, texView.writeRef()));
- return texView;
- }
+ auto rootObject = encoder->bindPipeline(pipelineState);
- template <typename T>
- ComPtr<IBufferResource> createBuffer(IDevice* device, int size, void* initialData)
- {
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = size * sizeof(T);
- bufferDesc.format = gfx::Format::Unknown;
- bufferDesc.elementSize = sizeof(T);
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> outBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- initialData,
- outBuffer.writeRef()));
- return outBuffer;
- }
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- ComPtr<IResourceView> createOutBufferView(IDevice* device, ComPtr<IBufferResource> outBuffer)
- {
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(outBuffer, nullptr, viewDesc, bufferView.writeRef()));
- return bufferView;
+ auto& desc = *tex->getDesc();
+ entryPointCursor["width"].setData(desc.size.width);
+ entryPointCursor["height"].setData(desc.size.height);
+
+ // Bind texture view to the entry point
+ entryPointCursor["tex"].setResource(texView);
+
+ if (sampler)
+ entryPointCursor["sampler"].setSampler(sampler);
+
+ // Bind buffer view to the entry point.
+ entryPointCursor["buffer"].setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+}
+
+ComPtr<ITextureResource> createTexture(
+ IDevice* device,
+ ITextureResource::Extents extents,
+ gfx::Format format,
+ ITextureResource::SubresourceData* initialData)
+{
+ ITextureResource::Desc texDesc = {};
+ texDesc.type = IResource::Type::Texture2D;
+ texDesc.numMipLevels = 1;
+ texDesc.arraySize = 1;
+ texDesc.size = extents;
+ texDesc.defaultState = ResourceState::UnorderedAccess;
+ texDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ texDesc.format = format;
+ texDesc.isShared = true;
+
+ ComPtr<ITextureResource> inTex;
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(texDesc, initialData, inTex.writeRef()));
+ return inTex;
+}
+
+ComPtr<IResourceView> createTexView(IDevice* device, ComPtr<ITextureResource> inTexture)
+{
+ ComPtr<IResourceView> texView;
+ IResourceView::Desc texViewDesc = {};
+ texViewDesc.type = IResourceView::Type::UnorderedAccess;
+ texViewDesc.format =
+ inTexture->getDesc()->format; // TODO: Handle typeless formats - gfxIsTypelessFormat(format)
+ // ? convertTypelessFormat(format) : format;
+ GFX_CHECK_CALL_ABORT(device->createTextureView(inTexture, texViewDesc, texView.writeRef()));
+ return texView;
+}
+
+template<typename T>
+ComPtr<IBufferResource> createBuffer(IDevice* device, int size, void* initialData)
+{
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = size * sizeof(T);
+ bufferDesc.format = gfx::Format::Unknown;
+ bufferDesc.elementSize = sizeof(T);
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> outBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, initialData, outBuffer.writeRef()));
+ return outBuffer;
+}
+
+ComPtr<IResourceView> createOutBufferView(IDevice* device, ComPtr<IBufferResource> outBuffer)
+{
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(outBuffer, nullptr, viewDesc, bufferView.writeRef()));
+ return bufferView;
+}
+
+void sharedTextureTestImpl(IDevice* srcDevice, IDevice* dstDevice, UnitTestContext* context)
+{
+ ISamplerState::Desc samplerDesc;
+ auto sampler = dstDevice->createSamplerState(samplerDesc);
+
+ float initFloatData[16] = {0.0f};
+ auto floatResults = createBuffer<float>(dstDevice, 16, initFloatData);
+ auto floatBufferView = createOutBufferView(dstDevice, floatResults);
+
+ uint32_t initUintData[16] = {0u};
+ auto uintResults = createBuffer<uint32_t>(dstDevice, 16, initUintData);
+ auto uintBufferView = createOutBufferView(dstDevice, uintResults);
+
+ int32_t initIntData[16] = {0};
+ auto intResults = createBuffer<uint32_t>(dstDevice, 16, initIntData);
+ auto intBufferView = createOutBufferView(dstDevice, intResults);
+
+ ITextureResource::Extents size = {};
+ size.width = 2;
+ size.height = 2;
+ size.depth = 1;
+
+ ITextureResource::Extents bcSize = {};
+ bcSize.width = 4;
+ bcSize.height = 4;
+ bcSize.depth = 1;
- void sharedTextureTestImpl(IDevice* srcDevice, IDevice* dstDevice, UnitTestContext* context)
{
- ISamplerState::Desc samplerDesc;
- auto sampler = dstDevice->createSamplerState(samplerDesc);
-
- float initFloatData[16] = { 0.0f };
- auto floatResults = createBuffer<float>(dstDevice, 16, initFloatData);
- auto floatBufferView = createOutBufferView(dstDevice, floatResults);
-
- uint32_t initUintData[16] = { 0u };
- auto uintResults = createBuffer<uint32_t>(dstDevice, 16, initUintData);
- auto uintBufferView = createOutBufferView(dstDevice, uintResults);
-
- int32_t initIntData[16] = { 0 };
- auto intResults = createBuffer<uint32_t>(dstDevice, 16, initIntData);
- auto intBufferView = createOutBufferView(dstDevice, intResults);
-
- ITextureResource::Extents size = {};
- size.width = 2;
- size.height = 2;
- size.depth = 1;
-
- ITextureResource::Extents bcSize = {};
- bcSize.width = 4;
- bcSize.height = 4;
- bcSize.depth = 1;
-
- {
- float texData[] = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f };
- ITextureResource::SubresourceData subData = { (void*)texData, 32, 0 };
-
- // Create a shareable texture using srcDevice, get its handle, then create a texture using the handle using
- // dstDevice. Read back the texture and check that its contents are correct.
- auto srcTexture = createTexture(srcDevice, size, gfx::Format::R32G32B32A32_FLOAT, &subData);
-
- InteropHandle sharedHandle;
- GFX_CHECK_CALL_ABORT(srcTexture->getSharedHandle(&sharedHandle));
- ComPtr<ITextureResource> dstTexture;
- size_t sizeInBytes = 0;
- size_t alignment = 0;
- GFX_CHECK_CALL_ABORT(srcDevice->getTextureAllocationInfo(*(srcTexture->getDesc()), &sizeInBytes, &alignment));
- GFX_CHECK_CALL_ABORT(dstDevice->createTextureFromSharedHandle(sharedHandle, *(srcTexture->getDesc()), sizeInBytes, dstTexture.writeRef()));
- // Reading back the buffer from srcDevice to make sure it's been filled in before reading anything back from dstDevice
- // TODO: Implement actual synchronization (and not this hacky solution)
- compareComputeResult(
- dstDevice,
- dstTexture,
- ResourceState::ShaderResource,
- texData,
- 32,
- 2);
-
- auto texView = createTexView(dstDevice, dstTexture);
- setUpAndRunShader(dstDevice, dstTexture, texView, floatBufferView, "copyTexFloat4");
- compareComputeResult(
- dstDevice,
- floatResults,
- Slang::makeArray<float>(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f,
- 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f));
- }
+ float texData[] = {
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.5f,
+ 0.5f,
+ 0.5f,
+ 1.0f};
+ ITextureResource::SubresourceData subData = {(void*)texData, 32, 0};
+
+ // Create a shareable texture using srcDevice, get its handle, then create a texture using
+ // the handle using dstDevice. Read back the texture and check that its contents are
+ // correct.
+ auto srcTexture = createTexture(srcDevice, size, gfx::Format::R32G32B32A32_FLOAT, &subData);
+
+ InteropHandle sharedHandle;
+ GFX_CHECK_CALL_ABORT(srcTexture->getSharedHandle(&sharedHandle));
+ ComPtr<ITextureResource> dstTexture;
+ size_t sizeInBytes = 0;
+ size_t alignment = 0;
+ GFX_CHECK_CALL_ABORT(srcDevice->getTextureAllocationInfo(
+ *(srcTexture->getDesc()),
+ &sizeInBytes,
+ &alignment));
+ GFX_CHECK_CALL_ABORT(dstDevice->createTextureFromSharedHandle(
+ sharedHandle,
+ *(srcTexture->getDesc()),
+ sizeInBytes,
+ dstTexture.writeRef()));
+ // Reading back the buffer from srcDevice to make sure it's been filled in before reading
+ // anything back from dstDevice
+ // TODO: Implement actual synchronization (and not this hacky solution)
+ compareComputeResult(dstDevice, dstTexture, ResourceState::ShaderResource, texData, 32, 2);
+
+ auto texView = createTexView(dstDevice, dstTexture);
+ setUpAndRunShader(dstDevice, dstTexture, texView, floatBufferView, "copyTexFloat4");
+ compareComputeResult(
+ dstDevice,
+ floatResults,
+ Slang::makeArray<float>(
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 1.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 0.5f,
+ 0.5f,
+ 0.5f,
+ 1.0f));
}
+}
- void sharedTextureTestAPI(UnitTestContext* context, Slang::RenderApiFlag::Enum srcApi, Slang::RenderApiFlag::Enum dstApi)
+void sharedTextureTestAPI(
+ UnitTestContext* context,
+ Slang::RenderApiFlag::Enum srcApi,
+ Slang::RenderApiFlag::Enum dstApi)
+{
+ auto srcDevice = createTestingDevice(context, srcApi);
+ auto dstDevice = createTestingDevice(context, dstApi);
+ if (!srcDevice || !dstDevice)
{
- auto srcDevice = createTestingDevice(context, srcApi);
- auto dstDevice = createTestingDevice(context, dstApi);
- if (!srcDevice || !dstDevice)
- {
- SLANG_IGNORE_TEST;
- }
-
- sharedTextureTestImpl(srcDevice, dstDevice, context);
+ SLANG_IGNORE_TEST;
}
+
+ sharedTextureTestImpl(srcDevice, dstDevice, context);
+}
#if SLANG_WIN64
- SLANG_UNIT_TEST(sharedTextureD3D12ToCUDA)
- {
- sharedTextureTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12, Slang::RenderApiFlag::CUDA);
- }
+SLANG_UNIT_TEST(sharedTextureD3D12ToCUDA)
+{
+ sharedTextureTestAPI(unitTestContext, Slang::RenderApiFlag::D3D12, Slang::RenderApiFlag::CUDA);
+}
- SLANG_UNIT_TEST(sharedTextureVulkanToCUDA)
- {
- sharedTextureTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan, Slang::RenderApiFlag::CUDA);
- }
-#endif
+SLANG_UNIT_TEST(sharedTextureVulkanToCUDA)
+{
+ sharedTextureTestAPI(unitTestContext, Slang::RenderApiFlag::Vulkan, Slang::RenderApiFlag::CUDA);
}
+#endif
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/swap-chain-resize-test.cpp b/tools/gfx-unit-test/swap-chain-resize-test.cpp
index 2be690077..269f08735 100644
--- a/tools/gfx-unit-test/swap-chain-resize-test.cpp
+++ b/tools/gfx-unit-test/swap-chain-resize-test.cpp
@@ -1,242 +1,249 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
+#include "slang-gfx.h"
+#include "source/core/slang-basic.h"
#include "tools/gfx-util/shader-cursor.h"
#include "tools/platform/window.h"
-#include "source/core/slang-basic.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
using namespace Slang;
namespace gfx_test
{
- struct Vertex
- {
- float position[3];
- };
-
- static const int kVertexCount = 3;
- static const Vertex kVertexData[kVertexCount] =
- {
- // Triangle 1
- { 0, 0, 1 },
- { 4, 0, 1 },
- { 0, 4, 1 },
- };
-
- struct SwapchainResizeTest
- {
- IDevice* device;
- UnitTestContext* context;
-
- RefPtr<platform::Window> window;
- ComPtr<ICommandQueue> queue;
- ComPtr<ISwapchain> swapchain;
+struct Vertex
+{
+ float position[3];
+};
+
+static const int kVertexCount = 3;
+static const Vertex kVertexData[kVertexCount] = {
+ // Triangle 1
+ {0, 0, 1},
+ {4, 0, 1},
+ {0, 4, 1},
+};
+
+struct SwapchainResizeTest
+{
+ IDevice* device;
+ UnitTestContext* context;
- ComPtr<ITransientResourceHeap> transientHeap;
- ComPtr<gfx::IFramebufferLayout> framebufferLayout;
- ComPtr<IPipelineState> pipelineState;
- ComPtr<IRenderPassLayout> renderPass;
- List<ComPtr<IFramebuffer>> framebuffers;
+ RefPtr<platform::Window> window;
+ ComPtr<ICommandQueue> queue;
+ ComPtr<ISwapchain> swapchain;
- ComPtr<IBufferResource> vertexBuffer;
+ ComPtr<ITransientResourceHeap> transientHeap;
+ ComPtr<gfx::IFramebufferLayout> framebufferLayout;
+ ComPtr<IPipelineState> pipelineState;
+ ComPtr<IRenderPassLayout> renderPass;
+ List<ComPtr<IFramebuffer>> framebuffers;
- GfxCount width = 500;
- GfxCount height = 500;
- static const int kSwapchainImageCount = 2;
- const Format desiredFormat = Format::R8G8B8A8_UNORM;
+ ComPtr<IBufferResource> vertexBuffer;
- void init(IDevice* device, UnitTestContext* context)
- {
- this->device = device;
- this->context = context;
- }
+ GfxCount width = 500;
+ GfxCount height = 500;
+ static const int kSwapchainImageCount = 2;
+ const Format desiredFormat = Format::R8G8B8A8_UNORM;
- void createSwapchainFramebuffers()
- {
- framebuffers.clear();
- for (GfxIndex i = 0; i < kSwapchainImageCount; ++i)
- {
- ComPtr<ITextureResource> colorBuffer;
- swapchain->getImage(i, colorBuffer.writeRef());
-
- gfx::IResourceView::Desc colorBufferViewDesc;
- memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
- colorBufferViewDesc.format = swapchain->getDesc().format;
- colorBufferViewDesc.renderTarget.shape = gfx::IResource::Type::Texture2D;
- colorBufferViewDesc.type = gfx::IResourceView::Type::RenderTarget;
- auto rtv = device->createTextureView(colorBuffer.get(), colorBufferViewDesc);
-
- gfx::IFramebuffer::Desc framebufferDesc;
- framebufferDesc.renderTargetCount = 1;
- framebufferDesc.depthStencilView = nullptr;
- framebufferDesc.renderTargetViews = rtv.readRef();
- framebufferDesc.layout = framebufferLayout;
- ComPtr<IFramebuffer> framebuffer;
- GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
-
- framebuffers.add(framebuffer);
- }
- }
+ void init(IDevice* device, UnitTestContext* context)
+ {
+ this->device = device;
+ this->context = context;
+ }
- void createRequiredResources()
+ void createSwapchainFramebuffers()
+ {
+ framebuffers.clear();
+ for (GfxIndex i = 0; i < kSwapchainImageCount; ++i)
{
- platform::Application::init();
-
- platform::WindowDesc windowDesc;
- windowDesc.title = "";
- windowDesc.width = width;
- windowDesc.height = height;
- windowDesc.style = platform::WindowStyle::Default;
- window = platform::Application::createWindow(windowDesc);
-
- ICommandQueue::Desc queueDesc = {};
- queueDesc.type = ICommandQueue::QueueType::Graphics;
- queue = device->createCommandQueue(queueDesc);
-
- ISwapchain::Desc swapchainDesc = {};
- swapchainDesc.format = desiredFormat;
- swapchainDesc.width = width;
- swapchainDesc.height = height;
- swapchainDesc.imageCount = kSwapchainImageCount;
- swapchainDesc.queue = queue;
- WindowHandle windowHandle = window->getNativeHandle().convert<WindowHandle>();
- auto createSwapchainResult = device->createSwapchain(swapchainDesc, windowHandle, swapchain.writeRef());
- if (SLANG_FAILED(createSwapchainResult))
- {
- SLANG_IGNORE_TEST;
- }
-
- VertexStreamDesc vertexStreams[] = {
- { sizeof(Vertex), InputSlotClass::PerVertex, 0 },
- };
-
- InputElementDesc inputElements[] = {
- // Vertex buffer data
- { "POSITIONA", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0 },
- };
- IInputLayout::Desc inputLayoutDesc = {};
- inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
- inputLayoutDesc.inputElements = inputElements;
- inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
- inputLayoutDesc.vertexStreams = vertexStreams;
- auto inputLayout = device->createInputLayout(inputLayoutDesc);
- SLANG_CHECK_ABORT(inputLayout != nullptr);
-
- IBufferResource::Desc vertexBufferDesc;
- vertexBufferDesc.type = IResource::Type::Buffer;
- vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
- vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
- vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
- SLANG_CHECK_ABORT(vertexBuffer != nullptr);
-
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096 * 1024;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadGraphicsProgram(device, shaderProgram, "swapchain-shader", "vertexMain", "fragmentMain", slangReflection));
-
- IFramebufferLayout::TargetLayout targetLayout;
- targetLayout.format = swapchain->getDesc().format;
- targetLayout.sampleCount = 1;
-
- IFramebufferLayout::Desc framebufferLayoutDesc;
- framebufferLayoutDesc.renderTargetCount = 1;
- framebufferLayoutDesc.renderTargets = &targetLayout;
- framebufferLayout = device->createFramebufferLayout(framebufferLayoutDesc);
- SLANG_CHECK_ABORT(framebufferLayout != nullptr);
-
- GraphicsPipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- pipelineDesc.inputLayout = inputLayout;
- pipelineDesc.framebufferLayout = framebufferLayout;
- pipelineDesc.depthStencil.depthTestEnable = false;
- pipelineDesc.depthStencil.depthWriteEnable = false;
+ ComPtr<ITextureResource> colorBuffer;
+ swapchain->getImage(i, colorBuffer.writeRef());
+
+ gfx::IResourceView::Desc colorBufferViewDesc;
+ memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
+ colorBufferViewDesc.format = swapchain->getDesc().format;
+ colorBufferViewDesc.renderTarget.shape = gfx::IResource::Type::Texture2D;
+ colorBufferViewDesc.type = gfx::IResourceView::Type::RenderTarget;
+ auto rtv = device->createTextureView(colorBuffer.get(), colorBufferViewDesc);
+
+ gfx::IFramebuffer::Desc framebufferDesc;
+ framebufferDesc.renderTargetCount = 1;
+ framebufferDesc.depthStencilView = nullptr;
+ framebufferDesc.renderTargetViews = rtv.readRef();
+ framebufferDesc.layout = framebufferLayout;
+ ComPtr<IFramebuffer> framebuffer;
GFX_CHECK_CALL_ABORT(
- device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
-
- IRenderPassLayout::Desc renderPassDesc = {};
- renderPassDesc.framebufferLayout = framebufferLayout;
- renderPassDesc.renderTargetCount = 1;
- IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
- renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
- renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
- renderTargetAccess.initialState = ResourceState::Undefined;
- renderTargetAccess.finalState = ResourceState::Present;
- renderPassDesc.renderTargetAccess = &renderTargetAccess;
- GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
-
- createSwapchainFramebuffers();
- }
+ device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
- void renderFrame(GfxIndex framebufferIndex)
- {
- auto commandBuffer = transientHeap->createCommandBuffer();
-
- auto encoder = commandBuffer->encodeRenderCommands(renderPass, framebuffers[framebufferIndex]);
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- gfx::Viewport viewport = {};
- viewport.maxZ = 1.0f;
- viewport.extentX = (float)width;
- viewport.extentY = (float)height;
- encoder->setViewportAndScissor(viewport);
-
- encoder->setVertexBuffer(0, vertexBuffer);
- encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
-
- swapchain->acquireNextImage();
- encoder->draw(kVertexCount);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- swapchain->present();
+ framebuffers.add(framebuffer);
}
+ }
- void run()
+ void createRequiredResources()
+ {
+ platform::Application::init();
+
+ platform::WindowDesc windowDesc;
+ windowDesc.title = "";
+ windowDesc.width = width;
+ windowDesc.height = height;
+ windowDesc.style = platform::WindowStyle::Default;
+ window = platform::Application::createWindow(windowDesc);
+
+ ICommandQueue::Desc queueDesc = {};
+ queueDesc.type = ICommandQueue::QueueType::Graphics;
+ queue = device->createCommandQueue(queueDesc);
+
+ ISwapchain::Desc swapchainDesc = {};
+ swapchainDesc.format = desiredFormat;
+ swapchainDesc.width = width;
+ swapchainDesc.height = height;
+ swapchainDesc.imageCount = kSwapchainImageCount;
+ swapchainDesc.queue = queue;
+ WindowHandle windowHandle = window->getNativeHandle().convert<WindowHandle>();
+ auto createSwapchainResult =
+ device->createSwapchain(swapchainDesc, windowHandle, swapchain.writeRef());
+ if (SLANG_FAILED(createSwapchainResult))
{
- createRequiredResources();
- // Render for 5 frames then resize the swapchain and render for another 5 frames to ensure the
- // swapchain remains usable after resizing.
- for (GfxIndex i = 0; i < 5; ++i)
- {
- renderFrame(i % kSwapchainImageCount);
- }
- queue->waitOnHost();
-
- framebuffers = decltype(framebuffers)();
- GFX_CHECK_CALL(swapchain->resize(700, 700));
- createSwapchainFramebuffers();
- width = 700;
- height = 700;
-
- for (GfxIndex i = 0; i < 5; ++i)
- {
- renderFrame(i % kSwapchainImageCount);
- }
- queue->waitOnHost();
+ SLANG_IGNORE_TEST;
}
- };
- void swapchainResizeTestImpl(IDevice* device, UnitTestContext* context)
- {
- SwapchainResizeTest t;
- t.init(device, context);
- t.run();
+ VertexStreamDesc vertexStreams[] = {
+ {sizeof(Vertex), InputSlotClass::PerVertex, 0},
+ };
+
+ InputElementDesc inputElements[] = {
+ // Vertex buffer data
+ {"POSITIONA", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0},
+ };
+ IInputLayout::Desc inputLayoutDesc = {};
+ inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
+ inputLayoutDesc.inputElements = inputElements;
+ inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
+ inputLayoutDesc.vertexStreams = vertexStreams;
+ auto inputLayout = device->createInputLayout(inputLayoutDesc);
+ SLANG_CHECK_ABORT(inputLayout != nullptr);
+
+ IBufferResource::Desc vertexBufferDesc;
+ vertexBufferDesc.type = IResource::Type::Buffer;
+ vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
+ vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
+ vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
+ SLANG_CHECK_ABORT(vertexBuffer != nullptr);
+
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096 * 1024;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadGraphicsProgram(
+ device,
+ shaderProgram,
+ "swapchain-shader",
+ "vertexMain",
+ "fragmentMain",
+ slangReflection));
+
+ IFramebufferLayout::TargetLayout targetLayout;
+ targetLayout.format = swapchain->getDesc().format;
+ targetLayout.sampleCount = 1;
+
+ IFramebufferLayout::Desc framebufferLayoutDesc;
+ framebufferLayoutDesc.renderTargetCount = 1;
+ framebufferLayoutDesc.renderTargets = &targetLayout;
+ framebufferLayout = device->createFramebufferLayout(framebufferLayoutDesc);
+ SLANG_CHECK_ABORT(framebufferLayout != nullptr);
+
+ GraphicsPipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ pipelineDesc.inputLayout = inputLayout;
+ pipelineDesc.framebufferLayout = framebufferLayout;
+ pipelineDesc.depthStencil.depthTestEnable = false;
+ pipelineDesc.depthStencil.depthWriteEnable = false;
+ GFX_CHECK_CALL_ABORT(
+ device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ IRenderPassLayout::Desc renderPassDesc = {};
+ renderPassDesc.framebufferLayout = framebufferLayout;
+ renderPassDesc.renderTargetCount = 1;
+ IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
+ renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
+ renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
+ renderTargetAccess.initialState = ResourceState::Undefined;
+ renderTargetAccess.finalState = ResourceState::Present;
+ renderPassDesc.renderTargetAccess = &renderTargetAccess;
+ GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
+
+ createSwapchainFramebuffers();
}
- SLANG_UNIT_TEST(swapchainResizeD3D12)
+ void renderFrame(GfxIndex framebufferIndex)
{
- runTestImpl(swapchainResizeTestImpl, unitTestContext, RenderApiFlag::D3D12);
+ auto commandBuffer = transientHeap->createCommandBuffer();
+
+ auto encoder =
+ commandBuffer->encodeRenderCommands(renderPass, framebuffers[framebufferIndex]);
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ gfx::Viewport viewport = {};
+ viewport.maxZ = 1.0f;
+ viewport.extentX = (float)width;
+ viewport.extentY = (float)height;
+ encoder->setViewportAndScissor(viewport);
+
+ encoder->setVertexBuffer(0, vertexBuffer);
+ encoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
+
+ swapchain->acquireNextImage();
+ encoder->draw(kVertexCount);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ swapchain->present();
}
- SLANG_UNIT_TEST(swapchainResizeVulkan)
+ void run()
{
- runTestImpl(swapchainResizeTestImpl, unitTestContext, RenderApiFlag::Vulkan);
+ createRequiredResources();
+ // Render for 5 frames then resize the swapchain and render for another 5 frames to ensure
+ // the swapchain remains usable after resizing.
+ for (GfxIndex i = 0; i < 5; ++i)
+ {
+ renderFrame(i % kSwapchainImageCount);
+ }
+ queue->waitOnHost();
+
+ framebuffers = decltype(framebuffers)();
+ GFX_CHECK_CALL(swapchain->resize(700, 700));
+ createSwapchainFramebuffers();
+ width = 700;
+ height = 700;
+
+ for (GfxIndex i = 0; i < 5; ++i)
+ {
+ renderFrame(i % kSwapchainImageCount);
+ }
+ queue->waitOnHost();
}
+};
+
+void swapchainResizeTestImpl(IDevice* device, UnitTestContext* context)
+{
+ SwapchainResizeTest t;
+ t.init(device, context);
+ t.run();
+}
+SLANG_UNIT_TEST(swapchainResizeD3D12)
+{
+ runTestImpl(swapchainResizeTestImpl, unitTestContext, RenderApiFlag::D3D12);
}
+
+SLANG_UNIT_TEST(swapchainResizeVulkan)
+{
+ runTestImpl(swapchainResizeTestImpl, unitTestContext, RenderApiFlag::Vulkan);
+}
+
+} // namespace gfx_test
diff --git a/tools/gfx-unit-test/texture-types-tests.cpp b/tools/gfx-unit-test/texture-types-tests.cpp
index 7f010e6fd..0aa082a1e 100644
--- a/tools/gfx-unit-test/texture-types-tests.cpp
+++ b/tools/gfx-unit-test/texture-types-tests.cpp
@@ -1,10 +1,9 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
-#include "gfx-test-util.h"
#include "gfx-test-texture-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "gfx-test-util.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
#if SLANG_WINDOWS_FAMILY
#include <d3d12.h>
@@ -15,654 +14,688 @@ using namespace gfx;
namespace gfx_test
{
- struct BaseTextureViewTest
- {
- IDevice* device;
- UnitTestContext* context;
+struct BaseTextureViewTest
+{
+ IDevice* device;
+ UnitTestContext* context;
- IResourceView::Type viewType;
- size_t alignedRowStride;
+ IResourceView::Type viewType;
+ size_t alignedRowStride;
- RefPtr<TextureInfo> textureInfo;
- RefPtr<ValidationTextureFormatBase> validationFormat;
+ RefPtr<TextureInfo> textureInfo;
+ RefPtr<ValidationTextureFormatBase> validationFormat;
- ComPtr<ITextureResource> texture;
- ComPtr<IResourceView> textureView;
- ComPtr<IBufferResource> resultsBuffer;
- ComPtr<IResourceView> bufferView;
+ ComPtr<ITextureResource> texture;
+ ComPtr<IResourceView> textureView;
+ ComPtr<IBufferResource> resultsBuffer;
+ ComPtr<IResourceView> bufferView;
- ComPtr<ISamplerState> sampler;
+ ComPtr<ISamplerState> sampler;
- const void* expectedTextureData;
+ const void* expectedTextureData;
- void init(
- IDevice* device,
- UnitTestContext* context,
- Format format,
- RefPtr<ValidationTextureFormatBase> validationFormat,
- IResourceView::Type viewType,
- IResource::Type type)
+ void init(
+ IDevice* device,
+ UnitTestContext* context,
+ Format format,
+ RefPtr<ValidationTextureFormatBase> validationFormat,
+ IResourceView::Type viewType,
+ IResource::Type type)
+ {
+ this->device = device;
+ this->context = context;
+ this->validationFormat = validationFormat;
+ this->viewType = viewType;
+
+ this->textureInfo = new TextureInfo();
+ this->textureInfo->format = format;
+ this->textureInfo->textureType = type;
+ }
+
+ ResourceState getDefaultResourceStateForViewType(IResourceView::Type type)
+ {
+ switch (type)
{
- this->device = device;
- this->context = context;
- this->validationFormat = validationFormat;
- this->viewType = viewType;
-
- this->textureInfo = new TextureInfo();
- this->textureInfo->format = format;
- this->textureInfo->textureType = type;
+ case IResourceView::Type::RenderTarget: return ResourceState::RenderTarget;
+ case IResourceView::Type::DepthStencil: return ResourceState::DepthWrite;
+ case IResourceView::Type::ShaderResource: return ResourceState::ShaderResource;
+ case IResourceView::Type::UnorderedAccess: return ResourceState::UnorderedAccess;
+ case IResourceView::Type::AccelerationStructure:
+ return ResourceState::AccelerationStructure;
+ default: return ResourceState::Undefined;
}
+ }
+
+ String getShaderEntryPoint()
+ {
+ String base = "resourceViewTest";
+ String shape;
+ String view;
- ResourceState getDefaultResourceStateForViewType(IResourceView::Type type)
+ switch (textureInfo->textureType)
{
- switch (type)
- {
- case IResourceView::Type::RenderTarget:
- return ResourceState::RenderTarget;
- case IResourceView::Type::DepthStencil:
- return ResourceState::DepthWrite;
- case IResourceView::Type::ShaderResource:
- return ResourceState::ShaderResource;
- case IResourceView::Type::UnorderedAccess:
- return ResourceState::UnorderedAccess;
- case IResourceView::Type::AccelerationStructure:
- return ResourceState::AccelerationStructure;
- default:
- return ResourceState::Undefined;
- }
+ case IResource::Type::Texture1D: shape = "1D"; break;
+ case IResource::Type::Texture2D: shape = "2D"; break;
+ case IResource::Type::Texture3D: shape = "3D"; break;
+ case IResource::Type::TextureCube: shape = "Cube"; break;
+ default: assert(!"Invalid texture shape"); SLANG_CHECK_ABORT(false);
}
- String getShaderEntryPoint()
+ switch (viewType)
{
- String base = "resourceViewTest";
- String shape;
- String view;
-
- switch (textureInfo->textureType)
- {
- case IResource::Type::Texture1D:
- shape = "1D";
- break;
- case IResource::Type::Texture2D:
- shape = "2D";
- break;
- case IResource::Type::Texture3D:
- shape = "3D";
- break;
- case IResource::Type::TextureCube:
- shape = "Cube";
- break;
- default:
- assert(!"Invalid texture shape");
- SLANG_CHECK_ABORT(false);
- }
-
- switch (viewType)
- {
- case IResourceView::Type::RenderTarget:
- view = "Render";
- break;
- case IResourceView::Type::DepthStencil:
- view = "Depth";
- break;
- case IResourceView::Type::ShaderResource:
- view = "Shader";
- break;
- case IResourceView::Type::UnorderedAccess:
- view = "Unordered";
- break;
- case IResourceView::Type::AccelerationStructure:
- view = "Accel";
- break;
- default:
- assert(!"Invalid resource view");
- SLANG_CHECK_ABORT(false);
- }
-
- return base + shape + view;
+ case IResourceView::Type::RenderTarget: view = "Render"; break;
+ case IResourceView::Type::DepthStencil: view = "Depth"; break;
+ case IResourceView::Type::ShaderResource: view = "Shader"; break;
+ case IResourceView::Type::UnorderedAccess: view = "Unordered"; break;
+ case IResourceView::Type::AccelerationStructure: view = "Accel"; break;
+ default: assert(!"Invalid resource view"); SLANG_CHECK_ABORT(false);
}
-
- };
+ return base + shape + view;
+ }
+};
- // used for shaderresource and unorderedaccess
- struct ShaderAndUnorderedTests : BaseTextureViewTest
+// used for shaderresource and unorderedaccess
+struct ShaderAndUnorderedTests : BaseTextureViewTest
+{
+ void createRequiredResources()
{
- void createRequiredResources()
- {
- ITextureResource::Desc textureDesc = {};
- textureDesc.type = textureInfo->textureType;
- textureDesc.numMipLevels = textureInfo->mipLevelCount;
- textureDesc.arraySize = textureInfo->arrayLayerCount;
- textureDesc.size = textureInfo->extents;
- textureDesc.defaultState = getDefaultResourceStateForViewType(viewType);
- textureDesc.allowedStates = ResourceStateSet(
- textureDesc.defaultState,
- ResourceState::CopySource,
- ResourceState::CopyDestination);
- textureDesc.format = textureInfo->format;
-
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- textureDesc,
- textureInfo->subresourceDatas.getBuffer(),
- texture.writeRef()));
-
- IResourceView::Desc textureViewDesc = {};
- textureViewDesc.type = viewType;
- textureViewDesc.format = textureDesc.format; // TODO: Handle typeless formats - gfxIsTypelessFormat(format) ? convertTypelessFormat(format) : format;
- GFX_CHECK_CALL_ABORT(device->createTextureView(texture, textureViewDesc, textureView.writeRef()));
-
- auto texelSize = getTexelSize(textureInfo->format);
- size_t alignment;
- device->getTextureRowAlignment(&alignment);
- alignedRowStride = (textureInfo->extents.width * texelSize + alignment - 1) & ~(alignment - 1);
- IBufferResource::Desc bufferDesc = {};
- // All of the values read back from the shader will be uint32_t
- bufferDesc.sizeInBytes = textureDesc.size.width * textureDesc.size.height * textureDesc.size.depth * texelSize * sizeof(uint32_t);
- bufferDesc.format = Format::Unknown;
- bufferDesc.elementSize = sizeof(uint32_t);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.allowedStates = ResourceStateSet(
- bufferDesc.defaultState,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- GFX_CHECK_CALL_ABORT(device->createBufferResource(bufferDesc, nullptr, resultsBuffer.writeRef()));
-
- IResourceView::Desc bufferViewDesc = {};
- bufferViewDesc.type = IResourceView::Type::UnorderedAccess;
- bufferViewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(device->createBufferView(resultsBuffer, nullptr, bufferViewDesc, bufferView.writeRef()));
- }
+ ITextureResource::Desc textureDesc = {};
+ textureDesc.type = textureInfo->textureType;
+ textureDesc.numMipLevels = textureInfo->mipLevelCount;
+ textureDesc.arraySize = textureInfo->arrayLayerCount;
+ textureDesc.size = textureInfo->extents;
+ textureDesc.defaultState = getDefaultResourceStateForViewType(viewType);
+ textureDesc.allowedStates = ResourceStateSet(
+ textureDesc.defaultState,
+ ResourceState::CopySource,
+ ResourceState::CopyDestination);
+ textureDesc.format = textureInfo->format;
+
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(
+ textureDesc,
+ textureInfo->subresourceDatas.getBuffer(),
+ texture.writeRef()));
+
+ IResourceView::Desc textureViewDesc = {};
+ textureViewDesc.type = viewType;
+ textureViewDesc.format =
+ textureDesc.format; // TODO: Handle typeless formats - gfxIsTypelessFormat(format) ?
+ // convertTypelessFormat(format) : format;
+ GFX_CHECK_CALL_ABORT(
+ device->createTextureView(texture, textureViewDesc, textureView.writeRef()));
+
+ auto texelSize = getTexelSize(textureInfo->format);
+ size_t alignment;
+ device->getTextureRowAlignment(&alignment);
+ alignedRowStride =
+ (textureInfo->extents.width * texelSize + alignment - 1) & ~(alignment - 1);
+ IBufferResource::Desc bufferDesc = {};
+ // All of the values read back from the shader will be uint32_t
+ bufferDesc.sizeInBytes = textureDesc.size.width * textureDesc.size.height *
+ textureDesc.size.depth * texelSize * sizeof(uint32_t);
+ bufferDesc.format = Format::Unknown;
+ bufferDesc.elementSize = sizeof(uint32_t);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.allowedStates = ResourceStateSet(
+ bufferDesc.defaultState,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, nullptr, resultsBuffer.writeRef()));
+
+ IResourceView::Desc bufferViewDesc = {};
+ bufferViewDesc.type = IResourceView::Type::UnorderedAccess;
+ bufferViewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(device->createBufferView(
+ resultsBuffer,
+ nullptr,
+ bufferViewDesc,
+ bufferView.writeRef()));
+ }
- void submitShaderWork(const char* entryPoint)
+ void submitShaderWork(const char* entryPoint)
+ {
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadComputeProgram(
+ device,
+ shaderProgram,
+ "trivial-copy-textures",
+ entryPoint,
+ slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "trivial-copy-textures", entryPoint, slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- auto rootObject = encoder->bindPipeline(pipelineState);
+ auto rootObject = encoder->bindPipeline(pipelineState);
- ShaderCursor entryPointCursor(
- rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
+ ShaderCursor entryPointCursor(
+ rootObject->getEntryPoint(0)); // get a cursor the the first entry-point.
- auto width = textureInfo->extents.width;
- auto height = textureInfo->extents.height;
- auto depth = textureInfo->extents.depth;
+ auto width = textureInfo->extents.width;
+ auto height = textureInfo->extents.height;
+ auto depth = textureInfo->extents.depth;
- entryPointCursor["width"].setData(width);
- entryPointCursor["height"].setData(height);
- entryPointCursor["depth"].setData(depth);
+ entryPointCursor["width"].setData(width);
+ entryPointCursor["height"].setData(height);
+ entryPointCursor["depth"].setData(depth);
- // Bind texture view to the entry point
- entryPointCursor["resourceView"].setResource(textureView); // TODO: Bind nullptr and make sure it doesn't splut - should be 0 everywhere
- entryPointCursor["testResults"].setResource(bufferView);
+ // Bind texture view to the entry point
+ entryPointCursor["resourceView"].setResource(
+ textureView); // TODO: Bind nullptr and make sure it doesn't splut - should be 0
+ // everywhere
+ entryPointCursor["testResults"].setResource(bufferView);
- if (sampler) entryPointCursor["sampler"].setSampler(sampler); // TODO: Bind nullptr and make sure it doesn't splut
+ if (sampler)
+ entryPointCursor["sampler"].setSampler(
+ sampler); // TODO: Bind nullptr and make sure it doesn't splut
- auto bufferElementCount = width * height * depth;
- encoder->dispatchCompute(bufferElementCount, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
+ auto bufferElementCount = width * height * depth;
+ encoder->dispatchCompute(bufferElementCount, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+ }
- void validateTextureValues(ValidationTextureData actual, ValidationTextureData original)
+ void validateTextureValues(ValidationTextureData actual, ValidationTextureData original)
+ {
+ // TODO: needs to be extended to cover mip levels and array layers
+ for (GfxIndex x = 0; x < actual.extents.width; ++x)
{
- // TODO: needs to be extended to cover mip levels and array layers
- for (GfxIndex x = 0; x < actual.extents.width; ++x)
+ for (GfxIndex y = 0; y < actual.extents.height; ++y)
{
- for (GfxIndex y = 0; y < actual.extents.height; ++y)
+ for (GfxIndex z = 0; z < actual.extents.depth; ++z)
{
- for (GfxIndex z = 0; z < actual.extents.depth; ++z)
+ auto actualBlock = (uint8_t*)actual.getBlockAt(x, y, z);
+ for (Int i = 0; i < 4; ++i)
{
- auto actualBlock = (uint8_t*)actual.getBlockAt(x, y, z);
- for (Int i = 0; i < 4; ++i)
- {
- SLANG_CHECK(actualBlock[i] == 1);
- }
+ SLANG_CHECK(actualBlock[i] == 1);
}
}
}
}
+ }
- void checkTestResults()
+ void checkTestResults()
+ {
+ // Shader resources are read-only, so we don't need to check that writes to the resource
+ // were correct.
+ if (viewType != IResourceView::Type::ShaderResource)
{
- // Shader resources are read-only, so we don't need to check that writes to the resource were correct.
- if (viewType != IResourceView::Type::ShaderResource)
- {
- ComPtr<ISlangBlob> textureBlob;
- size_t rowPitch;
- size_t pixelSize;
- GFX_CHECK_CALL_ABORT(device->readTextureResource(texture, ResourceState::CopySource, textureBlob.writeRef(), &rowPitch, &pixelSize));
- auto textureValues = (uint8_t*)textureBlob->getBufferPointer();
-
- ValidationTextureData textureResults;
- textureResults.extents = textureInfo->extents;
- textureResults.textureData = textureValues;
- textureResults.strides.x = (uint32_t)pixelSize;
- textureResults.strides.y = (uint32_t)rowPitch;
- textureResults.strides.z = textureResults.extents.height * textureResults.strides.y;
-
- ValidationTextureData originalData;
- originalData.extents = textureInfo->extents;
- originalData.textureData = textureInfo->subresourceDatas.getBuffer();
- originalData.strides.x = (uint32_t)pixelSize;
- originalData.strides.y = textureInfo->extents.width * originalData.strides.x;
- originalData.strides.z = textureInfo->extents.height * originalData.strides.y;
-
- validateTextureValues(textureResults, originalData);
- }
+ ComPtr<ISlangBlob> textureBlob;
+ size_t rowPitch;
+ size_t pixelSize;
+ GFX_CHECK_CALL_ABORT(device->readTextureResource(
+ texture,
+ ResourceState::CopySource,
+ textureBlob.writeRef(),
+ &rowPitch,
+ &pixelSize));
+ auto textureValues = (uint8_t*)textureBlob->getBufferPointer();
- ComPtr<ISlangBlob> bufferBlob;
- GFX_CHECK_CALL_ABORT(device->readBufferResource(resultsBuffer, 0, resultsBuffer->getDesc()->sizeInBytes, bufferBlob.writeRef()));
- auto results = (uint32_t*)bufferBlob->getBufferPointer();
+ ValidationTextureData textureResults;
+ textureResults.extents = textureInfo->extents;
+ textureResults.textureData = textureValues;
+ textureResults.strides.x = (uint32_t)pixelSize;
+ textureResults.strides.y = (uint32_t)rowPitch;
+ textureResults.strides.z = textureResults.extents.height * textureResults.strides.y;
- auto elementCount = textureInfo->extents.width * textureInfo->extents.height * textureInfo->extents.depth * 4;
- auto castedTextureData = (uint8_t*)expectedTextureData;
- for (Int i = 0; i < elementCount; ++i)
- {
- SLANG_CHECK(results[i] == castedTextureData[i]);
- }
+ ValidationTextureData originalData;
+ originalData.extents = textureInfo->extents;
+ originalData.textureData = textureInfo->subresourceDatas.getBuffer();
+ originalData.strides.x = (uint32_t)pixelSize;
+ originalData.strides.y = textureInfo->extents.width * originalData.strides.x;
+ originalData.strides.z = textureInfo->extents.height * originalData.strides.y;
+
+ validateTextureValues(textureResults, originalData);
}
- void run()
+ ComPtr<ISlangBlob> bufferBlob;
+ GFX_CHECK_CALL_ABORT(device->readBufferResource(
+ resultsBuffer,
+ 0,
+ resultsBuffer->getDesc()->sizeInBytes,
+ bufferBlob.writeRef()));
+ auto results = (uint32_t*)bufferBlob->getBufferPointer();
+
+ auto elementCount = textureInfo->extents.width * textureInfo->extents.height *
+ textureInfo->extents.depth * 4;
+ auto castedTextureData = (uint8_t*)expectedTextureData;
+ for (Int i = 0; i < elementCount; ++i)
{
- // TODO: Should test with samplers
-// ISamplerState::Desc samplerDesc;
-// sampler = device->createSamplerState(samplerDesc);
-
- // TODO: Should test multiple mip levels and array layers
- textureInfo->extents.width = 4;
- textureInfo->extents.height = (textureInfo->textureType == IResource::Type::Texture1D) ? 1 : 4;
- textureInfo->extents.depth = (textureInfo->textureType != IResource::Type::Texture3D) ? 1 : 2;
- textureInfo->mipLevelCount = 1;
- textureInfo->arrayLayerCount = 1;
- generateTextureData(textureInfo, validationFormat);
-
- // We need to save the pointer to the original texture data for results checking because the texture will be
- // overwritten during testing (if the texture can be written to).
- expectedTextureData = textureInfo->subresourceDatas[getSubresourceIndex(0, 1, 0)].data;
-
- createRequiredResources();
- auto entryPointName = getShaderEntryPoint();
- //printf("%s\n", entryPointName.getBuffer());
- submitShaderWork(entryPointName.getBuffer());
-
- checkTestResults();
+ SLANG_CHECK(results[i] == castedTextureData[i]);
}
+ }
+
+ void run()
+ {
+ // TODO: Should test with samplers
+ // ISamplerState::Desc samplerDesc;
+ // sampler = device->createSamplerState(samplerDesc);
+
+ // TODO: Should test multiple mip levels and array layers
+ textureInfo->extents.width = 4;
+ textureInfo->extents.height =
+ (textureInfo->textureType == IResource::Type::Texture1D) ? 1 : 4;
+ textureInfo->extents.depth =
+ (textureInfo->textureType != IResource::Type::Texture3D) ? 1 : 2;
+ textureInfo->mipLevelCount = 1;
+ textureInfo->arrayLayerCount = 1;
+ generateTextureData(textureInfo, validationFormat);
+
+ // We need to save the pointer to the original texture data for results checking because the
+ // texture will be overwritten during testing (if the texture can be written to).
+ expectedTextureData = textureInfo->subresourceDatas[getSubresourceIndex(0, 1, 0)].data;
+
+ createRequiredResources();
+ auto entryPointName = getShaderEntryPoint();
+ // printf("%s\n", entryPointName.getBuffer());
+ submitShaderWork(entryPointName.getBuffer());
+
+ checkTestResults();
+ }
+};
+
+// used for rendertarget and depthstencil
+struct RenderTargetTests : BaseTextureViewTest
+{
+ struct Vertex
+ {
+ float position[3];
+ float color[3];
};
- // used for rendertarget and depthstencil
- struct RenderTargetTests : BaseTextureViewTest
+ const int kVertexCount = 12;
+ const Vertex kVertexData[12] = {
+ // Triangle 1
+ {{0, 0, 0.5}, {1, 0, 0}},
+ {{1, 1, 0.5}, {1, 0, 0}},
+ {{-1, 1, 0.5}, {1, 0, 0}},
+
+ // Triangle 2
+ {{-1, 1, 0.5}, {0, 1, 0}},
+ {{0, 0, 0.5}, {0, 1, 0}},
+ {{-1, -1, 0.5}, {0, 1, 0}},
+
+ // Triangle 3
+ {{-1, -1, 0.5}, {0, 0, 1}},
+ {{0, 0, 0.5}, {0, 0, 1}},
+ {{1, -1, 0.5}, {0, 0, 1}},
+
+ // Triangle 4
+ {{1, -1, 0.5}, {0, 0, 0}},
+ {{0, 0, 0.5}, {0, 0, 0}},
+ {{1, 1, 0.5}, {0, 0, 0}},
+ };
+
+ int sampleCount = 1;
+
+ ComPtr<ITransientResourceHeap> transientHeap;
+ ComPtr<IPipelineState> pipelineState;
+ ComPtr<IRenderPassLayout> renderPass;
+ ComPtr<IFramebuffer> framebuffer;
+
+ ComPtr<ITextureResource> sampledTexture;
+ ComPtr<IBufferResource> vertexBuffer;
+
+ void createRequiredResources()
{
- struct Vertex
- {
- float position[3];
- float color[3];
+ IBufferResource::Desc vertexBufferDesc;
+ vertexBufferDesc.type = IResource::Type::Buffer;
+ vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
+ vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
+ vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
+ vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
+ SLANG_CHECK_ABORT(vertexBuffer != nullptr);
+
+ VertexStreamDesc vertexStreams[] = {
+ {sizeof(Vertex), InputSlotClass::PerVertex, 0},
};
- const int kVertexCount = 12;
- const Vertex kVertexData[12] =
- {
- // Triangle 1
- { { 0, 0, 0.5 }, { 1, 0, 0 } },
- { { 1, 1, 0.5 }, { 1, 0, 0 } },
- { { -1, 1, 0.5 }, { 1, 0, 0 } },
-
- // Triangle 2
- { { -1, 1, 0.5 }, { 0, 1, 0 } },
- { { 0, 0, 0.5 }, { 0, 1, 0 } },
- { { -1, -1, 0.5 }, { 0, 1, 0 } },
-
- // Triangle 3
- { { -1, -1, 0.5 }, { 0, 0, 1 } },
- { { 0, 0, 0.5 }, { 0, 0, 1 } },
- { { 1, -1, 0.5 }, { 0, 0, 1 } },
-
- // Triangle 4
- { { 1, -1, 0.5 }, { 0, 0, 0 } },
- { { 0, 0, 0.5 }, { 0, 0, 0 } },
- { { 1, 1, 0.5 }, { 0, 0, 0 } },
+ InputElementDesc inputElements[] = {
+ // Vertex buffer data
+ {"POSITION", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0},
+ {"COLOR", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, color), 0},
};
- int sampleCount = 1;
+ ITextureResource::Desc sampledTexDesc = {};
+ sampledTexDesc.type = textureInfo->textureType;
+ sampledTexDesc.numMipLevels = textureInfo->mipLevelCount;
+ sampledTexDesc.arraySize = textureInfo->arrayLayerCount;
+ sampledTexDesc.size = textureInfo->extents;
+ sampledTexDesc.defaultState = getDefaultResourceStateForViewType(viewType);
+ sampledTexDesc.allowedStates = ResourceStateSet(
+ sampledTexDesc.defaultState,
+ ResourceState::ResolveSource,
+ ResourceState::CopySource);
+ sampledTexDesc.format = textureInfo->format;
+ sampledTexDesc.sampleDesc.numSamples = sampleCount;
+
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(
+ sampledTexDesc,
+ textureInfo->subresourceDatas.getBuffer(),
+ sampledTexture.writeRef()));
+
+ ITextureResource::Desc texDesc = {};
+ texDesc.type = textureInfo->textureType;
+ texDesc.numMipLevels = textureInfo->mipLevelCount;
+ texDesc.arraySize = textureInfo->arrayLayerCount;
+ texDesc.size = textureInfo->extents;
+ texDesc.defaultState = ResourceState::ResolveDestination;
+ texDesc.allowedStates =
+ ResourceStateSet(ResourceState::ResolveDestination, ResourceState::CopySource);
+ texDesc.format = textureInfo->format;
+
+ GFX_CHECK_CALL_ABORT(device->createTextureResource(
+ texDesc,
+ textureInfo->subresourceDatas.getBuffer(),
+ texture.writeRef()));
+
+ IInputLayout::Desc inputLayoutDesc = {};
+ inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
+ inputLayoutDesc.inputElements = inputElements;
+ inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
+ inputLayoutDesc.vertexStreams = vertexStreams;
+ auto inputLayout = device->createInputLayout(inputLayoutDesc);
+ SLANG_CHECK_ABORT(inputLayout != nullptr);
+
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(loadGraphicsProgram(
+ device,
+ shaderProgram,
+ "trivial-copy-textures",
+ "vertexMain",
+ "fragmentMain",
+ slangReflection));
+
+ IFramebufferLayout::TargetLayout targetLayout;
+ targetLayout.format = textureInfo->format;
+ targetLayout.sampleCount = sampleCount;
+
+ IFramebufferLayout::Desc framebufferLayoutDesc;
+ framebufferLayoutDesc.renderTargetCount = 1;
+ framebufferLayoutDesc.renderTargets = &targetLayout;
+ ComPtr<gfx::IFramebufferLayout> framebufferLayout =
+ device->createFramebufferLayout(framebufferLayoutDesc);
+ SLANG_CHECK_ABORT(framebufferLayout != nullptr);
+
+ GraphicsPipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ pipelineDesc.inputLayout = inputLayout;
+ pipelineDesc.framebufferLayout = framebufferLayout;
+ pipelineDesc.depthStencil.depthTestEnable = false;
+ pipelineDesc.depthStencil.depthWriteEnable = false;
+ GFX_CHECK_CALL_ABORT(
+ device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ IRenderPassLayout::Desc renderPassDesc = {};
+ renderPassDesc.framebufferLayout = framebufferLayout;
+ renderPassDesc.renderTargetCount = 1;
+ IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
+ renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
+ renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
+ renderTargetAccess.initialState = getDefaultResourceStateForViewType(viewType);
+ renderTargetAccess.finalState = ResourceState::ResolveSource;
+ renderPassDesc.renderTargetAccess = &renderTargetAccess;
+ GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
+
+ gfx::IResourceView::Desc colorBufferViewDesc;
+ memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
+ colorBufferViewDesc.format = textureInfo->format;
+ colorBufferViewDesc.renderTarget.shape = textureInfo->textureType; // TODO: TextureCube?
+ colorBufferViewDesc.type = viewType;
+ auto rtv = device->createTextureView(sampledTexture, colorBufferViewDesc);
+
+ gfx::IFramebuffer::Desc framebufferDesc;
+ framebufferDesc.renderTargetCount = 1;
+ framebufferDesc.depthStencilView = nullptr;
+ framebufferDesc.renderTargetViews = rtv.readRef();
+ framebufferDesc.layout = framebufferLayout;
+ GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
+
+ auto texelSize = getTexelSize(textureInfo->format);
+ size_t alignment;
+ device->getTextureRowAlignment(&alignment);
+ alignedRowStride =
+ (textureInfo->extents.width * texelSize + alignment - 1) & ~(alignment - 1);
+ }
+
+ void submitShaderWork(const char* entryPointName)
+ {
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
+
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto renderEncoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
+ auto rootObject = renderEncoder->bindPipeline(pipelineState);
- ComPtr<ITransientResourceHeap> transientHeap;
- ComPtr<IPipelineState> pipelineState;
- ComPtr<IRenderPassLayout> renderPass;
- ComPtr<IFramebuffer> framebuffer;
+ gfx::Viewport viewport = {};
+ viewport.maxZ = (float)textureInfo->extents.depth;
+ viewport.extentX = (float)textureInfo->extents.width;
+ viewport.extentY = (float)textureInfo->extents.height;
+ renderEncoder->setViewportAndScissor(viewport);
- ComPtr<ITextureResource> sampledTexture;
- ComPtr<IBufferResource> vertexBuffer;
+ renderEncoder->setVertexBuffer(0, vertexBuffer);
+ renderEncoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
+ renderEncoder->draw(kVertexCount, 0);
+ renderEncoder->endEncoding();
- void createRequiredResources()
+ auto resourceEncoder = commandBuffer->encodeResourceCommands();
+
+ if (sampleCount > 1)
{
- IBufferResource::Desc vertexBufferDesc;
- vertexBufferDesc.type = IResource::Type::Buffer;
- vertexBufferDesc.sizeInBytes = kVertexCount * sizeof(Vertex);
- vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
- vertexBufferDesc.allowedStates = ResourceState::VertexBuffer;
- vertexBuffer = device->createBufferResource(vertexBufferDesc, &kVertexData[0]);
- SLANG_CHECK_ABORT(vertexBuffer != nullptr);
-
- VertexStreamDesc vertexStreams[] = {
- { sizeof(Vertex), InputSlotClass::PerVertex, 0 },
- };
-
- InputElementDesc inputElements[] = {
- // Vertex buffer data
- { "POSITION", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position), 0 },
- { "COLOR", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, color), 0 },
- };
-
- ITextureResource::Desc sampledTexDesc = {};
- sampledTexDesc.type = textureInfo->textureType;
- sampledTexDesc.numMipLevels = textureInfo->mipLevelCount;
- sampledTexDesc.arraySize = textureInfo->arrayLayerCount;
- sampledTexDesc.size = textureInfo->extents;
- sampledTexDesc.defaultState = getDefaultResourceStateForViewType(viewType);
- sampledTexDesc.allowedStates = ResourceStateSet(
- sampledTexDesc.defaultState,
+ SubresourceRange msaaSubresource = {};
+ msaaSubresource.aspectMask = TextureAspect::Color;
+ msaaSubresource.mipLevel = 0;
+ msaaSubresource.mipLevelCount = 1;
+ msaaSubresource.baseArrayLayer = 0;
+ msaaSubresource.layerCount = 1;
+
+ SubresourceRange dstSubresource = {};
+ dstSubresource.aspectMask = TextureAspect::Color;
+ dstSubresource.mipLevel = 0;
+ dstSubresource.mipLevelCount = 1;
+ dstSubresource.baseArrayLayer = 0;
+ dstSubresource.layerCount = 1;
+
+ resourceEncoder->resolveResource(
+ sampledTexture,
ResourceState::ResolveSource,
- ResourceState::CopySource);
- sampledTexDesc.format = textureInfo->format;
- sampledTexDesc.sampleDesc.numSamples = sampleCount;
-
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- sampledTexDesc,
- textureInfo->subresourceDatas.getBuffer(),
- sampledTexture.writeRef()));
-
- ITextureResource::Desc texDesc = {};
- texDesc.type = textureInfo->textureType;
- texDesc.numMipLevels = textureInfo->mipLevelCount;
- texDesc.arraySize = textureInfo->arrayLayerCount;
- texDesc.size = textureInfo->extents;
- texDesc.defaultState = ResourceState::ResolveDestination;
- texDesc.allowedStates = ResourceStateSet(
+ msaaSubresource,
+ texture,
+ ResourceState::ResolveDestination,
+ dstSubresource);
+ resourceEncoder->textureBarrier(
+ texture,
ResourceState::ResolveDestination,
ResourceState::CopySource);
- texDesc.format = textureInfo->format;
-
- GFX_CHECK_CALL_ABORT(device->createTextureResource(
- texDesc,
- textureInfo->subresourceDatas.getBuffer(),
- texture.writeRef()));
-
- IInputLayout::Desc inputLayoutDesc = {};
- inputLayoutDesc.inputElementCount = SLANG_COUNT_OF(inputElements);
- inputLayoutDesc.inputElements = inputElements;
- inputLayoutDesc.vertexStreamCount = SLANG_COUNT_OF(vertexStreams);
- inputLayoutDesc.vertexStreams = vertexStreams;
- auto inputLayout = device->createInputLayout(inputLayoutDesc);
- SLANG_CHECK_ABORT(inputLayout != nullptr);
-
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadGraphicsProgram(device, shaderProgram, "trivial-copy-textures", "vertexMain", "fragmentMain", slangReflection));
-
- IFramebufferLayout::TargetLayout targetLayout;
- targetLayout.format = textureInfo->format;
- targetLayout.sampleCount = sampleCount;
-
- IFramebufferLayout::Desc framebufferLayoutDesc;
- framebufferLayoutDesc.renderTargetCount = 1;
- framebufferLayoutDesc.renderTargets = &targetLayout;
- ComPtr<gfx::IFramebufferLayout> framebufferLayout = device->createFramebufferLayout(framebufferLayoutDesc);
- SLANG_CHECK_ABORT(framebufferLayout != nullptr);
-
- GraphicsPipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- pipelineDesc.inputLayout = inputLayout;
- pipelineDesc.framebufferLayout = framebufferLayout;
- pipelineDesc.depthStencil.depthTestEnable = false;
- pipelineDesc.depthStencil.depthWriteEnable = false;
- GFX_CHECK_CALL_ABORT(
- device->createGraphicsPipelineState(pipelineDesc, pipelineState.writeRef()));
-
- IRenderPassLayout::Desc renderPassDesc = {};
- renderPassDesc.framebufferLayout = framebufferLayout;
- renderPassDesc.renderTargetCount = 1;
- IRenderPassLayout::TargetAccessDesc renderTargetAccess = {};
- renderTargetAccess.loadOp = IRenderPassLayout::TargetLoadOp::Clear;
- renderTargetAccess.storeOp = IRenderPassLayout::TargetStoreOp::Store;
- renderTargetAccess.initialState = getDefaultResourceStateForViewType(viewType);
- renderTargetAccess.finalState = ResourceState::ResolveSource;
- renderPassDesc.renderTargetAccess = &renderTargetAccess;
- GFX_CHECK_CALL_ABORT(device->createRenderPassLayout(renderPassDesc, renderPass.writeRef()));
-
- gfx::IResourceView::Desc colorBufferViewDesc;
- memset(&colorBufferViewDesc, 0, sizeof(colorBufferViewDesc));
- colorBufferViewDesc.format = textureInfo->format;
- colorBufferViewDesc.renderTarget.shape = textureInfo->textureType; // TODO: TextureCube?
- colorBufferViewDesc.type = viewType;
- auto rtv = device->createTextureView(sampledTexture, colorBufferViewDesc);
-
- gfx::IFramebuffer::Desc framebufferDesc;
- framebufferDesc.renderTargetCount = 1;
- framebufferDesc.depthStencilView = nullptr;
- framebufferDesc.renderTargetViews = rtv.readRef();
- framebufferDesc.layout = framebufferLayout;
- GFX_CHECK_CALL_ABORT(device->createFramebuffer(framebufferDesc, framebuffer.writeRef()));
-
- auto texelSize = getTexelSize(textureInfo->format);
- size_t alignment;
- device->getTextureRowAlignment(&alignment);
- alignedRowStride = (textureInfo->extents.width * texelSize + alignment - 1) & ~(alignment - 1);
}
-
- void submitShaderWork(const char* entryPointName)
+ else
{
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto renderEncoder = commandBuffer->encodeRenderCommands(renderPass, framebuffer);
- auto rootObject = renderEncoder->bindPipeline(pipelineState);
-
- gfx::Viewport viewport = {};
- viewport.maxZ = (float)textureInfo->extents.depth;
- viewport.extentX = (float)textureInfo->extents.width;
- viewport.extentY = (float)textureInfo->extents.height;
- renderEncoder->setViewportAndScissor(viewport);
-
- renderEncoder->setVertexBuffer(0, vertexBuffer);
- renderEncoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
- renderEncoder->draw(kVertexCount, 0);
- renderEncoder->endEncoding();
-
- auto resourceEncoder = commandBuffer->encodeResourceCommands();
-
- if (sampleCount > 1)
- {
- SubresourceRange msaaSubresource = {};
- msaaSubresource.aspectMask = TextureAspect::Color;
- msaaSubresource.mipLevel = 0;
- msaaSubresource.mipLevelCount = 1;
- msaaSubresource.baseArrayLayer = 0;
- msaaSubresource.layerCount = 1;
-
- SubresourceRange dstSubresource = {};
- dstSubresource.aspectMask = TextureAspect::Color;
- dstSubresource.mipLevel = 0;
- dstSubresource.mipLevelCount = 1;
- dstSubresource.baseArrayLayer = 0;
- dstSubresource.layerCount = 1;
-
- resourceEncoder->resolveResource(sampledTexture, ResourceState::ResolveSource, msaaSubresource, texture, ResourceState::ResolveDestination, dstSubresource);
- resourceEncoder->textureBarrier(texture, ResourceState::ResolveDestination, ResourceState::CopySource);
- }
- else
- {
- resourceEncoder->textureBarrier(sampledTexture, ResourceState::ResolveSource, ResourceState::CopySource);
- }
- resourceEncoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
+ resourceEncoder->textureBarrier(
+ sampledTexture,
+ ResourceState::ResolveSource,
+ ResourceState::CopySource);
}
+ resourceEncoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
+ }
- // TODO: Should take a value indicating the slice that was rendered into
- // TODO: Needs to handle either the correct slice or array layer (will not always check z)
- void validateTextureValues(ValidationTextureData actual)
+ // TODO: Should take a value indicating the slice that was rendered into
+ // TODO: Needs to handle either the correct slice or array layer (will not always check z)
+ void validateTextureValues(ValidationTextureData actual)
+ {
+ for (GfxIndex x = 0; x < actual.extents.width; ++x)
{
- for (GfxIndex x = 0; x < actual.extents.width; ++x)
+ for (GfxIndex y = 0; y < actual.extents.height; ++y)
{
- for (GfxIndex y = 0; y < actual.extents.height; ++y)
+ for (GfxIndex z = 0; z < actual.extents.depth; ++z)
{
- for (GfxIndex z = 0; z < actual.extents.depth; ++z)
+ auto actualBlock = (float*)actual.getBlockAt(x, y, z);
+ for (Int i = 0; i < 4; ++i)
{
- auto actualBlock = (float*)actual.getBlockAt(x, y, z);
- for (Int i = 0; i < 4; ++i)
+ if (z == 0)
+ {
+ // Slice being rendered into
+ SLANG_CHECK(actualBlock[i] == (float)i + 1);
+ }
+ else
{
- if (z == 0)
- {
- // Slice being rendered into
- SLANG_CHECK(actualBlock[i] == (float)i + 1);
- }
- else
- {
- SLANG_CHECK(actualBlock[i] == 0.0f);
- }
+ SLANG_CHECK(actualBlock[i] == 0.0f);
}
}
}
}
}
+ }
- void checkTestResults()
+ void checkTestResults()
+ {
+ ComPtr<ISlangBlob> textureBlob;
+ size_t rowPitch;
+ size_t pixelSize;
+ if (sampleCount > 1)
{
- ComPtr<ISlangBlob> textureBlob;
- size_t rowPitch;
- size_t pixelSize;
- if (sampleCount > 1)
- {
- GFX_CHECK_CALL_ABORT(device->readTextureResource(texture, ResourceState::CopySource, textureBlob.writeRef(), &rowPitch, &pixelSize));
- }
- else
- {
- GFX_CHECK_CALL_ABORT(device->readTextureResource(sampledTexture, ResourceState::CopySource, textureBlob.writeRef(), &rowPitch, &pixelSize));
- }
- auto textureValues = (float*)textureBlob->getBufferPointer();
-
- ValidationTextureData textureResults;
- textureResults.extents = textureInfo->extents;
- textureResults.textureData = textureValues;
- textureResults.strides.x = (uint32_t)pixelSize;
- textureResults.strides.y = (uint32_t)rowPitch;
- textureResults.strides.z = textureResults.extents.height * textureResults.strides.y;
-
- validateTextureValues(textureResults);
+ GFX_CHECK_CALL_ABORT(device->readTextureResource(
+ texture,
+ ResourceState::CopySource,
+ textureBlob.writeRef(),
+ &rowPitch,
+ &pixelSize));
}
-
- void run()
+ else
{
- auto entryPointName = getShaderEntryPoint();
-// printf("%s\n", entryPointName.getBuffer());
-
- // TODO: Sampler state and null state?
-// ISamplerState::Desc samplerDesc;
-// sampler = device->createSamplerState(samplerDesc);
-
- textureInfo->extents.width = 4;
- textureInfo->extents.height = (textureInfo->textureType == IResource::Type::Texture1D) ? 1 : 4;
- textureInfo->extents.depth = (textureInfo->textureType != IResource::Type::Texture3D) ? 1 : 2;
- textureInfo->mipLevelCount = 1;
- textureInfo->arrayLayerCount = 1;
- generateTextureData(textureInfo, validationFormat);
-
- // We need to save the pointer to the original texture data for results checking because the texture will be
- // overwritten during testing (if the texture can be written to).
- expectedTextureData = textureInfo->subresourceDatas[getSubresourceIndex(0, 1, 0)].data;
+ GFX_CHECK_CALL_ABORT(device->readTextureResource(
+ sampledTexture,
+ ResourceState::CopySource,
+ textureBlob.writeRef(),
+ &rowPitch,
+ &pixelSize));
+ }
+ auto textureValues = (float*)textureBlob->getBufferPointer();
- createRequiredResources();
- submitShaderWork(entryPointName.getBuffer());
+ ValidationTextureData textureResults;
+ textureResults.extents = textureInfo->extents;
+ textureResults.textureData = textureValues;
+ textureResults.strides.x = (uint32_t)pixelSize;
+ textureResults.strides.y = (uint32_t)rowPitch;
+ textureResults.strides.z = textureResults.extents.height * textureResults.strides.y;
- checkTestResults();
- }
- };
+ validateTextureValues(textureResults);
+ }
- void shaderAndUnorderedTestImpl(IDevice* device, UnitTestContext* context)
+ void run()
{
- // TODO: Buffer and TextureCube
- for (Int i = 2; i < (int32_t)IResource::Type::TextureCube; ++i)
- {
- for (Int j = 3; j < (int32_t)IResourceView::Type::AccelerationStructure; ++j)
- {
- auto shape = (IResource::Type)i;
- auto view = (IResourceView::Type)j;
- auto format = Format::R8G8B8A8_UINT;
- auto validationFormat = getValidationTextureFormat(format);
- if (!validationFormat)
- SLANG_CHECK_ABORT(false);
-
- ShaderAndUnorderedTests test;
- test.init(device, context, format, validationFormat, view, shape);
- test.run();
- }
- }
+ auto entryPointName = getShaderEntryPoint();
+ // printf("%s\n", entryPointName.getBuffer());
+
+ // TODO: Sampler state and null state?
+ // ISamplerState::Desc samplerDesc;
+ // sampler = device->createSamplerState(samplerDesc);
+
+ textureInfo->extents.width = 4;
+ textureInfo->extents.height =
+ (textureInfo->textureType == IResource::Type::Texture1D) ? 1 : 4;
+ textureInfo->extents.depth =
+ (textureInfo->textureType != IResource::Type::Texture3D) ? 1 : 2;
+ textureInfo->mipLevelCount = 1;
+ textureInfo->arrayLayerCount = 1;
+ generateTextureData(textureInfo, validationFormat);
+
+ // We need to save the pointer to the original texture data for results checking because the
+ // texture will be overwritten during testing (if the texture can be written to).
+ expectedTextureData = textureInfo->subresourceDatas[getSubresourceIndex(0, 1, 0)].data;
+
+ createRequiredResources();
+ submitShaderWork(entryPointName.getBuffer());
+
+ checkTestResults();
}
+};
- void renderTargetTestImpl(IDevice* device, UnitTestContext* context)
+void shaderAndUnorderedTestImpl(IDevice* device, UnitTestContext* context)
+{
+ // TODO: Buffer and TextureCube
+ for (Int i = 2; i < (int32_t)IResource::Type::TextureCube; ++i)
{
- // TODO: Buffer and TextureCube
- for (Int i = 2; i < (int32_t)IResource::Type::TextureCube; ++i)
+ for (Int j = 3; j < (int32_t)IResourceView::Type::AccelerationStructure; ++j)
{
auto shape = (IResource::Type)i;
- auto view = IResourceView::Type::RenderTarget;
- auto format = Format::R32G32B32A32_FLOAT;
+ auto view = (IResourceView::Type)j;
+ auto format = Format::R8G8B8A8_UINT;
auto validationFormat = getValidationTextureFormat(format);
if (!validationFormat)
SLANG_CHECK_ABORT(false);
- RenderTargetTests test;
+ ShaderAndUnorderedTests test;
test.init(device, context, format, validationFormat, view, shape);
test.run();
}
}
+}
- SLANG_UNIT_TEST(shaderAndUnorderedAccessTests)
+void renderTargetTestImpl(IDevice* device, UnitTestContext* context)
+{
+ // TODO: Buffer and TextureCube
+ for (Int i = 2; i < (int32_t)IResource::Type::TextureCube; ++i)
{
- runTestImpl(shaderAndUnorderedTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(shaderAndUnorderedTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ auto shape = (IResource::Type)i;
+ auto view = IResourceView::Type::RenderTarget;
+ auto format = Format::R32G32B32A32_FLOAT;
+ auto validationFormat = getValidationTextureFormat(format);
+ if (!validationFormat)
+ SLANG_CHECK_ABORT(false);
+
+ RenderTargetTests test;
+ test.init(device, context, format, validationFormat, view, shape);
+ test.run();
}
+}
- SLANG_UNIT_TEST(renderTargetTests)
- {
- runTestImpl(renderTargetTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- runTestImpl(renderTargetTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
- }
+SLANG_UNIT_TEST(shaderAndUnorderedAccessTests)
+{
+ runTestImpl(shaderAndUnorderedTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+ runTestImpl(shaderAndUnorderedTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+SLANG_UNIT_TEST(renderTargetTests)
+{
+ runTestImpl(renderTargetTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
+ runTestImpl(renderTargetTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
}
+} // namespace gfx_test
// 1D + array + multisample, ditto for 2D, ditto for 3D
-// one test with something bound, one test with nothing bound, one test with subset of layers (set values in SubresourceRange and assign in desc)
+// one test with something bound, one test with nothing bound, one test with subset of layers (set
+// values in SubresourceRange and assign in desc)
diff --git a/tools/gfx-unit-test/uint16-structured-buffer.cpp b/tools/gfx-unit-test/uint16-structured-buffer.cpp
index 8f2f2cb97..23fd70544 100644
--- a/tools/gfx-unit-test/uint16-structured-buffer.cpp
+++ b/tools/gfx-unit-test/uint16-structured-buffer.cpp
@@ -1,96 +1,91 @@
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang-gfx.h"
#include "gfx-test-util.h"
-#include "tools/gfx-util/shader-cursor.h"
+#include "slang-gfx.h"
#include "source/core/slang-basic.h"
+#include "tools/gfx-util/shader-cursor.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace gfx;
namespace gfx_test
{
- void uint16BufferTestImpl(IDevice* device, UnitTestContext* context)
+void uint16BufferTestImpl(IDevice* device, UnitTestContext* context)
+{
+ Slang::ComPtr<ITransientResourceHeap> transientHeap;
+ ITransientResourceHeap::Desc transientHeapDesc = {};
+ transientHeapDesc.constantBufferSize = 4096;
+ GFX_CHECK_CALL_ABORT(
+ device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
+
+ ComPtr<IShaderProgram> shaderProgram;
+ slang::ProgramLayout* slangReflection;
+ GFX_CHECK_CALL_ABORT(
+ loadComputeProgram(device, shaderProgram, "uint16-buffer", "computeMain", slangReflection));
+
+ ComputePipelineStateDesc pipelineDesc = {};
+ pipelineDesc.program = shaderProgram.get();
+ ComPtr<gfx::IPipelineState> pipelineState;
+ GFX_CHECK_CALL_ABORT(
+ device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
+
+ const int numberCount = 4;
+ uint16_t initialData[] = {0, 1, 2, 3};
+ IBufferResource::Desc bufferDesc = {};
+ bufferDesc.sizeInBytes = numberCount * sizeof(uint16_t);
+ bufferDesc.format = gfx::Format::Unknown;
+ // Note: we don't specify any element size here, and gfx should be able to derive the
+ // correct element size from the reflection infomation.
+ bufferDesc.elementSize = 0;
+ bufferDesc.allowedStates = ResourceStateSet(
+ ResourceState::ShaderResource,
+ ResourceState::UnorderedAccess,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
+ bufferDesc.defaultState = ResourceState::UnorderedAccess;
+ bufferDesc.memoryType = MemoryType::DeviceLocal;
+
+ ComPtr<IBufferResource> numbersBuffer;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferResource(bufferDesc, (void*)initialData, numbersBuffer.writeRef()));
+
+ ComPtr<IResourceView> bufferView;
+ IResourceView::Desc viewDesc = {};
+ viewDesc.type = IResourceView::Type::UnorderedAccess;
+ viewDesc.format = Format::Unknown;
+ GFX_CHECK_CALL_ABORT(
+ device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
+
+ // We have done all the set up work, now it is time to start recording a command buffer for
+ // GPU execution.
{
- Slang::ComPtr<ITransientResourceHeap> transientHeap;
- ITransientResourceHeap::Desc transientHeapDesc = {};
- transientHeapDesc.constantBufferSize = 4096;
- GFX_CHECK_CALL_ABORT(
- device->createTransientResourceHeap(transientHeapDesc, transientHeap.writeRef()));
-
- ComPtr<IShaderProgram> shaderProgram;
- slang::ProgramLayout* slangReflection;
- GFX_CHECK_CALL_ABORT(loadComputeProgram(device, shaderProgram, "uint16-buffer", "computeMain", slangReflection));
-
- ComputePipelineStateDesc pipelineDesc = {};
- pipelineDesc.program = shaderProgram.get();
- ComPtr<gfx::IPipelineState> pipelineState;
- GFX_CHECK_CALL_ABORT(
- device->createComputePipelineState(pipelineDesc, pipelineState.writeRef()));
-
- const int numberCount = 4;
- uint16_t initialData[] = { 0, 1, 2, 3 };
- IBufferResource::Desc bufferDesc = {};
- bufferDesc.sizeInBytes = numberCount * sizeof(uint16_t);
- bufferDesc.format = gfx::Format::Unknown;
- // Note: we don't specify any element size here, and gfx should be able to derive the
- // correct element size from the reflection infomation.
- bufferDesc.elementSize = 0;
- bufferDesc.allowedStates = ResourceStateSet(
- ResourceState::ShaderResource,
- ResourceState::UnorderedAccess,
- ResourceState::CopyDestination,
- ResourceState::CopySource);
- bufferDesc.defaultState = ResourceState::UnorderedAccess;
- bufferDesc.memoryType = MemoryType::DeviceLocal;
-
- ComPtr<IBufferResource> numbersBuffer;
- GFX_CHECK_CALL_ABORT(device->createBufferResource(
- bufferDesc,
- (void*)initialData,
- numbersBuffer.writeRef()));
-
- ComPtr<IResourceView> bufferView;
- IResourceView::Desc viewDesc = {};
- viewDesc.type = IResourceView::Type::UnorderedAccess;
- viewDesc.format = Format::Unknown;
- GFX_CHECK_CALL_ABORT(
- device->createBufferView(numbersBuffer, nullptr, viewDesc, bufferView.writeRef()));
-
- // We have done all the set up work, now it is time to start recording a command buffer for
- // GPU execution.
- {
- ICommandQueue::Desc queueDesc = { ICommandQueue::QueueType::Graphics };
- auto queue = device->createCommandQueue(queueDesc);
-
- auto commandBuffer = transientHeap->createCommandBuffer();
- auto encoder = commandBuffer->encodeComputeCommands();
-
- auto rootObject = encoder->bindPipeline(pipelineState);
-
- // Bind buffer view to the entry point.
- ShaderCursor(rootObject).getPath("buffer").setResource(bufferView);
-
- encoder->dispatchCompute(1, 1, 1);
- encoder->endEncoding();
- commandBuffer->close();
- queue->executeCommandBuffer(commandBuffer);
- queue->waitOnHost();
- }
-
- compareComputeResult(
- device,
- numbersBuffer,
- Slang::makeArray<uint16_t>(1, 2, 3, 4));
- }
+ ICommandQueue::Desc queueDesc = {ICommandQueue::QueueType::Graphics};
+ auto queue = device->createCommandQueue(queueDesc);
- SLANG_UNIT_TEST(uint16BufferTestD3D12)
- {
- runTestImpl(uint16BufferTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
- }
+ auto commandBuffer = transientHeap->createCommandBuffer();
+ auto encoder = commandBuffer->encodeComputeCommands();
- SLANG_UNIT_TEST(uint16BufferTestVulkan)
- {
- runTestImpl(uint16BufferTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+ auto rootObject = encoder->bindPipeline(pipelineState);
+
+ // Bind buffer view to the entry point.
+ ShaderCursor(rootObject).getPath("buffer").setResource(bufferView);
+
+ encoder->dispatchCompute(1, 1, 1);
+ encoder->endEncoding();
+ commandBuffer->close();
+ queue->executeCommandBuffer(commandBuffer);
+ queue->waitOnHost();
}
+ compareComputeResult(device, numbersBuffer, Slang::makeArray<uint16_t>(1, 2, 3, 4));
+}
+
+SLANG_UNIT_TEST(uint16BufferTestD3D12)
+{
+ runTestImpl(uint16BufferTestImpl, unitTestContext, Slang::RenderApiFlag::D3D12);
}
+
+SLANG_UNIT_TEST(uint16BufferTestVulkan)
+{
+ runTestImpl(uint16BufferTestImpl, unitTestContext, Slang::RenderApiFlag::Vulkan);
+}
+
+} // namespace gfx_test
diff --git a/tools/gfx-util/shader-cursor.cpp b/tools/gfx-util/shader-cursor.cpp
index c849673bf..7166ef66a 100644
--- a/tools/gfx-util/shader-cursor.cpp
+++ b/tools/gfx-util/shader-cursor.cpp
@@ -7,8 +7,7 @@ Result gfx::ShaderCursor::getDereferenced(ShaderCursor& outCursor) const
{
switch (m_typeLayout->getKind())
{
- default:
- return SLANG_E_INVALID_ARG;
+ default: return SLANG_E_INVALID_ARG;
case slang::TypeReflection::Kind::ConstantBuffer:
case slang::TypeReflection::Kind::ParameterBlock:
@@ -26,7 +25,7 @@ ShaderCursor ShaderCursor::getExplicitCounter() const
// The alternative to handling this here would be to augment IResourceView
// with a `getCounterResourceView()`, and set that also in `setResource`
- if(const auto counterVarLayout = m_typeLayout->getExplicitCounter())
+ if (const auto counterVarLayout = m_typeLayout->getExplicitCounter())
{
ShaderCursor counterCursor;
@@ -38,10 +37,11 @@ ShaderCursor ShaderCursor::getExplicitCounter() const
// The byte offset is the current offset plus the relative offset of the counter.
// The offset in binding ranges is computed similarly.
- counterCursor.m_offset.uniformOffset
- = m_offset.uniformOffset + SlangInt(counterVarLayout->getOffset());
- counterCursor.m_offset.bindingRangeIndex
- = m_offset.bindingRangeIndex + GfxIndex(m_typeLayout->getExplicitCounterBindingRangeOffset());
+ counterCursor.m_offset.uniformOffset =
+ m_offset.uniformOffset + SlangInt(counterVarLayout->getOffset());
+ counterCursor.m_offset.bindingRangeIndex =
+ m_offset.bindingRangeIndex +
+ GfxIndex(m_typeLayout->getExplicitCounterBindingRangeOffset());
// The index of the counter within any binding ranges will be the same
// as the index computed for the parent structure.
@@ -118,7 +118,8 @@ Result ShaderCursor::getField(const char* name, const char* nameEnd, ShaderCurso
//
fieldCursor.m_offset.uniformOffset = m_offset.uniformOffset + fieldLayout->getOffset();
fieldCursor.m_offset.bindingRangeIndex =
- m_offset.bindingRangeIndex + (GfxIndex)m_typeLayout->getFieldBindingRangeOffset(fieldIndex);
+ m_offset.bindingRangeIndex +
+ (GfxIndex)m_typeLayout->getFieldBindingRangeOffset(fieldIndex);
// The index of the field within any binding ranges will be the same
// as the index computed for the parent structure.
@@ -178,8 +179,8 @@ Result ShaderCursor::getField(const char* name, const char* nameEnd, ShaderCurso
//
// TODO: figure out whether we should support this long-term.
//
- auto entryPointCount = (GfxIndex) m_baseObject->getEntryPointCount();
- for( GfxIndex e = 0; e < entryPointCount; ++e )
+ auto entryPointCount = (GfxIndex)m_baseObject->getEntryPointCount();
+ for (GfxIndex e = 0; e < entryPointCount; ++e)
{
ComPtr<IShaderObject> entryPoint;
m_baseObject->getEntryPoint(e, entryPoint.writeRef());
@@ -187,7 +188,7 @@ Result ShaderCursor::getField(const char* name, const char* nameEnd, ShaderCurso
ShaderCursor entryPointCursor(entryPoint);
auto result = entryPointCursor.getField(name, nameEnd, outCursor);
- if(SLANG_SUCCEEDED(result))
+ if (SLANG_SUCCEEDED(result))
return result;
}
@@ -208,7 +209,7 @@ ShaderCursor ShaderCursor::getElement(GfxIndex index) const
return elementCursor;
}
- switch( m_typeLayout->getKind() )
+ switch (m_typeLayout->getKind())
{
case slang::TypeReflection::Kind::Array:
{
@@ -233,7 +234,7 @@ ShaderCursor ShaderCursor::getElement(GfxIndex index) const
auto fieldIndex = index;
slang::VariableLayoutReflection* fieldLayout =
m_typeLayout->getFieldByIndex((unsigned int)fieldIndex);
- if(!fieldLayout)
+ if (!fieldLayout)
return ShaderCursor();
ShaderCursor fieldCursor;
@@ -241,7 +242,8 @@ ShaderCursor ShaderCursor::getElement(GfxIndex index) const
fieldCursor.m_typeLayout = fieldLayout->getTypeLayout();
fieldCursor.m_offset.uniformOffset = m_offset.uniformOffset + fieldLayout->getOffset();
fieldCursor.m_offset.bindingRangeIndex =
- m_offset.bindingRangeIndex + (GfxIndex)m_typeLayout->getFieldBindingRangeOffset(fieldIndex);
+ m_offset.bindingRangeIndex +
+ (GfxIndex)m_typeLayout->getFieldBindingRangeOffset(fieldIndex);
fieldCursor.m_offset.bindingArrayIndex = m_offset.bindingArrayIndex;
return fieldCursor;
@@ -254,7 +256,9 @@ ShaderCursor ShaderCursor::getElement(GfxIndex index) const
ShaderCursor fieldCursor;
fieldCursor.m_baseObject = m_baseObject;
fieldCursor.m_typeLayout = m_typeLayout->getElementTypeLayout();
- fieldCursor.m_offset.uniformOffset = m_offset.uniformOffset + m_typeLayout->getElementStride(SLANG_PARAMETER_CATEGORY_UNIFORM) * index;
+ fieldCursor.m_offset.uniformOffset =
+ m_offset.uniformOffset +
+ m_typeLayout->getElementStride(SLANG_PARAMETER_CATEGORY_UNIFORM) * index;
fieldCursor.m_offset.bindingRangeIndex = m_offset.bindingRangeIndex;
fieldCursor.m_offset.bindingArrayIndex = m_offset.bindingArrayIndex;
return fieldCursor;
@@ -347,14 +351,11 @@ Result ShaderCursor::followPath(const char* path, ShaderCursor& ioCursor)
{
switch (_peek(rest))
{
- default:
- _get(rest);
- continue;
+ default: _get(rest); continue;
case -1:
case '.':
- case '[':
- break;
+ case '[': break;
}
break;
}
diff --git a/tools/gfx-util/shader-cursor.h b/tools/gfx-util/shader-cursor.h
index 3d35bb2ed..b24edb594 100644
--- a/tools/gfx-util/shader-cursor.h
+++ b/tools/gfx-util/shader-cursor.h
@@ -87,14 +87,15 @@ struct ShaderCursor
: m_baseObject(object)
, m_typeLayout(object->getElementTypeLayout())
, m_containerType(object->getContainerType())
- {}
+ {
+ }
SlangResult setData(void const* data, Size size) const
{
return m_baseObject->setData(m_offset, data, size);
}
- template <typename T>
+ template<typename T>
SlangResult setData(T const& data) const
{
return setData(&data, sizeof(data));
@@ -125,17 +126,14 @@ struct ShaderCursor
return m_baseObject->setCombinedTextureSampler(m_offset, textureView, sampler);
}
- /// Produce a cursor to the field with the given `name`.
- ///
- /// This is a convenience wrapper around `getField()`.
- ShaderCursor operator[](const char* name) const
- {
- return getField(name);
- }
+ /// Produce a cursor to the field with the given `name`.
+ ///
+ /// This is a convenience wrapper around `getField()`.
+ ShaderCursor operator[](const char* name) const { return getField(name); }
- /// Produce a cursor to the element or field with the given `index`.
- ///
- /// This is a convenience wrapper around `getElement()`.
+ /// Produce a cursor to the element or field with the given `index`.
+ ///
+ /// This is a convenience wrapper around `getElement()`.
ShaderCursor operator[](int64_t index) const { return getElement((GfxIndex)index); }
ShaderCursor operator[](uint64_t index) const { return getElement((GfxIndex)index); }
ShaderCursor operator[](int32_t index) const { return getElement((GfxIndex)index); }
@@ -145,4 +143,4 @@ struct ShaderCursor
ShaderCursor operator[](int8_t index) const { return getElement((GfxIndex)index); }
ShaderCursor operator[](uint8_t index) const { return getElement((GfxIndex)index); }
};
-}
+} // namespace gfx
diff --git a/tools/gfx/apple/cocoa-util.h b/tools/gfx/apple/cocoa-util.h
index e9d29b87c..427cf1570 100644
--- a/tools/gfx/apple/cocoa-util.h
+++ b/tools/gfx/apple/cocoa-util.h
@@ -1,15 +1,17 @@
#pragma once
-namespace gfx {
+namespace gfx
+{
// Utility functions for Cocoa
-struct CocoaUtil {
+struct CocoaUtil
+{
static void getNSWindowContentSize(void* nswindow, int* widthOut, int* heightOut);
static void* createMetalLayer(void* nswindow);
static void destroyMetalLayer(void* metalLayer);
- static void* nextDrawable(void* metalLayer) ;
+ static void* nextDrawable(void* metalLayer);
};
-}
+} // namespace gfx
diff --git a/tools/gfx/command-encoder-com-forward.h b/tools/gfx/command-encoder-com-forward.h
index 9a26b0590..43f87c931 100644
--- a/tools/gfx/command-encoder-com-forward.h
+++ b/tools/gfx/command-encoder-com-forward.h
@@ -1,142 +1,165 @@
#pragma once
-#define SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoderBase) \
- virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface( \
- SlangUUID const& uuid, void** outObject) override \
- { \
- return ResourceCommandEncoderBase::queryInterface(uuid, outObject); \
- } \
- virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() override \
- { \
- return ResourceCommandEncoderBase::addRef(); \
- } \
- virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() override \
- { \
- return ResourceCommandEncoderBase::release(); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL copyBuffer( \
- IBufferResource* dst, Offset dstOffset, IBufferResource* src, Offset srcOffset, Size size) \
- override \
- { \
- ResourceCommandEncoderBase::copyBuffer(dst, dstOffset, src, srcOffset, size); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL copyTexture( \
- ITextureResource* dst, \
- ResourceState dstState, \
- SubresourceRange dstSubresource, \
- ITextureResource::Offset3D dstOffset, \
- ITextureResource* src, \
- ResourceState srcState, \
- SubresourceRange srcSubresource, \
- ITextureResource::Offset3D srcOffset, \
- ITextureResource::Extents extent) override \
- { \
- ResourceCommandEncoderBase::copyTexture( \
- dst, \
- dstState, \
- dstSubresource, \
- dstOffset, \
- src, \
- srcState, \
- srcSubresource, \
- srcOffset, \
- extent); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL copyTextureToBuffer( \
- IBufferResource* dst, \
- Offset dstOffset, \
- Size dstSize, \
- Size dstRowStride, \
- ITextureResource* src, \
- ResourceState srcState, \
- SubresourceRange srcSubresource, \
- ITextureResource::Offset3D srcOffset, \
- ITextureResource::Extents extent) override \
- { \
- ResourceCommandEncoderBase::copyTextureToBuffer( \
- dst, \
- dstOffset, \
- dstSize, \
- dstRowStride, \
- src, \
- srcState, \
- srcSubresource, \
- srcOffset, \
- extent); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL uploadTextureData( \
- ITextureResource* dst, \
- SubresourceRange subResourceRange, \
- ITextureResource::Offset3D offset, \
- ITextureResource::Extents extent, \
- ITextureResource::SubresourceData* subResourceData, \
- GfxCount subResourceDataCount) override \
- { \
- ResourceCommandEncoderBase::uploadTextureData( \
- dst, subResourceRange, offset, extent, subResourceData, subResourceDataCount); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL uploadBufferData( \
- IBufferResource* dst, Offset offset, Size size, void* data) override \
- { \
- ResourceCommandEncoderBase::uploadBufferData(dst, offset, size, data); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL textureBarrier( \
- GfxCount count, ITextureResource* const* textures, ResourceState src, ResourceState dst) \
- override \
- { \
- ResourceCommandEncoderBase::textureBarrier(count, textures, src, dst); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL textureSubresourceBarrier( \
- ITextureResource* texture, \
- SubresourceRange subresourceRange, \
- ResourceState src, \
- ResourceState dst) override \
- { \
- ResourceCommandEncoderBase::textureSubresourceBarrier( \
- texture, subresourceRange, src, dst); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL bufferBarrier( \
- GfxCount count, IBufferResource* const* buffers, ResourceState src, ResourceState dst) \
- override \
- { \
- ResourceCommandEncoderBase::bufferBarrier(count, buffers, src, dst); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL clearResourceView( \
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags) override \
- { \
- ResourceCommandEncoderBase::clearResourceView(view, clearValue, flags); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL resolveResource( \
- ITextureResource* source, \
- ResourceState sourceState, \
- SubresourceRange sourceRange, \
- ITextureResource* dest, \
- ResourceState destState, \
- SubresourceRange destRange) override \
- { \
- ResourceCommandEncoderBase::resolveResource( \
- source, sourceState, sourceRange, dest, destState, destRange); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL resolveQuery( \
- IQueryPool* queryPool, \
- GfxIndex index, \
- GfxCount count, \
- IBufferResource* buffer, \
- Offset offset) override \
- { \
- ResourceCommandEncoderBase::resolveQuery(queryPool, index, count, buffer, offset); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL writeTimestamp(IQueryPool* pool, GfxIndex index) \
- override \
- { \
- ResourceCommandEncoderBase::writeTimestamp(pool, index); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL beginDebugEvent(const char* name, float rgbColor[3]) \
- override \
- { \
- ResourceCommandEncoderBase::beginDebugEvent(name, rgbColor); \
- } \
- virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent() override \
- { \
- ResourceCommandEncoderBase::endDebugEvent(); \
+#define SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoderBase) \
+ virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface( \
+ SlangUUID const& uuid, \
+ void** outObject) override \
+ { \
+ return ResourceCommandEncoderBase::queryInterface(uuid, outObject); \
+ } \
+ virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() override \
+ { \
+ return ResourceCommandEncoderBase::addRef(); \
+ } \
+ virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() override \
+ { \
+ return ResourceCommandEncoderBase::release(); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL copyBuffer( \
+ IBufferResource* dst, \
+ Offset dstOffset, \
+ IBufferResource* src, \
+ Offset srcOffset, \
+ Size size) override \
+ { \
+ ResourceCommandEncoderBase::copyBuffer(dst, dstOffset, src, srcOffset, size); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL copyTexture( \
+ ITextureResource* dst, \
+ ResourceState dstState, \
+ SubresourceRange dstSubresource, \
+ ITextureResource::Offset3D dstOffset, \
+ ITextureResource* src, \
+ ResourceState srcState, \
+ SubresourceRange srcSubresource, \
+ ITextureResource::Offset3D srcOffset, \
+ ITextureResource::Extents extent) override \
+ { \
+ ResourceCommandEncoderBase::copyTexture( \
+ dst, \
+ dstState, \
+ dstSubresource, \
+ dstOffset, \
+ src, \
+ srcState, \
+ srcSubresource, \
+ srcOffset, \
+ extent); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL copyTextureToBuffer( \
+ IBufferResource* dst, \
+ Offset dstOffset, \
+ Size dstSize, \
+ Size dstRowStride, \
+ ITextureResource* src, \
+ ResourceState srcState, \
+ SubresourceRange srcSubresource, \
+ ITextureResource::Offset3D srcOffset, \
+ ITextureResource::Extents extent) override \
+ { \
+ ResourceCommandEncoderBase::copyTextureToBuffer( \
+ dst, \
+ dstOffset, \
+ dstSize, \
+ dstRowStride, \
+ src, \
+ srcState, \
+ srcSubresource, \
+ srcOffset, \
+ extent); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL uploadTextureData( \
+ ITextureResource* dst, \
+ SubresourceRange subResourceRange, \
+ ITextureResource::Offset3D offset, \
+ ITextureResource::Extents extent, \
+ ITextureResource::SubresourceData* subResourceData, \
+ GfxCount subResourceDataCount) override \
+ { \
+ ResourceCommandEncoderBase::uploadTextureData( \
+ dst, \
+ subResourceRange, \
+ offset, \
+ extent, \
+ subResourceData, \
+ subResourceDataCount); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL \
+ uploadBufferData(IBufferResource* dst, Offset offset, Size size, void* data) override \
+ { \
+ ResourceCommandEncoderBase::uploadBufferData(dst, offset, size, data); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL textureBarrier( \
+ GfxCount count, \
+ ITextureResource* const* textures, \
+ ResourceState src, \
+ ResourceState dst) override \
+ { \
+ ResourceCommandEncoderBase::textureBarrier(count, textures, src, dst); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL textureSubresourceBarrier( \
+ ITextureResource* texture, \
+ SubresourceRange subresourceRange, \
+ ResourceState src, \
+ ResourceState dst) override \
+ { \
+ ResourceCommandEncoderBase::textureSubresourceBarrier( \
+ texture, \
+ subresourceRange, \
+ src, \
+ dst); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL bufferBarrier( \
+ GfxCount count, \
+ IBufferResource* const* buffers, \
+ ResourceState src, \
+ ResourceState dst) override \
+ { \
+ ResourceCommandEncoderBase::bufferBarrier(count, buffers, src, dst); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL clearResourceView( \
+ IResourceView* view, \
+ ClearValue* clearValue, \
+ ClearResourceViewFlags::Enum flags) override \
+ { \
+ ResourceCommandEncoderBase::clearResourceView(view, clearValue, flags); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL resolveResource( \
+ ITextureResource* source, \
+ ResourceState sourceState, \
+ SubresourceRange sourceRange, \
+ ITextureResource* dest, \
+ ResourceState destState, \
+ SubresourceRange destRange) override \
+ { \
+ ResourceCommandEncoderBase::resolveResource( \
+ source, \
+ sourceState, \
+ sourceRange, \
+ dest, \
+ destState, \
+ destRange); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL resolveQuery( \
+ IQueryPool* queryPool, \
+ GfxIndex index, \
+ GfxCount count, \
+ IBufferResource* buffer, \
+ Offset offset) override \
+ { \
+ ResourceCommandEncoderBase::resolveQuery(queryPool, index, count, buffer, offset); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL writeTimestamp(IQueryPool* pool, GfxIndex index) \
+ override \
+ { \
+ ResourceCommandEncoderBase::writeTimestamp(pool, index); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL beginDebugEvent(const char* name, float rgbColor[3]) \
+ override \
+ { \
+ ResourceCommandEncoderBase::beginDebugEvent(name, rgbColor); \
+ } \
+ virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent() override \
+ { \
+ ResourceCommandEncoderBase::endDebugEvent(); \
}
diff --git a/tools/gfx/command-writer.h b/tools/gfx/command-writer.h
index 03ac3ac6d..febdcfef3 100644
--- a/tools/gfx/command-writer.h
+++ b/tools/gfx/command-writer.h
@@ -1,9 +1,9 @@
#pragma once
-#include "slang-gfx.h"
-#include "slang-com-ptr.h"
#include "core/slang-basic.h"
#include "renderer-shared.h"
+#include "slang-com-ptr.h"
+#include "slang-gfx.h"
namespace gfx
{
@@ -115,12 +115,14 @@ public:
return offset;
}
- template <typename T> T* getObject(uint32_t offset)
+ template<typename T>
+ T* getObject(uint32_t offset)
{
return static_cast<T*>(m_objects[offset].Ptr());
}
- template <typename T> T* getData(Offset offset)
+ template<typename T>
+ T* getData(Offset offset)
{
return reinterpret_cast<T*>(m_data.getBuffer() + offset);
}
@@ -176,7 +178,10 @@ public:
void clearFrame(uint32_t colorBufferMask, bool clearDepth, bool clearStencil)
{
m_commands.add(Command(
- CommandName::ClearFrame, colorBufferMask, clearDepth ? 1 : 0, clearStencil ? 1 : 0));
+ CommandName::ClearFrame,
+ colorBufferMask,
+ clearDepth ? 1 : 0,
+ clearStencil ? 1 : 0));
}
void setViewports(GfxCount count, const Viewport* viewports)
@@ -222,7 +227,10 @@ public:
{
auto bufferOffset = encodeObject(static_cast<BufferResource*>(buffer));
m_commands.add(Command(
- CommandName::SetIndexBuffer, (uint32_t)bufferOffset, (uint32_t)indexFormat, (uint32_t)offset));
+ CommandName::SetIndexBuffer,
+ (uint32_t)bufferOffset,
+ (uint32_t)indexFormat,
+ (uint32_t)offset));
}
void draw(GfxCount vertexCount, GfxIndex startVertex)
@@ -283,9 +291,8 @@ public:
void writeTimestamp(IQueryPool* pool, GfxIndex index)
{
auto poolOffset = encodeObject(static_cast<QueryPoolBase*>(pool));
- m_commands.add(
- Command(CommandName::WriteTimestamp, (uint32_t)poolOffset, (uint32_t)index));
+ m_commands.add(Command(CommandName::WriteTimestamp, (uint32_t)poolOffset, (uint32_t)index));
m_hasWriteTimestamps = true;
}
};
-}
+} // namespace gfx
diff --git a/tools/gfx/cpu/cpu-base.h b/tools/gfx/cpu/cpu-base.h
index 6f30662ec..5c9cca5d9 100644
--- a/tools/gfx/cpu/cpu-base.h
+++ b/tools/gfx/cpu/cpu-base.h
@@ -2,15 +2,14 @@
// Shared header file for CPU implementation
#pragma once
-#include "slang.h"
-#include "slang-com-ptr.h"
-#include "slang-com-helper.h"
-#include "core/slang-basic.h"
-#include "core/slang-blob.h"
-
#include "../immediate-renderer-base.h"
-#include "../slang-context.h"
#include "../mutable-shader-object.h"
+#include "../slang-context.h"
+#include "core/slang-basic.h"
+#include "core/slang-blob.h"
+#include "slang-com-helper.h"
+#include "slang-com-ptr.h"
+#include "slang.h"
#define SLANG_PRELUDE_NAMESPACE slang_prelude
#include "prelude/slang-cpp-types.h"
@@ -20,21 +19,21 @@ using namespace Slang;
namespace cpu
{
- class BufferResourceImpl;
- class TextureResourceImpl;
- class ResourceViewImpl;
- class BufferResourceViewImpl;
- class TextureResourceViewImpl;
- class ShaderObjectLayoutImpl;
- class EntryPointLayoutImpl;
- class RootShaderObjectLayoutImpl;
- class ShaderObjectImpl;
- class MutableShaderObjectImpl;
- class EntryPointShaderObjectImpl;
- class RootShaderObjectImpl;
- class ShaderProgramImpl;
- class PipelineStateImpl;
- class QueryPoolImpl;
- class DeviceImpl;
+class BufferResourceImpl;
+class TextureResourceImpl;
+class ResourceViewImpl;
+class BufferResourceViewImpl;
+class TextureResourceViewImpl;
+class ShaderObjectLayoutImpl;
+class EntryPointLayoutImpl;
+class RootShaderObjectLayoutImpl;
+class ShaderObjectImpl;
+class MutableShaderObjectImpl;
+class EntryPointShaderObjectImpl;
+class RootShaderObjectImpl;
+class ShaderProgramImpl;
+class PipelineStateImpl;
+class QueryPoolImpl;
+class DeviceImpl;
} // namespace cpu
} // namespace gfx
diff --git a/tools/gfx/cpu/cpu-buffer.cpp b/tools/gfx/cpu/cpu-buffer.cpp
index 2c9c3077d..a1184fd95 100644
--- a/tools/gfx/cpu/cpu-buffer.cpp
+++ b/tools/gfx/cpu/cpu-buffer.cpp
@@ -36,7 +36,7 @@ SLANG_NO_THROW DeviceAddress SLANG_MCALL BufferResourceImpl::getDeviceAddress()
}
SLANG_NO_THROW Result SLANG_MCALL
- BufferResourceImpl::map(MemoryRange* rangeToRead, void** outPointer)
+BufferResourceImpl::map(MemoryRange* rangeToRead, void** outPointer)
{
SLANG_UNUSED(rangeToRead);
if (outPointer)
diff --git a/tools/gfx/cpu/cpu-buffer.h b/tools/gfx/cpu/cpu-buffer.h
index 6273b18b9..9b1866c74 100644
--- a/tools/gfx/cpu/cpu-buffer.h
+++ b/tools/gfx/cpu/cpu-buffer.h
@@ -14,7 +14,8 @@ class BufferResourceImpl : public BufferResource
public:
BufferResourceImpl(const Desc& _desc)
: BufferResource(_desc)
- {}
+ {
+ }
~BufferResourceImpl();
@@ -27,7 +28,7 @@ public:
virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- map(MemoryRange* rangeToRead, void** outPointer) override;
+ map(MemoryRange* rangeToRead, void** outPointer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL unmap(MemoryRange* writtenRange) override;
};
diff --git a/tools/gfx/cpu/cpu-device.cpp b/tools/gfx/cpu/cpu-device.cpp
index bd747d998..6f7ff0f16 100644
--- a/tools/gfx/cpu/cpu-device.cpp
+++ b/tools/gfx/cpu/cpu-device.cpp
@@ -1,8 +1,6 @@
// cpu-device.cpp
#include "cpu-device.h"
-#include <chrono>
-
#include "cpu-buffer.h"
#include "cpu-pipeline-state.h"
#include "cpu-query.h"
@@ -11,293 +9,300 @@
#include "cpu-shader-program.h"
#include "cpu-texture.h"
+#include <chrono>
+
namespace gfx
{
using namespace Slang;
namespace cpu
{
- DeviceImpl::~DeviceImpl()
+DeviceImpl::~DeviceImpl()
+{
+ m_currentPipeline = nullptr;
+ m_currentRootObject = nullptr;
+}
+
+SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::initialize(const Desc& desc)
+{
+ SLANG_RETURN_ON_FAIL(slangContext.initialize(
+ desc.slang,
+ desc.extendedDescCount,
+ desc.extendedDescs,
+ SLANG_SHADER_HOST_CALLABLE,
+ "sm_5_1",
+ makeArray(slang::PreprocessorMacroDesc{"__CPU__", "1"}).getView()));
+
+ SLANG_RETURN_ON_FAIL(RendererBase::initialize(desc));
+
+ // Initialize DeviceInfo
{
- m_currentPipeline = nullptr;
- m_currentRootObject = nullptr;
+ m_info.deviceType = DeviceType::CPU;
+ m_info.bindingStyle = BindingStyle::CUDA;
+ m_info.projectionStyle = ProjectionStyle::DirectX;
+ m_info.apiName = "CPU";
+ static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
+ ::memcpy(m_info.identityProjectionMatrix, kIdentity, sizeof(kIdentity));
+ m_info.adapterName = "CPU";
+ m_info.timestampFrequency = 1000000000;
}
- SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::initialize(const Desc& desc)
+ // Can support pointers (or something akin to that)
{
- SLANG_RETURN_ON_FAIL(slangContext.initialize(
- desc.slang,
- desc.extendedDescCount,
- desc.extendedDescs,
- SLANG_SHADER_HOST_CALLABLE,
- "sm_5_1",
- makeArray(slang::PreprocessorMacroDesc{ "__CPU__", "1" }).getView()));
-
- SLANG_RETURN_ON_FAIL(RendererBase::initialize(desc));
-
- // Initialize DeviceInfo
- {
- m_info.deviceType = DeviceType::CPU;
- m_info.bindingStyle = BindingStyle::CUDA;
- m_info.projectionStyle = ProjectionStyle::DirectX;
- m_info.apiName = "CPU";
- static const float kIdentity[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
- ::memcpy(m_info.identityProjectionMatrix, kIdentity, sizeof(kIdentity));
- m_info.adapterName = "CPU";
- m_info.timestampFrequency = 1000000000;
- }
-
- // Can support pointers (or something akin to that)
- {
- m_features.add("has-ptr");
- }
-
- return SLANG_OK;
+ m_features.add("has-ptr");
}
- SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureResource(
- const ITextureResource::Desc& desc,
- const ITextureResource::SubresourceData* initData,
- ITextureResource** outResource)
- {
- TextureResource::Desc srcDesc = fixupTextureDesc(desc);
+ return SLANG_OK;
+}
- RefPtr<TextureResourceImpl> texture = new TextureResourceImpl(srcDesc);
+SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureResource(
+ const ITextureResource::Desc& desc,
+ const ITextureResource::SubresourceData* initData,
+ ITextureResource** outResource)
+{
+ TextureResource::Desc srcDesc = fixupTextureDesc(desc);
- SLANG_RETURN_ON_FAIL(texture->init(initData));
+ RefPtr<TextureResourceImpl> texture = new TextureResourceImpl(srcDesc);
- returnComPtr(outResource, texture);
- return SLANG_OK;
- }
+ SLANG_RETURN_ON_FAIL(texture->init(initData));
- SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createBufferResource(
- const IBufferResource::Desc& descIn,
- const void* initData,
- IBufferResource** outResource)
- {
- auto desc = fixupBufferDesc(descIn);
- RefPtr<BufferResourceImpl> resource = new BufferResourceImpl(desc);
- SLANG_RETURN_ON_FAIL(resource->init());
- if (initData)
- {
- SLANG_RETURN_ON_FAIL(resource->setData(0, desc.sizeInBytes, initData));
- }
- returnComPtr(outResource, resource);
- return SLANG_OK;
- }
+ returnComPtr(outResource, texture);
+ return SLANG_OK;
+}
- SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureView(
- ITextureResource* inTexture, IResourceView::Desc const& desc, IResourceView** outView)
+SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createBufferResource(
+ const IBufferResource::Desc& descIn,
+ const void* initData,
+ IBufferResource** outResource)
+{
+ auto desc = fixupBufferDesc(descIn);
+ RefPtr<BufferResourceImpl> resource = new BufferResourceImpl(desc);
+ SLANG_RETURN_ON_FAIL(resource->init());
+ if (initData)
{
- auto texture = static_cast<TextureResourceImpl*>(inTexture);
- RefPtr<TextureResourceViewImpl> view = new TextureResourceViewImpl(desc, texture);
- returnComPtr(outView, view);
- return SLANG_OK;
+ SLANG_RETURN_ON_FAIL(resource->setData(0, desc.sizeInBytes, initData));
}
+ returnComPtr(outResource, resource);
+ return SLANG_OK;
+}
- SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createBufferView(
- IBufferResource* inBuffer,
- IBufferResource* counterBuffer,
- IResourceView::Desc const& desc,
- IResourceView** outView)
- {
- auto buffer = static_cast<BufferResourceImpl*>(inBuffer);
- RefPtr<BufferResourceViewImpl> view = new BufferResourceViewImpl(desc, buffer);
- returnComPtr(outView, view);
- return SLANG_OK;
- }
+SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureView(
+ ITextureResource* inTexture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView)
+{
+ auto texture = static_cast<TextureResourceImpl*>(inTexture);
+ RefPtr<TextureResourceViewImpl> view = new TextureResourceViewImpl(desc, texture);
+ returnComPtr(outView, view);
+ return SLANG_OK;
+}
- Result DeviceImpl::createShaderObjectLayout(
- slang::ISession* session,
- slang::TypeLayoutReflection* typeLayout,
- ShaderObjectLayoutBase** outLayout)
- {
- RefPtr<ShaderObjectLayoutImpl> cpuLayout = new ShaderObjectLayoutImpl(this, session, typeLayout);
- returnRefPtrMove(outLayout, cpuLayout);
+SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createBufferView(
+ IBufferResource* inBuffer,
+ IBufferResource* counterBuffer,
+ IResourceView::Desc const& desc,
+ IResourceView** outView)
+{
+ auto buffer = static_cast<BufferResourceImpl*>(inBuffer);
+ RefPtr<BufferResourceViewImpl> view = new BufferResourceViewImpl(desc, buffer);
+ returnComPtr(outView, view);
+ return SLANG_OK;
+}
- return SLANG_OK;
- }
+Result DeviceImpl::createShaderObjectLayout(
+ slang::ISession* session,
+ slang::TypeLayoutReflection* typeLayout,
+ ShaderObjectLayoutBase** outLayout)
+{
+ RefPtr<ShaderObjectLayoutImpl> cpuLayout =
+ new ShaderObjectLayoutImpl(this, session, typeLayout);
+ returnRefPtrMove(outLayout, cpuLayout);
- Result DeviceImpl::createShaderObject(
- ShaderObjectLayoutBase* layout,
- IShaderObject** outObject)
- {
- auto cpuLayout = static_cast<ShaderObjectLayoutImpl*>(layout);
+ return SLANG_OK;
+}
- RefPtr<ShaderObjectImpl> result = new ShaderObjectImpl();
- SLANG_RETURN_ON_FAIL(result->init(this, cpuLayout));
- returnComPtr(outObject, result);
+Result DeviceImpl::createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+{
+ auto cpuLayout = static_cast<ShaderObjectLayoutImpl*>(layout);
- return SLANG_OK;
- }
+ RefPtr<ShaderObjectImpl> result = new ShaderObjectImpl();
+ SLANG_RETURN_ON_FAIL(result->init(this, cpuLayout));
+ returnComPtr(outObject, result);
- Result DeviceImpl::createMutableShaderObject(
- ShaderObjectLayoutBase* layout,
- IShaderObject** outObject)
- {
- auto cpuLayout = static_cast<ShaderObjectLayoutImpl*>(layout);
+ return SLANG_OK;
+}
- RefPtr<MutableShaderObjectImpl> result = new MutableShaderObjectImpl();
- SLANG_RETURN_ON_FAIL(result->init(this, cpuLayout));
- returnComPtr(outObject, result);
+Result DeviceImpl::createMutableShaderObject(
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject)
+{
+ auto cpuLayout = static_cast<ShaderObjectLayoutImpl*>(layout);
- return SLANG_OK;
- }
+ RefPtr<MutableShaderObjectImpl> result = new MutableShaderObjectImpl();
+ SLANG_RETURN_ON_FAIL(result->init(this, cpuLayout));
+ returnComPtr(outObject, result);
- Result DeviceImpl::createRootShaderObject(IShaderProgram* program, ShaderObjectBase** outObject)
- {
- auto cpuProgram = static_cast<ShaderProgramImpl*>(program);
- auto cpuProgramLayout = cpuProgram->layout;
+ return SLANG_OK;
+}
- RefPtr<RootShaderObjectImpl> result = new RootShaderObjectImpl();
- SLANG_RETURN_ON_FAIL(result->init(this, cpuProgramLayout));
- returnRefPtrMove(outObject, result);
- return SLANG_OK;
- }
+Result DeviceImpl::createRootShaderObject(IShaderProgram* program, ShaderObjectBase** outObject)
+{
+ auto cpuProgram = static_cast<ShaderProgramImpl*>(program);
+ auto cpuProgramLayout = cpuProgram->layout;
- SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createProgram(
- const IShaderProgram::Desc& desc,
- IShaderProgram** outProgram,
- ISlangBlob** outDiagnosticBlob)
- {
- RefPtr<ShaderProgramImpl> cpuProgram = new ShaderProgramImpl();
- cpuProgram->init(desc);
- auto slangGlobalScope = cpuProgram->linkedProgram;
- if (slangGlobalScope)
- {
- auto slangProgramLayout = slangGlobalScope->getLayout();
- if (!slangProgramLayout)
- return SLANG_FAIL;
-
- RefPtr<RootShaderObjectLayoutImpl> cpuProgramLayout = new RootShaderObjectLayoutImpl(this, slangGlobalScope->getSession(), slangProgramLayout);
- cpuProgramLayout->m_programLayout = slangProgramLayout;
-
- cpuProgram->layout = cpuProgramLayout;
- }
-
- returnComPtr(outProgram, cpuProgram);
- return SLANG_OK;
- }
+ RefPtr<RootShaderObjectImpl> result = new RootShaderObjectImpl();
+ SLANG_RETURN_ON_FAIL(result->init(this, cpuProgramLayout));
+ returnRefPtrMove(outObject, result);
+ return SLANG_OK;
+}
- SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState)
+SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createProgram(
+ const IShaderProgram::Desc& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnosticBlob)
+{
+ RefPtr<ShaderProgramImpl> cpuProgram = new ShaderProgramImpl();
+ cpuProgram->init(desc);
+ auto slangGlobalScope = cpuProgram->linkedProgram;
+ if (slangGlobalScope)
{
- RefPtr<PipelineStateImpl> state = new PipelineStateImpl();
- state->init(desc);
- returnComPtr(outState, state);
- return Result();
- }
+ auto slangProgramLayout = slangGlobalScope->getLayout();
+ if (!slangProgramLayout)
+ return SLANG_FAIL;
- SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createQueryPool(
- const IQueryPool::Desc& desc, IQueryPool** outPool)
- {
- RefPtr<QueryPoolImpl> pool = new QueryPoolImpl();
- pool->init(desc);
- returnComPtr(outPool, pool);
- return SLANG_OK;
- }
+ RefPtr<RootShaderObjectLayoutImpl> cpuProgramLayout = new RootShaderObjectLayoutImpl(
+ this,
+ slangGlobalScope->getSession(),
+ slangProgramLayout);
+ cpuProgramLayout->m_programLayout = slangProgramLayout;
- void DeviceImpl::writeTimestamp(IQueryPool* pool, GfxIndex index)
- {
- static_cast<QueryPoolImpl*>(pool)->m_queries[index] =
- std::chrono::high_resolution_clock::now().time_since_epoch().count();
+ cpuProgram->layout = cpuProgramLayout;
}
- SLANG_NO_THROW const DeviceInfo& SLANG_MCALL DeviceImpl::getDeviceInfo() const
- {
- return m_info;
- }
+ returnComPtr(outProgram, cpuProgram);
+ return SLANG_OK;
+}
- SLANG_NO_THROW Result SLANG_MCALL
- DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler)
- {
- SLANG_UNUSED(desc);
- *outSampler = nullptr;
- return SLANG_OK;
- }
+SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createComputePipelineState(
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState)
+{
+ RefPtr<PipelineStateImpl> state = new PipelineStateImpl();
+ state->init(desc);
+ returnComPtr(outState, state);
+ return Result();
+}
- void* DeviceImpl::map(IBufferResource* buffer, MapFlavor flavor)
- {
- SLANG_UNUSED(flavor);
- auto bufferImpl = static_cast<BufferResourceImpl*>(buffer);
- return bufferImpl->m_data;
- }
- void DeviceImpl::unmap(IBufferResource* buffer, size_t offsetWritten, size_t sizeWritten)
- {
- SLANG_UNUSED(buffer);
- SLANG_UNUSED(offsetWritten);
- SLANG_UNUSED(sizeWritten);
- }
+SLANG_NO_THROW Result SLANG_MCALL
+DeviceImpl::createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool)
+{
+ RefPtr<QueryPoolImpl> pool = new QueryPoolImpl();
+ pool->init(desc);
+ returnComPtr(outPool, pool);
+ return SLANG_OK;
+}
- void DeviceImpl::setPipelineState(IPipelineState* state)
- {
- m_currentPipeline = static_cast<PipelineStateImpl*>(state);
- }
+void DeviceImpl::writeTimestamp(IQueryPool* pool, GfxIndex index)
+{
+ static_cast<QueryPoolImpl*>(pool)->m_queries[index] =
+ std::chrono::high_resolution_clock::now().time_since_epoch().count();
+}
- void DeviceImpl::bindRootShaderObject(IShaderObject* object)
- {
- m_currentRootObject = static_cast<RootShaderObjectImpl*>(object);
- }
+SLANG_NO_THROW const DeviceInfo& SLANG_MCALL DeviceImpl::getDeviceInfo() const
+{
+ return m_info;
+}
- void DeviceImpl::dispatchCompute(int x, int y, int z)
- {
- int entryPointIndex = 0;
- int targetIndex = 0;
-
- // Specialize the compute kernel based on the shader object bindings.
- RefPtr<PipelineStateBase> newPipeline;
- maybeSpecializePipeline(m_currentPipeline, m_currentRootObject, newPipeline);
- m_currentPipeline = static_cast<PipelineStateImpl*>(newPipeline.Ptr());
-
- auto program = m_currentPipeline->getProgram();
- auto entryPointLayout =
- m_currentRootObject->getLayout()->getEntryPoint(entryPointIndex);
- auto entryPointName = entryPointLayout->getEntryPointName();
-
- auto entryPointObject = m_currentRootObject->getEntryPoint(entryPointIndex);
-
- ComPtr<ISlangSharedLibrary> sharedLibrary;
- ComPtr<ISlangBlob> diagnostics;
- auto compileResult = program->slangGlobalScope->getEntryPointHostCallable(
- entryPointIndex, targetIndex, sharedLibrary.writeRef(), diagnostics.writeRef());
- if (diagnostics)
- {
- getDebugCallback()->handleMessage(
- compileResult == SLANG_OK ? DebugMessageType::Warning : DebugMessageType::Error,
- DebugMessageSource::Slang,
- (char*)diagnostics->getBufferPointer());
- }
- if (SLANG_FAILED(compileResult)) return;
-
- auto func = (slang_prelude::ComputeFunc)sharedLibrary->findSymbolAddressByName(entryPointName);
-
- slang_prelude::ComputeVaryingInput varyingInput;
- varyingInput.startGroupID.x = 0;
- varyingInput.startGroupID.y = 0;
- varyingInput.startGroupID.z = 0;
- varyingInput.endGroupID.x = x;
- varyingInput.endGroupID.y = y;
- varyingInput.endGroupID.z = z;
-
- auto globalParamsData = m_currentRootObject->getDataBuffer();
- auto entryPointParamsData = entryPointObject->getDataBuffer();
- func(&varyingInput, entryPointParamsData, globalParamsData);
- }
+SLANG_NO_THROW Result SLANG_MCALL
+DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler)
+{
+ SLANG_UNUSED(desc);
+ *outSampler = nullptr;
+ return SLANG_OK;
+}
- void DeviceImpl::copyBuffer(
- IBufferResource* dst,
- size_t dstOffset,
- IBufferResource* src,
- size_t srcOffset,
- size_t size)
+void* DeviceImpl::map(IBufferResource* buffer, MapFlavor flavor)
+{
+ SLANG_UNUSED(flavor);
+ auto bufferImpl = static_cast<BufferResourceImpl*>(buffer);
+ return bufferImpl->m_data;
+}
+void DeviceImpl::unmap(IBufferResource* buffer, size_t offsetWritten, size_t sizeWritten)
+{
+ SLANG_UNUSED(buffer);
+ SLANG_UNUSED(offsetWritten);
+ SLANG_UNUSED(sizeWritten);
+}
+
+void DeviceImpl::setPipelineState(IPipelineState* state)
+{
+ m_currentPipeline = static_cast<PipelineStateImpl*>(state);
+}
+
+void DeviceImpl::bindRootShaderObject(IShaderObject* object)
+{
+ m_currentRootObject = static_cast<RootShaderObjectImpl*>(object);
+}
+
+void DeviceImpl::dispatchCompute(int x, int y, int z)
+{
+ int entryPointIndex = 0;
+ int targetIndex = 0;
+
+ // Specialize the compute kernel based on the shader object bindings.
+ RefPtr<PipelineStateBase> newPipeline;
+ maybeSpecializePipeline(m_currentPipeline, m_currentRootObject, newPipeline);
+ m_currentPipeline = static_cast<PipelineStateImpl*>(newPipeline.Ptr());
+
+ auto program = m_currentPipeline->getProgram();
+ auto entryPointLayout = m_currentRootObject->getLayout()->getEntryPoint(entryPointIndex);
+ auto entryPointName = entryPointLayout->getEntryPointName();
+
+ auto entryPointObject = m_currentRootObject->getEntryPoint(entryPointIndex);
+
+ ComPtr<ISlangSharedLibrary> sharedLibrary;
+ ComPtr<ISlangBlob> diagnostics;
+ auto compileResult = program->slangGlobalScope->getEntryPointHostCallable(
+ entryPointIndex,
+ targetIndex,
+ sharedLibrary.writeRef(),
+ diagnostics.writeRef());
+ if (diagnostics)
{
- auto dstImpl = static_cast<BufferResourceImpl*>(dst);
- auto srcImpl = static_cast<BufferResourceImpl*>(src);
- memcpy(
- (uint8_t*)dstImpl->m_data + dstOffset,
- (uint8_t*)srcImpl->m_data + srcOffset,
- size);
+ getDebugCallback()->handleMessage(
+ compileResult == SLANG_OK ? DebugMessageType::Warning : DebugMessageType::Error,
+ DebugMessageSource::Slang,
+ (char*)diagnostics->getBufferPointer());
}
+ if (SLANG_FAILED(compileResult))
+ return;
+
+ auto func = (slang_prelude::ComputeFunc)sharedLibrary->findSymbolAddressByName(entryPointName);
+
+ slang_prelude::ComputeVaryingInput varyingInput;
+ varyingInput.startGroupID.x = 0;
+ varyingInput.startGroupID.y = 0;
+ varyingInput.startGroupID.z = 0;
+ varyingInput.endGroupID.x = x;
+ varyingInput.endGroupID.y = y;
+ varyingInput.endGroupID.z = z;
+
+ auto globalParamsData = m_currentRootObject->getDataBuffer();
+ auto entryPointParamsData = entryPointObject->getDataBuffer();
+ func(&varyingInput, entryPointParamsData, globalParamsData);
+}
+
+void DeviceImpl::copyBuffer(
+ IBufferResource* dst,
+ size_t dstOffset,
+ IBufferResource* src,
+ size_t srcOffset,
+ size_t size)
+{
+ auto dstImpl = static_cast<BufferResourceImpl*>(dst);
+ auto srcImpl = static_cast<BufferResourceImpl*>(src);
+ memcpy((uint8_t*)dstImpl->m_data + dstOffset, (uint8_t*)srcImpl->m_data + srcOffset, size);
+}
} // namespace cpu
diff --git a/tools/gfx/cpu/cpu-device.h b/tools/gfx/cpu/cpu-device.h
index c7b80e26d..1bfafb1a1 100644
--- a/tools/gfx/cpu/cpu-device.h
+++ b/tools/gfx/cpu/cpu-device.h
@@ -1,7 +1,6 @@
// cpu-device.h
#pragma once
#include "cpu-base.h"
-
#include "cpu-pipeline-state.h"
#include "cpu-shader-object.h"
@@ -30,7 +29,9 @@ public:
IBufferResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
- ITextureResource* inTexture, IResourceView::Desc const& desc, IResourceView** outView) override;
+ ITextureResource* inTexture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createBufferView(
IBufferResource* inBuffer,
@@ -43,15 +44,15 @@ public:
slang::TypeLayoutReflection* typeLayout,
ShaderObjectLayoutBase** outLayout) override;
- virtual Result createShaderObject(
- ShaderObjectLayoutBase* layout,
- IShaderObject** outObject) override;
+ virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ override;
virtual Result createMutableShaderObject(
ShaderObjectLayoutBase* layout,
IShaderObject** outObject) override;
- virtual Result createRootShaderObject(IShaderProgram* program, ShaderObjectBase** outObject) override;
+ virtual Result createRootShaderObject(IShaderProgram* program, ShaderObjectBase** outObject)
+ override;
virtual SLANG_NO_THROW Result SLANG_MCALL createProgram(
const IShaderProgram::Desc& desc,
@@ -59,17 +60,18 @@ public:
ISlangBlob** outDiagnosticBlob) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState) override;
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL createQueryPool(
- const IQueryPool::Desc& desc, IQueryPool** outPool) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool) override;
virtual void writeTimestamp(IQueryPool* pool, GfxIndex index) override;
virtual SLANG_NO_THROW const DeviceInfo& SLANG_MCALL getDeviceInfo() const override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
+ createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
virtual void submitGpuWork() override {}
virtual void waitForGpu() override {}
diff --git a/tools/gfx/cpu/cpu-helper-functions.cpp b/tools/gfx/cpu/cpu-helper-functions.cpp
index f21be8d66..ea9308b35 100644
--- a/tools/gfx/cpu/cpu-helper-functions.cpp
+++ b/tools/gfx/cpu/cpu-helper-functions.cpp
@@ -8,5 +8,4 @@ namespace gfx
using namespace Slang;
-
} // namespace gfx
diff --git a/tools/gfx/cpu/cpu-helper-functions.h b/tools/gfx/cpu/cpu-helper-functions.h
index ba8d4c88e..2c6de19d8 100644
--- a/tools/gfx/cpu/cpu-helper-functions.h
+++ b/tools/gfx/cpu/cpu-helper-functions.h
@@ -7,5 +7,4 @@ namespace gfx
using namespace Slang;
-
} // namespace gfx
diff --git a/tools/gfx/cpu/cpu-pipeline-state.cpp b/tools/gfx/cpu/cpu-pipeline-state.cpp
index 7d2b6a636..d0de98532 100644
--- a/tools/gfx/cpu/cpu-pipeline-state.cpp
+++ b/tools/gfx/cpu/cpu-pipeline-state.cpp
@@ -10,18 +10,18 @@ using namespace Slang;
namespace cpu
{
- ShaderProgramImpl* PipelineStateImpl::getProgram()
- {
- return static_cast<ShaderProgramImpl*>(m_program.Ptr());
- }
+ShaderProgramImpl* PipelineStateImpl::getProgram()
+{
+ return static_cast<ShaderProgramImpl*>(m_program.Ptr());
+}
- void PipelineStateImpl::init(const ComputePipelineStateDesc& inDesc)
- {
- PipelineStateDesc pipelineDesc;
- pipelineDesc.type = PipelineType::Compute;
- pipelineDesc.compute = inDesc;
- initializeBase(pipelineDesc);
- }
+void PipelineStateImpl::init(const ComputePipelineStateDesc& inDesc)
+{
+ PipelineStateDesc pipelineDesc;
+ pipelineDesc.type = PipelineType::Compute;
+ pipelineDesc.compute = inDesc;
+ initializeBase(pipelineDesc);
+}
} // namespace cpu
} // namespace gfx
diff --git a/tools/gfx/cpu/cpu-query.cpp b/tools/gfx/cpu/cpu-query.cpp
index 3f87d7a65..9ed416c42 100644
--- a/tools/gfx/cpu/cpu-query.cpp
+++ b/tools/gfx/cpu/cpu-query.cpp
@@ -14,8 +14,8 @@ Result QueryPoolImpl::init(const IQueryPool::Desc& desc)
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL QueryPoolImpl::getResult(
- GfxIndex queryIndex, GfxCount count, uint64_t* data)
+SLANG_NO_THROW Result SLANG_MCALL
+QueryPoolImpl::getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data)
{
for (GfxCount i = 0; i < count; i++)
{
diff --git a/tools/gfx/cpu/cpu-query.h b/tools/gfx/cpu/cpu-query.h
index 172dcea41..fd4ac4754 100644
--- a/tools/gfx/cpu/cpu-query.h
+++ b/tools/gfx/cpu/cpu-query.h
@@ -14,8 +14,8 @@ class QueryPoolImpl : public QueryPoolBase
public:
List<uint64_t> m_queries;
Result init(const IQueryPool::Desc& desc);
- virtual SLANG_NO_THROW Result SLANG_MCALL getResult(
- GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
};
} // namespace cpu
diff --git a/tools/gfx/cpu/cpu-resource-views.cpp b/tools/gfx/cpu/cpu-resource-views.cpp
index ccf253cab..b9d04beff 100644
--- a/tools/gfx/cpu/cpu-resource-views.cpp
+++ b/tools/gfx/cpu/cpu-resource-views.cpp
@@ -77,8 +77,10 @@ void TextureResourceViewImpl::SampleLevel(
int32_t baseCoordCount = baseShape->baseCoordCount;
int32_t integerMipLevel = int32_t(level + 0.5f);
- if (integerMipLevel >= desc.numMipLevels) integerMipLevel = desc.numMipLevels - 1;
- if (integerMipLevel < 0) integerMipLevel = 0;
+ if (integerMipLevel >= desc.numMipLevels)
+ integerMipLevel = desc.numMipLevels - 1;
+ if (integerMipLevel < 0)
+ integerMipLevel = 0;
auto& mipLevelInfo = texture->m_mipLevels[integerMipLevel];
@@ -90,8 +92,10 @@ void TextureResourceViewImpl::SampleLevel(
{
elementIndex = int32_t(coords[coordIndex++] + 0.5f);
}
- if (elementIndex >= effectiveArrayElementCount) elementIndex = effectiveArrayElementCount - 1;
- if (elementIndex < 0) elementIndex = 0;
+ if (elementIndex >= effectiveArrayElementCount)
+ elementIndex = effectiveArrayElementCount - 1;
+ if (elementIndex < 0)
+ elementIndex = 0;
// Note: for now we are just going to do nearest-neighbor sampling
//
@@ -107,8 +111,10 @@ void TextureResourceViewImpl::SampleLevel(
int32_t integerCoord = int32_t(coord * (extent - 1) + 0.5f);
- if (integerCoord >= extent) integerCoord = extent - 1;
- if (integerCoord < 0) integerCoord = 0;
+ if (integerCoord >= extent)
+ integerCoord = extent - 1;
+ if (integerCoord < 0)
+ integerCoord = 0;
texelOffset += integerCoord * mipLevelInfo.strides[axis];
}
@@ -145,16 +151,20 @@ void* TextureResourceViewImpl::_getTexelPtr(int32_t const* texelCoords)
{
elementIndex = texelCoords[coordIndex++];
}
- if (elementIndex >= effectiveArrayElementCount) elementIndex = effectiveArrayElementCount - 1;
- if (elementIndex < 0) elementIndex = 0;
+ if (elementIndex >= effectiveArrayElementCount)
+ elementIndex = effectiveArrayElementCount - 1;
+ if (elementIndex < 0)
+ elementIndex = 0;
int32_t mipLevel = 0;
if (!hasMipLevels)
{
mipLevel = texelCoords[coordIndex++];
}
- if (mipLevel >= desc.numMipLevels) mipLevel = desc.numMipLevels - 1;
- if (mipLevel < 0) mipLevel = 0;
+ if (mipLevel >= desc.numMipLevels)
+ mipLevel = desc.numMipLevels - 1;
+ if (mipLevel < 0)
+ mipLevel = 0;
auto& mipLevelInfo = texture->m_mipLevels[mipLevel];
@@ -163,8 +173,10 @@ void* TextureResourceViewImpl::_getTexelPtr(int32_t const* texelCoords)
for (int32_t axis = 0; axis < rank; ++axis)
{
int32_t coord = texelCoords[axis];
- if (coord >= mipLevelInfo.extents[axis]) coord = mipLevelInfo.extents[axis] - 1;
- if (coord < 0) coord = 0;
+ if (coord >= mipLevelInfo.extents[axis])
+ coord = mipLevelInfo.extents[axis] - 1;
+ if (coord < 0)
+ coord = 0;
texelOffset += texelCoords[axis] * mipLevelInfo.strides[axis];
}
diff --git a/tools/gfx/cpu/cpu-resource-views.h b/tools/gfx/cpu/cpu-resource-views.h
index bec1339a3..c08946811 100644
--- a/tools/gfx/cpu/cpu-resource-views.h
+++ b/tools/gfx/cpu/cpu-resource-views.h
@@ -1,7 +1,6 @@
// cpu-resource-views.h
#pragma once
#include "cpu-base.h"
-
#include "cpu-buffer.h"
#include "cpu-texture.h"
@@ -34,9 +33,9 @@ class BufferResourceViewImpl : public ResourceViewImpl
{
public:
BufferResourceViewImpl(Desc const& desc, BufferResourceImpl* buffer)
- : ResourceViewImpl(Kind::Buffer, desc)
- , m_buffer(buffer)
- {}
+ : ResourceViewImpl(Kind::Buffer, desc), m_buffer(buffer)
+ {
+ }
BufferResourceImpl* getBuffer() const;
@@ -48,9 +47,9 @@ class TextureResourceViewImpl : public ResourceViewImpl, public slang_prelude::I
{
public:
TextureResourceViewImpl(Desc const& desc, TextureResourceImpl* texture)
- : ResourceViewImpl(Kind::Texture, desc)
- , m_texture(texture)
- {}
+ : ResourceViewImpl(Kind::Texture, desc), m_texture(texture)
+ {
+ }
TextureResourceImpl* getTexture() const;
@@ -62,9 +61,18 @@ public:
void Load(const int32_t* texelCoords, void* outData, size_t dataSize) SLANG_OVERRIDE;
- void Sample(slang_prelude::SamplerState samplerState, const float* coords, void* outData, size_t dataSize) SLANG_OVERRIDE;
-
- void SampleLevel(slang_prelude::SamplerState samplerState, const float* coords, float level, void* outData, size_t dataSize) SLANG_OVERRIDE;
+ void Sample(
+ slang_prelude::SamplerState samplerState,
+ const float* coords,
+ void* outData,
+ size_t dataSize) SLANG_OVERRIDE;
+
+ void SampleLevel(
+ slang_prelude::SamplerState samplerState,
+ const float* coords,
+ float level,
+ void* outData,
+ size_t dataSize) SLANG_OVERRIDE;
//
// IRWTexture interface
diff --git a/tools/gfx/cpu/cpu-shader-object-layout.cpp b/tools/gfx/cpu/cpu-shader-object-layout.cpp
index 4f4c33a6a..aeeadfc23 100644
--- a/tools/gfx/cpu/cpu-shader-object-layout.cpp
+++ b/tools/gfx/cpu/cpu-shader-object-layout.cpp
@@ -8,13 +8,16 @@ using namespace Slang;
namespace cpu
{
-ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(RendererBase* renderer, slang::ISession* session, slang::TypeLayoutReflection* layout)
+ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::TypeLayoutReflection* layout)
{
initBase(renderer, session, layout);
m_subObjectCount = 0;
m_resourceCount = 0;
-
+
m_elementTypeLayout = _unwrapParameterGroups(layout, m_containerType);
m_size = m_elementTypeLayout->getSize();
@@ -44,7 +47,8 @@ ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(RendererBase* renderer, slang::IS
// linear search over the descriptor ranges for a specific binding range.
//
auto uniformOffset = m_elementTypeLayout->getDescriptorSetDescriptorRangeIndexOffset(
- descriptorSetIndex, rangeIndexInDescriptorSet);
+ descriptorSetIndex,
+ rangeIndexInDescriptorSet);
Index baseIndex = 0;
Index subObjectIndex = 0;
@@ -103,8 +107,10 @@ ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(RendererBase* renderer, slang::IS
RefPtr<ShaderObjectLayoutImpl> subObjectLayout;
if (slangBindingType != slang::BindingType::ExistentialValue)
{
- subObjectLayout =
- new ShaderObjectLayoutImpl(renderer, m_slangSession, slangLeafTypeLayout->getElementTypeLayout());
+ subObjectLayout = new ShaderObjectLayoutImpl(
+ renderer,
+ m_slangSession,
+ slangLeafTypeLayout->getElementTypeLayout());
}
SubObjectRangeInfo subObjectRange;
@@ -119,35 +125,50 @@ size_t ShaderObjectLayoutImpl::getSize()
return m_size;
}
-Index ShaderObjectLayoutImpl::getResourceCount() const { return m_resourceCount; }
-Index ShaderObjectLayoutImpl::getSubObjectCount() const { return m_subObjectCount; }
-List<SubObjectRangeInfo>& ShaderObjectLayoutImpl::getSubObjectRanges() { return subObjectRanges; }
-BindingRangeInfo ShaderObjectLayoutImpl::getBindingRange(Index index) { return m_bindingRanges[index]; }
-Index ShaderObjectLayoutImpl::getBindingRangeCount() const { return m_bindingRanges.getCount(); }
+Index ShaderObjectLayoutImpl::getResourceCount() const
+{
+ return m_resourceCount;
+}
+Index ShaderObjectLayoutImpl::getSubObjectCount() const
+{
+ return m_subObjectCount;
+}
+List<SubObjectRangeInfo>& ShaderObjectLayoutImpl::getSubObjectRanges()
+{
+ return subObjectRanges;
+}
+BindingRangeInfo ShaderObjectLayoutImpl::getBindingRange(Index index)
+{
+ return m_bindingRanges[index];
+}
+Index ShaderObjectLayoutImpl::getBindingRangeCount() const
+{
+ return m_bindingRanges.getCount();
+}
const char* EntryPointLayoutImpl::getEntryPointName()
{
return m_entryPointLayout->getName();
}
-RootShaderObjectLayoutImpl::RootShaderObjectLayoutImpl(RendererBase* renderer, slang::ISession* session, slang::ProgramLayout* programLayout)
+RootShaderObjectLayoutImpl::RootShaderObjectLayoutImpl(
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::ProgramLayout* programLayout)
: ShaderObjectLayoutImpl(renderer, session, programLayout->getGlobalParamsTypeLayout())
, m_programLayout(programLayout)
{
- for (UInt i =0; i< programLayout->getEntryPointCount(); i++)
+ for (UInt i = 0; i < programLayout->getEntryPointCount(); i++)
{
- m_entryPointLayouts.add(new EntryPointLayoutImpl(
- renderer,
- session,
- programLayout->getEntryPointByIndex(i)));
+ m_entryPointLayouts.add(
+ new EntryPointLayoutImpl(renderer, session, programLayout->getEntryPointByIndex(i)));
}
-
}
int RootShaderObjectLayoutImpl::getKernelIndex(UnownedStringSlice kernelName)
{
- auto entryPointCount = (int) m_programLayout->getEntryPointCount();
- for(int i = 0; i < entryPointCount; i++)
+ auto entryPointCount = (int)m_programLayout->getEntryPointCount();
+ for (int i = 0; i < entryPointCount; i++)
{
auto entryPoint = m_programLayout->getEntryPointByIndex(i);
if (kernelName == entryPoint->getName())
@@ -164,7 +185,10 @@ void RootShaderObjectLayoutImpl::getKernelThreadGroupSize(int kernelIndex, UInt*
entryPoint->getComputeThreadGroupSize(3, threadGroupSizes);
}
-EntryPointLayoutImpl* RootShaderObjectLayoutImpl::getEntryPoint(Index index) { return m_entryPointLayouts[index]; }
+EntryPointLayoutImpl* RootShaderObjectLayoutImpl::getEntryPoint(Index index)
+{
+ return m_entryPointLayouts[index];
+}
} // namespace cpu
} // namespace gfx
diff --git a/tools/gfx/cpu/cpu-shader-object-layout.h b/tools/gfx/cpu/cpu-shader-object-layout.h
index 3bf2e2aa7..b5439f370 100644
--- a/tools/gfx/cpu/cpu-shader-object-layout.h
+++ b/tools/gfx/cpu/cpu-shader-object-layout.h
@@ -43,7 +43,6 @@ struct SubObjectRangeInfo
class ShaderObjectLayoutImpl : public ShaderObjectLayoutBase
{
public:
-
// TODO: Once memory lifetime stuff is handled, there is
// no specific need to even track binding or sub-object
// ranges for CPU.
@@ -55,7 +54,10 @@ public:
Index m_subObjectCount = 0;
Index m_resourceCount = 0;
- ShaderObjectLayoutImpl(RendererBase* renderer, slang::ISession* session, slang::TypeLayoutReflection* layout);
+ ShaderObjectLayoutImpl(
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::TypeLayoutReflection* layout);
size_t getSize();
Index getResourceCount() const;
@@ -72,12 +74,13 @@ private:
public:
EntryPointLayoutImpl(
- RendererBase* renderer,
- slang::ISession* session,
- slang::EntryPointLayout* entryPointLayout)
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::EntryPointLayout* entryPointLayout)
: ShaderObjectLayoutImpl(renderer, session, entryPointLayout->getTypeLayout())
, m_entryPointLayout(entryPointLayout)
- {}
+ {
+ }
const char* getEntryPointName();
};
@@ -88,7 +91,10 @@ public:
slang::ProgramLayout* m_programLayout = nullptr;
List<RefPtr<EntryPointLayoutImpl>> m_entryPointLayouts;
- RootShaderObjectLayoutImpl(RendererBase* renderer, slang::ISession* session, slang::ProgramLayout* programLayout);
+ RootShaderObjectLayoutImpl(
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::ProgramLayout* programLayout);
int getKernelIndex(UnownedStringSlice kernelName);
void getKernelThreadGroupSize(int kernelIndex, UInt* threadGroupSizes);
diff --git a/tools/gfx/cpu/cpu-shader-object.cpp b/tools/gfx/cpu/cpu-shader-object.cpp
index 67ffd6af5..3c9dd3cb2 100644
--- a/tools/gfx/cpu/cpu-shader-object.cpp
+++ b/tools/gfx/cpu/cpu-shader-object.cpp
@@ -54,7 +54,6 @@ ResourceViewBase* CPUShaderObjectData::getResourceView(
viewDesc.type = IResourceView::Type::UnorderedAccess;
viewDesc.format = Format::Unknown;
m_bufferView = new BufferResourceViewImpl(viewDesc, m_bufferResource);
-
}
m_bufferResource->getDesc()->sizeInBytes = m_ordinaryData.getCount();
m_bufferResource->m_data = m_ordinaryData.getBuffer();
@@ -129,7 +128,7 @@ SLANG_NO_THROW GfxCount SLANG_MCALL ShaderObjectImpl::getEntryPointCount()
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
+ShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
{
*outEntryPoint = nullptr;
return SLANG_OK;
@@ -146,7 +145,7 @@ SLANG_NO_THROW size_t SLANG_MCALL ShaderObjectImpl::getSize()
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setData(ShaderOffset const& offset, void const* data, size_t size)
+ShaderObjectImpl::setData(ShaderOffset const& offset, void const* data, size_t size)
{
size = Math::Min(size, size_t(m_data.getCount() - offset.uniformOffset));
memcpy((char*)m_data.getBuffer() + offset.uniformOffset, data, size);
@@ -154,7 +153,7 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView* inView)
+ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView* inView)
{
auto layout = getLayout();
@@ -172,40 +171,40 @@ SLANG_NO_THROW Result SLANG_MCALL
switch (view->getViewKind())
{
case ResourceViewImpl::Kind::Texture:
- {
- auto textureView = static_cast<TextureResourceViewImpl*>(view);
+ {
+ auto textureView = static_cast<TextureResourceViewImpl*>(view);
- slang_prelude::IRWTexture* textureObj = textureView;
- SLANG_RETURN_ON_FAIL(setData(offset, &textureObj, sizeof(textureObj)));
- }
- break;
+ slang_prelude::IRWTexture* textureObj = textureView;
+ SLANG_RETURN_ON_FAIL(setData(offset, &textureObj, sizeof(textureObj)));
+ }
+ break;
case ResourceViewImpl::Kind::Buffer:
- {
- auto bufferView = static_cast<BufferResourceViewImpl*>(view);
- auto buffer = bufferView->getBuffer();
- auto desc = *buffer->getDesc();
+ {
+ auto bufferView = static_cast<BufferResourceViewImpl*>(view);
+ auto buffer = bufferView->getBuffer();
+ auto desc = *buffer->getDesc();
- void* dataPtr = buffer->m_data;
- size_t size = desc.sizeInBytes;
- if (desc.elementSize > 1)
- size /= desc.elementSize;
+ void* dataPtr = buffer->m_data;
+ size_t size = desc.sizeInBytes;
+ if (desc.elementSize > 1)
+ size /= desc.elementSize;
- auto ptrOffset = offset;
- SLANG_RETURN_ON_FAIL(setData(ptrOffset, &dataPtr, sizeof(dataPtr)));
+ auto ptrOffset = offset;
+ SLANG_RETURN_ON_FAIL(setData(ptrOffset, &dataPtr, sizeof(dataPtr)));
- auto sizeOffset = offset;
- sizeOffset.uniformOffset += sizeof(dataPtr);
- SLANG_RETURN_ON_FAIL(setData(sizeOffset, &size, sizeof(size)));
- }
- break;
+ auto sizeOffset = offset;
+ sizeOffset.uniformOffset += sizeof(dataPtr);
+ SLANG_RETURN_ON_FAIL(setData(sizeOffset, &size, sizeof(size)));
+ }
+ break;
}
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setObject(ShaderOffset const& offset, IShaderObject* object)
+ShaderObjectImpl::setObject(ShaderOffset const& offset, IShaderObject* object)
{
SLANG_RETURN_ON_FAIL(Super::setObject(offset, object));
@@ -217,21 +216,20 @@ SLANG_NO_THROW Result SLANG_MCALL
switch (bindingRange.bindingType)
{
default:
- {
- void* bufferPtr = subObject->m_data.getBuffer();
- SLANG_RETURN_ON_FAIL(setData(offset, &bufferPtr, sizeof(void*)));
- }
- break;
+ {
+ void* bufferPtr = subObject->m_data.getBuffer();
+ SLANG_RETURN_ON_FAIL(setData(offset, &bufferPtr, sizeof(void*)));
+ }
+ break;
case slang::BindingType::ExistentialValue:
case slang::BindingType::RawBuffer:
- case slang::BindingType::MutableRawBuffer:
- break;
+ case slang::BindingType::MutableRawBuffer: break;
}
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* sampler)
+ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* sampler)
{
SLANG_UNUSED(sampler);
SLANG_UNUSED(offset);
@@ -239,7 +237,9 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL ShaderObjectImpl::setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler)
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler)
{
SLANG_UNUSED(sampler);
setResource(offset, textureView);
@@ -294,7 +294,7 @@ SLANG_NO_THROW GfxCount SLANG_MCALL RootShaderObjectImpl::getEntryPointCount()
}
SLANG_NO_THROW Result SLANG_MCALL
- RootShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
+RootShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
{
returnComPtr(outEntryPoint, m_entryPoints[index]);
return SLANG_OK;
diff --git a/tools/gfx/cpu/cpu-shader-object.h b/tools/gfx/cpu/cpu-shader-object.h
index 2be703dc5..dc7199509 100644
--- a/tools/gfx/cpu/cpu-shader-object.h
+++ b/tools/gfx/cpu/cpu-shader-object.h
@@ -1,7 +1,6 @@
// cpu-shader-object.h
#pragma once
#include "cpu-base.h"
-
#include "cpu-shader-object-layout.h"
namespace gfx
@@ -36,38 +35,43 @@ public:
class ShaderObjectImpl
: public ShaderObjectBaseImpl<ShaderObjectImpl, ShaderObjectLayoutImpl, CPUShaderObjectData>
{
- typedef ShaderObjectBaseImpl<ShaderObjectImpl, ShaderObjectLayoutImpl, CPUShaderObjectData> Super;
+ typedef ShaderObjectBaseImpl<ShaderObjectImpl, ShaderObjectLayoutImpl, CPUShaderObjectData>
+ Super;
public:
List<RefPtr<ResourceViewImpl>> m_resources;
virtual SLANG_NO_THROW Result SLANG_MCALL
- init(IDevice* device, ShaderObjectLayoutImpl* typeLayout);
+ init(IDevice* device, ShaderObjectLayoutImpl* typeLayout);
virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override;
virtual SLANG_NO_THROW size_t SLANG_MCALL getSize() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& offset, void const* data, size_t size) override;
+ setData(ShaderOffset const& offset, void const* data, size_t size) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* inView) override;
+ setResource(ShaderOffset const& offset, IResourceView* inView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setObject(ShaderOffset const& offset, IShaderObject* object) override;
+ setObject(ShaderOffset const& offset, IShaderObject* object) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
+ setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) override;
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) override;
char* getDataBuffer();
};
-class MutableShaderObjectImpl : public MutableShaderObject<MutableShaderObjectImpl, ShaderObjectLayoutImpl>
-{};
+class MutableShaderObjectImpl
+ : public MutableShaderObject<MutableShaderObjectImpl, ShaderObjectLayoutImpl>
+{
+};
class EntryPointShaderObjectImpl : public ShaderObjectImpl
{
@@ -92,7 +96,7 @@ public:
virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override;
};
diff --git a/tools/gfx/cpu/cpu-shader-program.h b/tools/gfx/cpu/cpu-shader-program.h
index f2f159538..6c92151fa 100644
--- a/tools/gfx/cpu/cpu-shader-program.h
+++ b/tools/gfx/cpu/cpu-shader-program.h
@@ -1,7 +1,6 @@
// cpu-shader-program.h
#pragma once
#include "cpu-base.h"
-
#include "cpu-shader-object-layout.h"
namespace gfx
@@ -16,9 +15,7 @@ class ShaderProgramImpl : public ShaderProgramBase
public:
RefPtr<RootShaderObjectLayoutImpl> layout;
- ~ShaderProgramImpl()
- {
- }
+ ~ShaderProgramImpl() {}
};
} // namespace cpu
diff --git a/tools/gfx/cpu/cpu-texture.cpp b/tools/gfx/cpu/cpu-texture.cpp
index d5367bd96..9077084f2 100644
--- a/tools/gfx/cpu/cpu-texture.cpp
+++ b/tools/gfx/cpu/cpu-texture.cpp
@@ -18,7 +18,7 @@ void _unpackFloatTexel(void const* texelData, void* outData, size_t outSize)
{
auto input = (float const*)texelData;
- float temp[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
+ float temp[4] = {0.0f, 0.0f, 0.0f, 1.0f};
for (int i = 0; i < N; ++i)
temp[i] = input[i];
@@ -30,7 +30,7 @@ void _unpackFloat16Texel(void const* texelData, void* outData, size_t outSize)
{
auto input = (int16_t const*)texelData;
- float temp[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
+ float temp[4] = {0.0f, 0.0f, 0.0f, 1.0f};
for (int i = 0; i < N; ++i)
temp[i] = HalfToFloat(input[i]);
@@ -47,7 +47,7 @@ void _unpackUnorm8Texel(void const* texelData, void* outData, size_t outSize)
{
auto input = (uint8_t const*)texelData;
- float temp[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
+ float temp[4] = {0.0f, 0.0f, 0.0f, 1.0f};
for (int i = 0; i < N; ++i)
temp[i] = _unpackUnorm8Value(input[i]);
@@ -72,7 +72,7 @@ void _unpackUInt16Texel(void const* texelData, void* outData, size_t outSize)
{
auto input = (uint16_t const*)texelData;
- uint32_t temp[4] = { 0, 0, 0, 0 };
+ uint32_t temp[4] = {0, 0, 0, 0};
for (int i = 0; i < N; ++i)
temp[i] = input[i];
@@ -84,7 +84,7 @@ void _unpackUInt32Texel(void const* texelData, void* outData, size_t outSize)
{
auto input = (uint32_t const*)texelData;
- uint32_t temp[4] = { 0, 0, 0, 0 };
+ uint32_t temp[4] = {0, 0, 0, 0};
for (int i = 0; i < N; ++i)
temp[i] = input[i];
@@ -117,16 +117,16 @@ Result TextureResourceImpl::init(ITextureResource::SubresourceData const* initDa
uint32_t texelSize = uint32_t(texelInfo.blockSizeInBytes / texelInfo.pixelsPerBlock);
m_texelSize = texelSize;
- int32_t formatBlockSize[kMaxRank] = { 1, 1, 1 };
+ int32_t formatBlockSize[kMaxRank] = {1, 1, 1};
auto baseShapeInfo = _getBaseShapeInfo(desc.type);
m_baseShape = baseShapeInfo;
- if(!baseShapeInfo)
+ if (!baseShapeInfo)
return SLANG_FAIL;
auto formatInfo = _getFormatInfo(desc.format);
m_formatInfo = formatInfo;
- if(!formatInfo)
+ if (!formatInfo)
return SLANG_FAIL;
int32_t rank = baseShapeInfo->rank;
@@ -139,7 +139,7 @@ Result TextureResourceImpl::init(ITextureResource::SubresourceData const* initDa
extents[1] = desc.size.height;
extents[2] = desc.size.depth;
- for(int32_t axis = rank; axis < kMaxRank; ++axis)
+ for (int32_t axis = rank; axis < kMaxRank; ++axis)
extents[axis] = 1;
int32_t levelCount = desc.numMipLevels;
@@ -147,26 +147,27 @@ Result TextureResourceImpl::init(ITextureResource::SubresourceData const* initDa
m_mipLevels.setCount(levelCount);
int64_t totalDataSize = 0;
- for( int32_t levelIndex = 0; levelIndex < levelCount; ++levelIndex )
+ for (int32_t levelIndex = 0; levelIndex < levelCount; ++levelIndex)
{
auto& level = m_mipLevels[levelIndex];
- for( int32_t axis = 0; axis < kMaxRank; ++axis )
+ for (int32_t axis = 0; axis < kMaxRank; ++axis)
{
int32_t extent = extents[axis] >> levelIndex;
- if(extent < 1) extent = 1;
+ if (extent < 1)
+ extent = 1;
level.extents[axis] = extent;
}
level.strides[0] = texelSize;
- for( int32_t axis = 1; axis < kMaxRank+1; ++axis)
+ for (int32_t axis = 1; axis < kMaxRank + 1; ++axis)
{
- level.strides[axis] = level.strides[axis-1]*level.extents[axis-1];
+ level.strides[axis] = level.strides[axis - 1] * level.extents[axis - 1];
}
int64_t levelDataSize = texelSize;
levelDataSize *= effectiveArrayElementCount;
- for( int32_t axis = 0; axis < rank; ++axis)
+ for (int32_t axis = 0; axis < rank; ++axis)
levelDataSize *= int64_t(level.extents[axis]);
level.offset = totalDataSize;
@@ -176,12 +177,13 @@ Result TextureResourceImpl::init(ITextureResource::SubresourceData const* initDa
void* textureData = malloc((size_t)totalDataSize);
m_data = textureData;
- if( initData )
+ if (initData)
{
int32_t subResourceCounter = 0;
- for(int32_t arrayElementIndex = 0; arrayElementIndex < effectiveArrayElementCount; ++arrayElementIndex)
+ for (int32_t arrayElementIndex = 0; arrayElementIndex < effectiveArrayElementCount;
+ ++arrayElementIndex)
{
- for(int32_t mipLevel = 0; mipLevel < m_desc.numMipLevels; ++mipLevel)
+ for (int32_t mipLevel = 0; mipLevel < m_desc.numMipLevels; ++mipLevel)
{
int32_t subResourceIndex = subResourceCounter++;
@@ -189,7 +191,7 @@ Result TextureResourceImpl::init(ITextureResource::SubresourceData const* initDa
auto dstLayerStride = m_mipLevels[mipLevel].strides[2];
auto dstArrayStride = m_mipLevels[mipLevel].strides[3];
- auto textureRowSize = m_mipLevels[mipLevel].extents[0]*texelSize;
+ auto textureRowSize = m_mipLevels[mipLevel].extents[0] * texelSize;
auto rowCount = m_mipLevels[mipLevel].extents[1];
auto depthLayerCount = m_mipLevels[mipLevel].extents[2];
@@ -199,17 +201,17 @@ Result TextureResourceImpl::init(ITextureResource::SubresourceData const* initDa
ptrdiff_t srcLayerStride = ptrdiff_t(srcImage.strideZ);
char* dstLevel = (char*)textureData + m_mipLevels[mipLevel].offset;
- char* dstImage = dstLevel + dstArrayStride*arrayElementIndex;
+ char* dstImage = dstLevel + dstArrayStride * arrayElementIndex;
- const char* srcLayer = (const char*) srcImage.data;
+ const char* srcLayer = (const char*)srcImage.data;
char* dstLayer = dstImage;
- for(int32_t depthLayer = 0; depthLayer < depthLayerCount; ++depthLayer)
+ for (int32_t depthLayer = 0; depthLayer < depthLayerCount; ++depthLayer)
{
const char* srcRow = srcLayer;
char* dstRow = dstLayer;
- for(int32_t row = 0; row < rowCount; ++row)
+ for (int32_t row = 0; row < rowCount; ++row)
{
memcpy(dstRow, srcRow, textureRowSize);
diff --git a/tools/gfx/cpu/cpu-texture.h b/tools/gfx/cpu/cpu-texture.h
index 5ae896d0f..e65f8f4be 100644
--- a/tools/gfx/cpu/cpu-texture.h
+++ b/tools/gfx/cpu/cpu-texture.h
@@ -16,14 +16,14 @@ struct CPUTextureBaseShapeInfo
int32_t implicitArrayElementCount;
};
-static const CPUTextureBaseShapeInfo kCPUTextureBaseShapeInfos[(int)ITextureResource::Type::_Count] =
-{
- /* Unknown */ { 0, 0, 0 },
- /* Buffer */ { 1, 1, 1 },
- /* Texture1D */ { 1, 1, 1 },
- /* Texture2D */ { 2, 2, 1 },
- /* Texture3D */ { 3, 3, 1 },
- /* TextureCube */ { 2, 3, 6 },
+static const CPUTextureBaseShapeInfo
+ kCPUTextureBaseShapeInfos[(int)ITextureResource::Type::_Count] = {
+ /* Unknown */ {0, 0, 0},
+ /* Buffer */ {1, 1, 1},
+ /* Texture1D */ {1, 1, 1},
+ /* Texture2D */ {2, 2, 1},
+ /* Texture3D */ {3, 3, 1},
+ /* TextureCube */ {2, 3, 6},
};
static CPUTextureBaseShapeInfo const* _getBaseShapeInfo(ITextureResource::Type baseShape);
@@ -82,7 +82,10 @@ struct CPUFormatInfoMap
auto& info = m_infos[Index(format)];
info.unpackFunc = func;
}
- SLANG_FORCE_INLINE const CPUTextureFormatInfo& get(Format format) const { return m_infos[Index(format)]; }
+ SLANG_FORCE_INLINE const CPUTextureFormatInfo& get(Format format) const
+ {
+ return m_infos[Index(format)];
+ }
CPUTextureFormatInfo m_infos[Index(Format::_Count)];
};
@@ -97,12 +100,16 @@ static CPUTextureFormatInfo const* _getFormatInfo(Format format)
class TextureResourceImpl : public TextureResource
{
- enum { kMaxRank = 3 };
+ enum
+ {
+ kMaxRank = 3
+ };
public:
TextureResourceImpl(const TextureResource::Desc& desc)
: TextureResource(desc)
- {}
+ {
+ }
~TextureResourceImpl();
Result init(ITextureResource::SubresourceData const* initData);
@@ -119,11 +126,11 @@ public:
struct MipLevel
{
int32_t extents[kMaxRank];
- int64_t strides[kMaxRank+1];
+ int64_t strides[kMaxRank + 1];
int64_t offset;
};
- List<MipLevel> m_mipLevels;
- void* m_data = nullptr;
+ List<MipLevel> m_mipLevels;
+ void* m_data = nullptr;
};
} // namespace cpu
diff --git a/tools/gfx/cuda/cuda-base.h b/tools/gfx/cuda/cuda-base.h
index 63c280cde..11a798636 100644
--- a/tools/gfx/cuda/cuda-base.h
+++ b/tools/gfx/cuda/cuda-base.h
@@ -3,32 +3,32 @@
#pragma once
#ifdef GFX_ENABLE_CUDA
-#include <cuda.h>
-#include "core/slang-basic.h"
-#include "core/slang-blob.h"
-#include "core/slang-std-writers.h"
-
-#include "slang.h"
-#include "slang-com-ptr.h"
-#include "slang-com-helper.h"
+#include "../command-encoder-com-forward.h"
#include "../command-writer.h"
-#include "../renderer-shared.h"
#include "../mutable-shader-object.h"
+#include "../renderer-shared.h"
#include "../simple-transient-resource-heap.h"
#include "../slang-context.h"
-#include "../command-encoder-com-forward.h"
+#include "core/slang-basic.h"
+#include "core/slang-blob.h"
+#include "core/slang-std-writers.h"
+#include "slang-com-helper.h"
+#include "slang-com-ptr.h"
+#include "slang.h"
+
+#include <cuda.h>
-# ifdef RENDER_TEST_OPTIX
+#ifdef RENDER_TEST_OPTIX
// The `optix_stubs.h` header produces warnings when compiled with MSVC
-# ifdef _MSC_VER
-# pragma warning(disable: 4996)
-# endif
+#ifdef _MSC_VER
+#pragma warning(disable : 4996)
+#endif
-# include <optix.h>
-# include <optix_function_table_definition.h>
-# include <optix_stubs.h>
-# endif
+#include <optix.h>
+#include <optix_function_table_definition.h>
+#include <optix_stubs.h>
+#endif
#endif
@@ -36,23 +36,23 @@ namespace gfx
{
namespace cuda
{
- class CUDAContext;
- class BufferResourceImpl;
- class TextureResourceImpl;
- class ResourceViewImpl;
- class ShaderObjectLayoutImpl;
- class RootShaderObjectLayoutImpl;
- class ShaderObjectImpl;
- class MutableShaderObjectImpl;
- class EntryPointShaderObjectImpl;
- class RootShaderObjectImpl;
- class ShaderProgramImpl;
- class PipelineStateImpl;
- class QueryPoolImpl;
- class DeviceImpl;
- class CommandBufferImpl;
- class ResourceCommandEncoderImpl;
- class ComputeCommandEncoderImpl;
- class CommandQueueImpl;
-}
-}
+class CUDAContext;
+class BufferResourceImpl;
+class TextureResourceImpl;
+class ResourceViewImpl;
+class ShaderObjectLayoutImpl;
+class RootShaderObjectLayoutImpl;
+class ShaderObjectImpl;
+class MutableShaderObjectImpl;
+class EntryPointShaderObjectImpl;
+class RootShaderObjectImpl;
+class ShaderProgramImpl;
+class PipelineStateImpl;
+class QueryPoolImpl;
+class DeviceImpl;
+class CommandBufferImpl;
+class ResourceCommandEncoderImpl;
+class ComputeCommandEncoderImpl;
+class CommandQueueImpl;
+} // namespace cuda
+} // namespace gfx
diff --git a/tools/gfx/cuda/cuda-buffer.cpp b/tools/gfx/cuda/cuda-buffer.cpp
index bc4ef32ef..63c94b459 100644
--- a/tools/gfx/cuda/cuda-buffer.cpp
+++ b/tools/gfx/cuda/cuda-buffer.cpp
@@ -19,7 +19,10 @@ BufferResourceImpl::~BufferResourceImpl()
}
}
-uint64_t BufferResourceImpl::getBindlessHandle() { return (uint64_t)m_cudaMemory; }
+uint64_t BufferResourceImpl::getBindlessHandle()
+{
+ return (uint64_t)m_cudaMemory;
+}
DeviceAddress BufferResourceImpl::getDeviceAddress()
{
diff --git a/tools/gfx/cuda/cuda-buffer.h b/tools/gfx/cuda/cuda-buffer.h
index 838a06555..c83ab755d 100644
--- a/tools/gfx/cuda/cuda-buffer.h
+++ b/tools/gfx/cuda/cuda-buffer.h
@@ -16,7 +16,8 @@ class BufferResourceImpl : public BufferResource
public:
BufferResourceImpl(const Desc& _desc)
: BufferResource(_desc)
- {}
+ {
+ }
~BufferResourceImpl();
@@ -28,9 +29,10 @@ public:
RefPtr<CUDAContext> m_cudaContext;
virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- map(MemoryRange* rangeToRead, void** outPointer) override;
+ getNativeResourceHandle(InteropHandle* outHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ map(MemoryRange* rangeToRead, void** outPointer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL unmap(MemoryRange* writtenRange) override;
};
diff --git a/tools/gfx/cuda/cuda-command-buffer.cpp b/tools/gfx/cuda/cuda-command-buffer.cpp
index efb2486f4..ce95a2196 100644
--- a/tools/gfx/cuda/cuda-command-buffer.cpp
+++ b/tools/gfx/cuda/cuda-command-buffer.cpp
@@ -33,21 +33,21 @@ SLANG_NO_THROW void SLANG_MCALL CommandBufferImpl::encodeRenderCommands(
}
SLANG_NO_THROW void SLANG_MCALL
- CommandBufferImpl::encodeResourceCommands(IResourceCommandEncoder** outEncoder)
+CommandBufferImpl::encodeResourceCommands(IResourceCommandEncoder** outEncoder)
{
m_resourceCommandEncoder.init(this);
*outEncoder = &m_resourceCommandEncoder;
}
SLANG_NO_THROW void SLANG_MCALL
- CommandBufferImpl::encodeComputeCommands(IComputeCommandEncoder** outEncoder)
+CommandBufferImpl::encodeComputeCommands(IComputeCommandEncoder** outEncoder)
{
m_computeCommandEncoder.init(this);
*outEncoder = &m_computeCommandEncoder;
}
SLANG_NO_THROW void SLANG_MCALL
- CommandBufferImpl::encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder)
+CommandBufferImpl::encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder)
{
*outEncoder = nullptr;
}
diff --git a/tools/gfx/cuda/cuda-command-buffer.h b/tools/gfx/cuda/cuda-command-buffer.h
index 76d9aa01f..05329d67c 100644
--- a/tools/gfx/cuda/cuda-command-buffer.h
+++ b/tools/gfx/cuda/cuda-command-buffer.h
@@ -11,14 +11,11 @@ using namespace Slang;
namespace cuda
{
-class CommandBufferImpl
- : public ICommandBuffer
- , public CommandWriter
- , public ComObject
+class CommandBufferImpl : public ICommandBuffer, public CommandWriter, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
- ICommandBuffer* getInterface(const Guid& guid);
+ ICommandBuffer* getInterface(const Guid& guid);
public:
DeviceImpl* m_device;
@@ -33,11 +30,11 @@ public:
IRenderCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
+ encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
+ encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
+ encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL close() override {}
diff --git a/tools/gfx/cuda/cuda-command-encoder.cpp b/tools/gfx/cuda/cuda-command-encoder.cpp
index d94b40e21..1f4afcc5c 100644
--- a/tools/gfx/cuda/cuda-command-encoder.cpp
+++ b/tools/gfx/cuda/cuda-command-encoder.cpp
@@ -13,7 +13,7 @@ namespace cuda
{
void ResourceCommandEncoderImpl::init(CommandBufferImpl* cmdBuffer)
-{
+{
m_writer = cmdBuffer;
}
@@ -28,13 +28,16 @@ SLANG_NO_THROW void SLANG_MCALL ResourceCommandEncoderImpl::copyBuffer(
}
SLANG_NO_THROW void SLANG_MCALL ResourceCommandEncoderImpl::uploadBufferData(
- IBufferResource* dst, Offset offset, Size size, void* data)
+ IBufferResource* dst,
+ Offset offset,
+ Size size,
+ void* data)
{
m_writer->uploadBufferData(dst, offset, size, data);
}
SLANG_NO_THROW void SLANG_MCALL
- ResourceCommandEncoderImpl::writeTimestamp(IQueryPool* pool, GfxIndex index)
+ResourceCommandEncoderImpl::writeTimestamp(IQueryPool* pool, GfxIndex index)
{
m_writer->writeTimestamp(pool, index);
}
@@ -159,7 +162,7 @@ SLANG_NO_THROW void SLANG_MCALL ResourceCommandEncoderImpl::textureSubresourceBa
}
SLANG_NO_THROW void SLANG_MCALL
- ResourceCommandEncoderImpl::beginDebugEvent(const char* name, float rgbColor[3])
+ResourceCommandEncoderImpl::beginDebugEvent(const char* name, float rgbColor[3])
{
SLANG_UNUSED(name);
SLANG_UNUSED(rgbColor);
@@ -172,23 +175,26 @@ void ComputeCommandEncoderImpl::init(CommandBufferImpl* cmdBuffer)
}
SLANG_NO_THROW Result SLANG_MCALL
- ComputeCommandEncoderImpl::bindPipeline(IPipelineState* state, IShaderObject** outRootObject)
+ComputeCommandEncoderImpl::bindPipeline(IPipelineState* state, IShaderObject** outRootObject)
{
m_writer->setPipelineState(state);
PipelineStateBase* pipelineImpl = static_cast<PipelineStateBase*>(state);
SLANG_RETURN_ON_FAIL(m_commandBuffer->m_device->createRootShaderObject(
- pipelineImpl->m_program, m_rootObject.writeRef()));
+ pipelineImpl->m_program,
+ m_rootObject.writeRef()));
returnComPtr(outRootObject, m_rootObject);
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL
- ComputeCommandEncoderImpl::bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject)
+SLANG_NO_THROW Result SLANG_MCALL ComputeCommandEncoderImpl::bindPipelineWithRootObject(
+ IPipelineState* state,
+ IShaderObject* rootObject)
{
m_writer->setPipelineState(state);
PipelineStateBase* pipelineImpl = static_cast<PipelineStateBase*>(state);
SLANG_RETURN_ON_FAIL(m_commandBuffer->m_device->createRootShaderObject(
- pipelineImpl->m_program, m_rootObject.writeRef()));
+ pipelineImpl->m_program,
+ m_rootObject.writeRef()));
m_rootObject->copyFrom(rootObject, m_commandBuffer->m_transientHeap);
return SLANG_OK;
}
@@ -201,7 +207,7 @@ SLANG_NO_THROW Result SLANG_MCALL ComputeCommandEncoderImpl::dispatchCompute(int
}
SLANG_NO_THROW Result SLANG_MCALL
- ComputeCommandEncoderImpl::dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset)
+ComputeCommandEncoderImpl::dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset)
{
SLANG_UNIMPLEMENTED_X("dispatchComputeIndirect");
}
diff --git a/tools/gfx/cuda/cuda-command-encoder.h b/tools/gfx/cuda/cuda-command-encoder.h
index ab8aa8f8f..e845e1962 100644
--- a/tools/gfx/cuda/cuda-command-encoder.h
+++ b/tools/gfx/cuda/cuda-command-encoder.h
@@ -22,7 +22,7 @@ public:
return nullptr;
}
virtual SLANG_NO_THROW SlangResult SLANG_MCALL
- queryInterface(SlangUUID const& uuid, void** outObject) override
+ queryInterface(SlangUUID const& uuid, void** outObject) override
{
if (auto ptr = getInterface(uuid))
{
@@ -49,20 +49,22 @@ public:
ITextureResource* const* textures,
ResourceState src,
ResourceState dst) override
- {}
+ {
+ }
virtual SLANG_NO_THROW void SLANG_MCALL bufferBarrier(
GfxCount count,
IBufferResource* const* buffers,
ResourceState src,
ResourceState dst) override
- {}
+ {
+ }
- virtual SLANG_NO_THROW void SLANG_MCALL uploadBufferData(
- IBufferResource* dst, Offset offset, Size size, void* data) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ uploadBufferData(IBufferResource* dst, Offset offset, Size size, void* data) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- writeTimestamp(IQueryPool* pool, GfxIndex index) override;
+ writeTimestamp(IQueryPool* pool, GfxIndex index) override;
virtual SLANG_NO_THROW void SLANG_MCALL copyTexture(
ITextureResource* dst,
@@ -120,22 +122,22 @@ public:
ResourceState src,
ResourceState dst) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- beginDebugEvent(const char* name, float rgbColor[3]) override;
+ beginDebugEvent(const char* name, float rgbColor[3]) override;
virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent() override {}
};
-class ComputeCommandEncoderImpl
- : public IComputeCommandEncoder
- , public ResourceCommandEncoderImpl
+class ComputeCommandEncoderImpl : public IComputeCommandEncoder, public ResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoderImpl)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
return this;
return nullptr;
}
+
public:
CommandWriter* m_writer;
CommandBufferImpl* m_commandBuffer;
@@ -144,15 +146,15 @@ public:
void init(CommandBufferImpl* cmdBuffer);
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL dispatchCompute(int x, int y, int z) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override;
+ dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override;
};
} // namespace cuda
diff --git a/tools/gfx/cuda/cuda-command-queue.cpp b/tools/gfx/cuda/cuda-command-queue.cpp
index 5c6f2db26..4cc3e111d 100644
--- a/tools/gfx/cuda/cuda-command-queue.cpp
+++ b/tools/gfx/cuda/cuda-command-queue.cpp
@@ -36,7 +36,10 @@ CommandQueueImpl::~CommandQueueImpl()
}
SLANG_NO_THROW void SLANG_MCALL CommandQueueImpl::executeCommandBuffers(
- GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal)
+ GfxCount count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal)
{
SLANG_UNUSED(valueToSignal);
// TODO: implement fence.
@@ -55,7 +58,9 @@ SLANG_NO_THROW void SLANG_MCALL CommandQueueImpl::waitOnHost()
}
SLANG_NO_THROW Result SLANG_MCALL CommandQueueImpl::waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* waitValues)
{
return SLANG_FAIL;
}
@@ -115,8 +120,7 @@ void CommandQueueImpl::dispatchCompute(int x, int y, int z)
// stored in host memory in a CUDAEntryPointShaderObject, as expected by cuLaunchKernel.
//
auto entryPointBuffer = currentRootObject->entryPointObjects[kernelId]->getBuffer();
- auto entryPointDataSize =
- currentRootObject->entryPointObjects[kernelId]->getBufferSize();
+ auto entryPointDataSize = currentRootObject->entryPointObjects[kernelId]->getBufferSize();
void* extraOptions[] = {
CU_LAUNCH_PARAM_BUFFER_POINTER,
@@ -160,13 +164,14 @@ void CommandQueueImpl::copyBuffer(
size);
}
-void CommandQueueImpl::uploadBufferData(IBufferResource* dst, size_t offset, size_t size, void* data)
+void CommandQueueImpl::uploadBufferData(
+ IBufferResource* dst,
+ size_t offset,
+ size_t size,
+ void* data)
{
auto dstImpl = static_cast<BufferResourceImpl*>(dst);
- cuMemcpy(
- (CUdeviceptr)((uint8_t*)dstImpl->m_cudaMemory + offset),
- (CUdeviceptr)data,
- size);
+ cuMemcpy((CUdeviceptr)((uint8_t*)dstImpl->m_cudaMemory + offset), (CUdeviceptr)data, size);
}
void CommandQueueImpl::writeTimestamp(IQueryPool* pool, SlangInt index)
@@ -185,12 +190,10 @@ void CommandQueueImpl::execute(CommandBufferImpl* commandBuffer)
setPipelineState(commandBuffer->getObject<PipelineStateBase>(cmd.operands[0]));
break;
case CommandName::BindRootShaderObject:
- bindRootShaderObject(
- commandBuffer->getObject<ShaderObjectBase>(cmd.operands[0]));
+ bindRootShaderObject(commandBuffer->getObject<ShaderObjectBase>(cmd.operands[0]));
break;
case CommandName::DispatchCompute:
- dispatchCompute(
- int(cmd.operands[0]), int(cmd.operands[1]), int(cmd.operands[2]));
+ dispatchCompute(int(cmd.operands[0]), int(cmd.operands[1]), int(cmd.operands[2]));
break;
case CommandName::CopyBuffer:
copyBuffer(
diff --git a/tools/gfx/cuda/cuda-command-queue.h b/tools/gfx/cuda/cuda-command-queue.h
index 10601890e..91d73b184 100644
--- a/tools/gfx/cuda/cuda-command-queue.h
+++ b/tools/gfx/cuda/cuda-command-queue.h
@@ -1,11 +1,10 @@
// cuda-command-queue.h
#pragma once
#include "cuda-base.h"
-
#include "cuda-device.h"
+#include "cuda-helper-functions.h"
#include "cuda-pipeline-state.h"
#include "cuda-shader-object.h"
-#include "cuda-helper-functions.h"
namespace gfx
{
@@ -15,13 +14,11 @@ using namespace Slang;
namespace cuda
{
-class CommandQueueImpl
- : public ICommandQueue
- , public ComObject
+class CommandQueueImpl : public ICommandQueue, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
- ICommandQueue* getInterface(const Guid& guid);
+ ICommandQueue* getInterface(const Guid& guid);
RefPtr<ComputePipelineStateImpl> currentPipeline;
RefPtr<RootShaderObjectImpl> currentRootObject;
@@ -35,12 +32,15 @@ public:
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override { return m_desc; }
virtual SLANG_NO_THROW void SLANG_MCALL executeCommandBuffers(
- GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal) override;
+ GfxCount count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal) override;
virtual SLANG_NO_THROW void SLANG_MCALL waitOnHost() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ waitForFenceValuesOnDevice(GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outHandle) override;
diff --git a/tools/gfx/cuda/cuda-device.cpp b/tools/gfx/cuda/cuda-device.cpp
index b1b582d00..8162a20b8 100644
--- a/tools/gfx/cuda/cuda-device.cpp
+++ b/tools/gfx/cuda/cuda-device.cpp
@@ -5,10 +5,10 @@
#include "cuda-command-queue.h"
#include "cuda-pipeline-state.h"
#include "cuda-query.h"
-#include "cuda-shader-object.h"
+#include "cuda-resource-views.h"
#include "cuda-shader-object-layout.h"
+#include "cuda-shader-object.h"
#include "cuda-shader-program.h"
-#include "cuda-resource-views.h"
#include "cuda-texture.h"
namespace gfx
@@ -42,7 +42,7 @@ int DeviceImpl::_calcSMCountPerMultiProcessor(int major, int minor)
{0x62, 128},
{0x70, 64},
{0x72, 64},
- {0x75, 64} };
+ {0x75, 64}};
const int sm = ((major << 4) + minor);
for (Index i = 0; i < SLANG_COUNT_OF(infos); ++i)
@@ -78,9 +78,12 @@ SlangResult DeviceImpl::_findMaxFlopsDeviceIndex(int* outDeviceIndex)
CUdevice device;
SLANG_CUDA_RETURN_ON_FAIL(cuDeviceGet(&device, currentDevice));
int computeMode = -1, major = 0, minor = 0;
- SLANG_CUDA_RETURN_ON_FAIL(cuDeviceGetAttribute(&computeMode, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, device));
- SLANG_CUDA_RETURN_ON_FAIL(cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, device));
- SLANG_CUDA_RETURN_ON_FAIL(cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, device));
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuDeviceGetAttribute(&computeMode, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, device));
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, device));
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, device));
// If this GPU is not running on Compute Mode prohibited,
// then we can add it to the list
@@ -96,8 +99,12 @@ SlangResult DeviceImpl::_findMaxFlopsDeviceIndex(int* outDeviceIndex)
}
int multiProcessorCount = 0, clockRate = 0;
- SLANG_CUDA_RETURN_ON_FAIL(cuDeviceGetAttribute(&multiProcessorCount, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, device));
- SLANG_CUDA_RETURN_ON_FAIL(cuDeviceGetAttribute(&clockRate, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, device));
+ SLANG_CUDA_RETURN_ON_FAIL(cuDeviceGetAttribute(
+ &multiProcessorCount,
+ CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT,
+ device));
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuDeviceGetAttribute(&clockRate, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, device));
uint64_t compute_perf = uint64_t(multiProcessorCount) * smPerMultiproc * clockRate;
if (compute_perf > maxComputePerf)
@@ -143,7 +150,7 @@ SLANG_NO_THROW SlangResult SLANG_MCALL DeviceImpl::initialize(const Desc& desc)
desc.extendedDescs,
SLANG_PTX,
"sm_5_1",
- makeArray(slang::PreprocessorMacroDesc{ "__CUDA_COMPUTE__", "1" }).getView()));
+ makeArray(slang::PreprocessorMacroDesc{"__CUDA_COMPUTE__", "1"}).getView()));
SLANG_RETURN_ON_FAIL(RendererBase::initialize(desc));
@@ -174,12 +181,13 @@ SLANG_NO_THROW SlangResult SLANG_MCALL DeviceImpl::initialize(const Desc& desc)
SLANG_CUDA_RETURN_ON_FAIL(cuDeviceGet(&m_device, m_deviceIndex));
SLANG_CUDA_RETURN_WITH_REPORT_ON_FAIL(
- cuCtxCreate(&m_context->m_context, 0, m_device), reportType);
+ cuCtxCreate(&m_context->m_context, 0, m_device),
+ reportType);
{
// Not clear how to detect half support on CUDA. For now we'll assume we have it
m_features.add("half");
-
+
// CUDA has support for realtime clock
m_features.add("realtime-clock");
@@ -193,7 +201,7 @@ SLANG_NO_THROW SlangResult SLANG_MCALL DeviceImpl::initialize(const Desc& desc)
m_info.bindingStyle = BindingStyle::CUDA;
m_info.projectionStyle = ProjectionStyle::DirectX;
m_info.apiName = "CUDA";
- static const float kIdentity[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
+ static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
::memcpy(m_info.identityProjectionMatrix, kIdentity, sizeof(kIdentity));
char deviceName[256];
cuDeviceGetName(deviceName, sizeof(deviceName), m_device);
@@ -225,7 +233,8 @@ SLANG_NO_THROW SlangResult SLANG_MCALL DeviceImpl::initialize(const Desc& desc)
Math::Min(
getAttribute(CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT),
getAttribute(CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH)));
- limits.maxTextureDimensionCube = getAttribute(CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH);
+ limits.maxTextureDimensionCube =
+ getAttribute(CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH);
limits.maxTextureArrayLayers = Math::Min(
getAttribute(CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS),
getAttribute(CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS));
@@ -266,47 +275,31 @@ Result DeviceImpl::getCUDAFormat(Format format, CUarray_format* outFormat)
case Format::R32G32B32_FLOAT:
case Format::R32G32_FLOAT:
case Format::R32_FLOAT:
- case Format::D32_FLOAT:
- *outFormat = CU_AD_FORMAT_FLOAT;
- return SLANG_OK;
+ case Format::D32_FLOAT: *outFormat = CU_AD_FORMAT_FLOAT; return SLANG_OK;
case Format::R16G16B16A16_FLOAT:
case Format::R16G16_FLOAT:
- case Format::R16_FLOAT:
- *outFormat = CU_AD_FORMAT_HALF;
- return SLANG_OK;
+ case Format::R16_FLOAT: *outFormat = CU_AD_FORMAT_HALF; return SLANG_OK;
case Format::R32G32B32A32_UINT:
case Format::R32G32B32_UINT:
case Format::R32G32_UINT:
- case Format::R32_UINT:
- *outFormat = CU_AD_FORMAT_UNSIGNED_INT32;
- return SLANG_OK;
+ case Format::R32_UINT: *outFormat = CU_AD_FORMAT_UNSIGNED_INT32; return SLANG_OK;
case Format::R16G16B16A16_UINT:
case Format::R16G16_UINT:
- case Format::R16_UINT:
- *outFormat = CU_AD_FORMAT_UNSIGNED_INT16;
- return SLANG_OK;
+ case Format::R16_UINT: *outFormat = CU_AD_FORMAT_UNSIGNED_INT16; return SLANG_OK;
case Format::R8G8B8A8_UINT:
case Format::R8G8_UINT:
case Format::R8_UINT:
- case Format::R8G8B8A8_UNORM:
- *outFormat = CU_AD_FORMAT_UNSIGNED_INT8;
- return SLANG_OK;
+ case Format::R8G8B8A8_UNORM: *outFormat = CU_AD_FORMAT_UNSIGNED_INT8; return SLANG_OK;
case Format::R32G32B32A32_SINT:
case Format::R32G32B32_SINT:
case Format::R32G32_SINT:
- case Format::R32_SINT:
- *outFormat = CU_AD_FORMAT_SIGNED_INT32;
- return SLANG_OK;
+ case Format::R32_SINT: *outFormat = CU_AD_FORMAT_SIGNED_INT32; return SLANG_OK;
case Format::R16G16B16A16_SINT:
case Format::R16G16_SINT:
- case Format::R16_SINT:
- *outFormat = CU_AD_FORMAT_SIGNED_INT16;
- return SLANG_OK;
+ case Format::R16_SINT: *outFormat = CU_AD_FORMAT_SIGNED_INT16; return SLANG_OK;
case Format::R8G8B8A8_SINT:
case Format::R8G8_SINT:
- case Format::R8_SINT:
- *outFormat = CU_AD_FORMAT_SIGNED_INT8;
- return SLANG_OK;
+ case Format::R8_SINT: *outFormat = CU_AD_FORMAT_SIGNED_INT8; return SLANG_OK;
default:
SLANG_ASSERT(!"Only support R32_FLOAT/R8G8B8A8_UNORM formats for now");
return SLANG_FAIL;
@@ -348,16 +341,11 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureResource(
depth = 0;
break;
- case IResource::Type::Texture2D:
- depth = 0;
- break;
+ case IResource::Type::Texture2D: depth = 0; break;
- case IResource::Type::Texture3D:
- break;
+ case IResource::Type::Texture3D: break;
- case IResource::Type::TextureCube:
- depth = 1;
- break;
+ case IResource::Type::TextureCube: depth = 1; break;
}
{
@@ -372,25 +360,25 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureResource(
switch (format)
{
case CU_AD_FORMAT_FLOAT:
- {
- elementSize = sizeof(float) * numChannels;
- break;
- }
+ {
+ elementSize = sizeof(float) * numChannels;
+ break;
+ }
case CU_AD_FORMAT_HALF:
- {
- elementSize = sizeof(uint16_t) * numChannels;
- break;
- }
+ {
+ elementSize = sizeof(uint16_t) * numChannels;
+ break;
+ }
case CU_AD_FORMAT_UNSIGNED_INT8:
- {
- elementSize = sizeof(uint8_t) * numChannels;
- break;
- }
+ {
+ elementSize = sizeof(uint8_t) * numChannels;
+ break;
+ }
default:
- {
- SLANG_ASSERT(!"Only support R32_FLOAT/R8G8B8A8_UNORM formats for now");
- return SLANG_FAIL;
- }
+ {
+ SLANG_ASSERT(!"Only support R32_FLOAT/R8G8B8A8_UNORM formats for now");
+ return SLANG_FAIL;
+ }
}
if (desc.numMipLevels > 1)
@@ -468,7 +456,8 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureResource(
SLANG_CUDA_RETURN_ON_FAIL(cuArray3DCreate(&tex->m_cudaArray, &arrayDesc));
}
- else if (desc.type == IResource::Type::Texture3D ||
+ else if (
+ desc.type == IResource::Type::Texture3D ||
desc.type == IResource::Type::TextureCube)
{
CUDA_ARRAY3D_DESCRIPTOR arrayDesc;
@@ -574,8 +563,7 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureResource(
{
const auto srcData = initData[mipLevel + j * desc.numMipLevels].data;
// Copy over to the workspace to make contiguous
- ::memcpy(
- workspace.begin() + faceSizeInBytes * j, srcData, faceSizeInBytes);
+ ::memcpy(workspace.begin() + faceSizeInBytes * j, srcData, faceSizeInBytes);
}
srcDataPtr = workspace.getBuffer();
@@ -590,8 +578,7 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureResource(
// Copy the data over to make contiguous
for (Index j = 0; j < 6; j++)
{
- const auto srcData =
- initData[mipLevel + j * desc.numMipLevels].data;
+ const auto srcData = initData[mipLevel + j * desc.numMipLevels].data;
::memcpy(
workspace.getBuffer() + faceSizeInBytes * j,
srcData,
@@ -640,44 +627,44 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureResource(
{
case IResource::Type::Texture1D:
case IResource::Type::Texture2D:
- {
- CUDA_MEMCPY2D copyParam;
- memset(&copyParam, 0, sizeof(copyParam));
- copyParam.dstMemoryType = CU_MEMORYTYPE_ARRAY;
- copyParam.dstArray = dstArray;
- copyParam.srcMemoryType = CU_MEMORYTYPE_HOST;
- copyParam.srcHost = srcDataPtr;
- copyParam.srcPitch = mipWidth * elementSize;
- copyParam.WidthInBytes = copyParam.srcPitch;
- copyParam.Height = mipHeight;
- SLANG_CUDA_RETURN_ON_FAIL(cuMemcpy2D(&copyParam));
- break;
- }
+ {
+ CUDA_MEMCPY2D copyParam;
+ memset(&copyParam, 0, sizeof(copyParam));
+ copyParam.dstMemoryType = CU_MEMORYTYPE_ARRAY;
+ copyParam.dstArray = dstArray;
+ copyParam.srcMemoryType = CU_MEMORYTYPE_HOST;
+ copyParam.srcHost = srcDataPtr;
+ copyParam.srcPitch = mipWidth * elementSize;
+ copyParam.WidthInBytes = copyParam.srcPitch;
+ copyParam.Height = mipHeight;
+ SLANG_CUDA_RETURN_ON_FAIL(cuMemcpy2D(&copyParam));
+ break;
+ }
case IResource::Type::Texture3D:
case IResource::Type::TextureCube:
- {
- CUDA_MEMCPY3D copyParam;
- memset(&copyParam, 0, sizeof(copyParam));
+ {
+ CUDA_MEMCPY3D copyParam;
+ memset(&copyParam, 0, sizeof(copyParam));
- copyParam.dstMemoryType = CU_MEMORYTYPE_ARRAY;
- copyParam.dstArray = dstArray;
+ copyParam.dstMemoryType = CU_MEMORYTYPE_ARRAY;
+ copyParam.dstArray = dstArray;
- copyParam.srcMemoryType = CU_MEMORYTYPE_HOST;
- copyParam.srcHost = srcDataPtr;
- copyParam.srcPitch = mipWidth * elementSize;
- copyParam.WidthInBytes = copyParam.srcPitch;
- copyParam.Height = mipHeight;
- copyParam.Depth = mipDepth;
+ copyParam.srcMemoryType = CU_MEMORYTYPE_HOST;
+ copyParam.srcHost = srcDataPtr;
+ copyParam.srcPitch = mipWidth * elementSize;
+ copyParam.WidthInBytes = copyParam.srcPitch;
+ copyParam.Height = mipHeight;
+ copyParam.Depth = mipDepth;
- SLANG_CUDA_RETURN_ON_FAIL(cuMemcpy3D(&copyParam));
- break;
- }
+ SLANG_CUDA_RETURN_ON_FAIL(cuMemcpy3D(&copyParam));
+ break;
+ }
default:
- {
- SLANG_ASSERT(!"Not implemented");
- break;
- }
+ {
+ SLANG_ASSERT(!"Not implemented");
+ break;
+ }
}
}
}
@@ -749,10 +736,8 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createBufferResource(
CU_MEM_ATTACH_GLOBAL));
if (initData)
{
- SLANG_CUDA_RETURN_ON_FAIL(cuMemcpy(
- (CUdeviceptr)resource->m_cudaMemory,
- (CUdeviceptr)initData,
- desc.sizeInBytes));
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuMemcpy((CUdeviceptr)resource->m_cudaMemory, (CUdeviceptr)initData, desc.sizeInBytes));
}
returnComPtr(outResource, resource);
return SLANG_OK;
@@ -786,8 +771,7 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createBufferFromSharedHandle(
case InteropHandleAPI::Vulkan:
externalMemoryHandleDesc.type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32;
break;
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
}
externalMemoryHandleDesc.handle.win32.handle = (void*)handle.handleValue;
externalMemoryHandleDesc.size = desc.sizeInBytes;
@@ -813,7 +797,8 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createBufferFromSharedHandle(
// Finally, we can "map" the buffer to get a device address.
void* deviceAddress;
- SLANG_CUDA_RETURN_ON_FAIL(cuExternalMemoryGetMappedBuffer((CUdeviceptr*)&deviceAddress, externalMemory, &bufferDesc));
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuExternalMemoryGetMappedBuffer((CUdeviceptr*)&deviceAddress, externalMemory, &bufferDesc));
resource->m_cudaMemory = deviceAddress;
returnComPtr(outResource, resource);
@@ -849,8 +834,7 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureFromSharedHandle(
case InteropHandleAPI::Vulkan:
externalMemoryHandleDesc.type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32;
break;
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
}
externalMemoryHandleDesc.handle.win32.handle = (void*)handle.handleValue;
externalMemoryHandleDesc.size = size;
@@ -877,7 +861,8 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureFromSharedHandle(
externalMemoryMipDesc.numLevels = desc.numMipLevels;
CUmipmappedArray mipArray;
- SLANG_CUDA_RETURN_ON_FAIL(cuExternalMemoryGetMappedMipmappedArray(&mipArray, externalMemory, &externalMemoryMipDesc));
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuExternalMemoryGetMappedMipmappedArray(&mipArray, externalMemory, &externalMemoryMipDesc));
resource->m_cudaMipMappedArray = mipArray;
CUarray cuArray;
@@ -898,7 +883,9 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureFromSharedHandle(
}
SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTextureView(
- ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView)
+ ITextureResource* texture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView)
{
RefPtr<ResourceViewImpl> view = new ResourceViewImpl();
view->m_desc = desc;
@@ -920,9 +907,8 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createBufferView(
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createQueryPool(
- const IQueryPool::Desc& desc,
- IQueryPool** outPool)
+SLANG_NO_THROW Result SLANG_MCALL
+DeviceImpl::createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool)
{
RefPtr<QueryPoolImpl> pool = new QueryPoolImpl();
SLANG_RETURN_ON_FAIL(pool->init(desc));
@@ -941,9 +927,7 @@ Result DeviceImpl::createShaderObjectLayout(
return SLANG_OK;
}
-Result DeviceImpl::createShaderObject(
- ShaderObjectLayoutBase* layout,
- IShaderObject** outObject)
+Result DeviceImpl::createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
{
RefPtr<ShaderObjectImpl> result = new ShaderObjectImpl();
SLANG_RETURN_ON_FAIL(result->init(this, dynamic_cast<ShaderObjectLayoutImpl*>(layout)));
@@ -985,15 +969,20 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createProgram(
cudaProgram->cudaContext = m_context;
if (desc.slangGlobalScope->getSpecializationParamCount() != 0)
{
- cudaProgram->layout = new RootShaderObjectLayoutImpl(this, desc.slangGlobalScope->getLayout());
+ cudaProgram->layout =
+ new RootShaderObjectLayoutImpl(this, desc.slangGlobalScope->getLayout());
returnComPtr(outProgram, cudaProgram);
return SLANG_OK;
}
ComPtr<ISlangBlob> kernelCode;
ComPtr<ISlangBlob> diagnostics;
- auto compileResult = getEntryPointCodeFromShaderCache(desc.slangGlobalScope,
- (SlangInt)0, 0, kernelCode.writeRef(), diagnostics.writeRef());
+ auto compileResult = getEntryPointCodeFromShaderCache(
+ desc.slangGlobalScope,
+ (SlangInt)0,
+ 0,
+ kernelCode.writeRef(),
+ diagnostics.writeRef());
if (diagnostics)
{
getDebugCallback()->handleMessage(
@@ -1005,10 +994,14 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createProgram(
}
SLANG_RETURN_ON_FAIL(compileResult);
- SLANG_CUDA_RETURN_ON_FAIL(cuModuleLoadData(&cudaProgram->cudaModule, kernelCode->getBufferPointer()));
- cudaProgram->kernelName = desc.slangGlobalScope->getLayout()->getEntryPointByIndex(0)->getName();
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuModuleLoadData(&cudaProgram->cudaModule, kernelCode->getBufferPointer()));
+ cudaProgram->kernelName =
+ desc.slangGlobalScope->getLayout()->getEntryPointByIndex(0)->getName();
SLANG_CUDA_RETURN_ON_FAIL(cuModuleGetFunction(
- &cudaProgram->cudaKernel, cudaProgram->cudaModule, cudaProgram->kernelName.getBuffer()));
+ &cudaProgram->cudaKernel,
+ cudaProgram->cudaModule,
+ cudaProgram->kernelName.getBuffer()));
auto slangGlobalScope = desc.slangGlobalScope;
if (slangGlobalScope)
@@ -1030,7 +1023,8 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createProgram(
}
SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState)
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState)
{
RefPtr<ComputePipelineStateImpl> state = new ComputePipelineStateImpl();
state->shaderProgram = static_cast<ShaderProgramImpl*>(desc.program);
@@ -1065,7 +1059,7 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createTransientResourceHeap(
}
SLANG_NO_THROW Result SLANG_MCALL
- DeviceImpl::createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue)
+DeviceImpl::createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue)
{
RefPtr<CommandQueueImpl> queue = new CommandQueueImpl();
queue->init(this);
@@ -1074,7 +1068,9 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain)
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(window);
@@ -1083,7 +1079,8 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createSwapchain(
}
SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout)
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outLayout);
@@ -1091,7 +1088,7 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createFramebufferLayout(
}
SLANG_NO_THROW Result SLANG_MCALL
- DeviceImpl::createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer)
+DeviceImpl::createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outFramebuffer);
@@ -1108,16 +1105,15 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createRenderPassLayout(
}
SLANG_NO_THROW Result SLANG_MCALL
- DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler)
+DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler)
{
SLANG_UNUSED(desc);
*outSampler = nullptr;
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createInputLayout(
- IInputLayout::Desc const& desc,
- IInputLayout** outLayout)
+SLANG_NO_THROW Result SLANG_MCALL
+DeviceImpl::createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outLayout);
@@ -1125,7 +1121,8 @@ SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createInputLayout(
}
SLANG_NO_THROW Result SLANG_MCALL DeviceImpl::createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& desc, IPipelineState** outState)
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outState);
diff --git a/tools/gfx/cuda/cuda-device.h b/tools/gfx/cuda/cuda-device.h
index e711dc261..a21333ab6 100644
--- a/tools/gfx/cuda/cuda-device.h
+++ b/tools/gfx/cuda/cuda-device.h
@@ -1,7 +1,6 @@
// cuda-device.h
#pragma once
#include "cuda-base.h"
-
#include "cuda-command-buffer.h"
#include "cuda-context.h"
#include "cuda-helper-functions.h"
@@ -32,7 +31,8 @@ private:
String m_adapterName;
public:
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeDeviceHandles(InteropHandles* outHandles) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeDeviceHandles(InteropHandles* outHandles) override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL initialize(const Desc& desc) override;
@@ -60,7 +60,9 @@ public:
ITextureResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
- ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView) override;
+ ITextureResource* texture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createBufferView(
IBufferResource* buffer,
@@ -68,18 +70,16 @@ public:
IResourceView::Desc const& desc,
IResourceView** outView) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL createQueryPool(
- const IQueryPool::Desc& desc,
- IQueryPool** outPool) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool) override;
virtual Result createShaderObjectLayout(
slang::ISession* session,
slang::TypeLayoutReflection* typeLayout,
ShaderObjectLayoutBase** outLayout) override;
- virtual Result createShaderObject(
- ShaderObjectLayoutBase* layout,
- IShaderObject** outObject) override;
+ virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ override;
virtual Result createMutableShaderObject(
ShaderObjectLayoutBase* layout,
@@ -93,7 +93,8 @@ public:
ISlangBlob** outDiagnosticBlob) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState) override;
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState) override;
void* map(IBufferResource* buffer);
@@ -109,30 +110,33 @@ public:
ITransientResourceHeap** outHeap) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
+ createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain) override;
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout) override;
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
+ createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createRenderPassLayout(
const IRenderPassLayout::Desc& desc,
IRenderPassLayout** outRenderPassLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
-
- virtual SLANG_NO_THROW Result SLANG_MCALL createInputLayout(
- IInputLayout::Desc const& desc,
- IInputLayout** outLayout) override;
+ createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
+
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& desc, IPipelineState** outState) override;
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL readTextureResource(
ITextureResource* texture,
diff --git a/tools/gfx/cuda/cuda-helper-functions.cpp b/tools/gfx/cuda/cuda-helper-functions.cpp
index d478e8815..9fb69d620 100644
--- a/tools/gfx/cuda/cuda-helper-functions.cpp
+++ b/tools/gfx/cuda/cuda-helper-functions.cpp
@@ -24,7 +24,9 @@ SlangResult CUDAErrorInfo::handle() const
builder << m_errorString;
}
- getDebugCallback()->handleMessage(DebugMessageType::Error, DebugMessageSource::Driver,
+ getDebugCallback()->handleMessage(
+ DebugMessageType::Error,
+ DebugMessageSource::Driver,
builder.getUnownedSlice().begin());
// Slang::signalUnexpectedError(builder.getBuffer());
@@ -39,14 +41,14 @@ SlangResult _handleCUDAError(CUresult cuResult, const char* file, int line)
return info.handle();
}
-# ifdef RENDER_TEST_OPTIX
+#ifdef RENDER_TEST_OPTIX
static bool _isError(OptixResult result)
{
return result != OPTIX_SUCCESS;
}
-# if 1
+#if 1
static SlangResult _handleOptixError(OptixResult result, char const* file, int line)
{
fprintf(
@@ -63,8 +65,8 @@ void _optixLogCallback(unsigned int level, const char* tag, const char* message,
{
fprintf(stderr, "optix: %s (%s)\n", message, tag);
}
-# endif
-# endif
+#endif
+#endif
AdapterLUID getAdapterLUID(int deviceIndex)
{
diff --git a/tools/gfx/cuda/cuda-helper-functions.h b/tools/gfx/cuda/cuda-helper-functions.h
index 2217c727c..8474e830d 100644
--- a/tools/gfx/cuda/cuda-helper-functions.h
+++ b/tools/gfx/cuda/cuda-helper-functions.h
@@ -1,9 +1,9 @@
// cuda-helper-functions.h
#pragma once
-#include "slang-gfx.h"
-#include "cuda-base.h"
#include "../../../source/core/slang-list.h"
+#include "cuda-base.h"
+#include "slang-gfx.h"
namespace gfx
{
@@ -12,7 +12,10 @@ using namespace Slang;
#ifdef GFX_ENABLE_CUDA
namespace cuda
{
-SLANG_FORCE_INLINE bool _isError(CUresult result) { return result != 0; }
+SLANG_FORCE_INLINE bool _isError(CUresult result)
+{
+ return result != 0;
+}
// A enum used to control if errors are reported on failure of CUDA call.
enum class CUDAReportStyle
@@ -28,11 +31,9 @@ struct CUDAErrorInfo
int lineNo,
const char* errorName = nullptr,
const char* errorString = nullptr)
- : m_filePath(filePath)
- , m_lineNo(lineNo)
- , m_errorName(errorName)
- , m_errorString(errorString)
- {}
+ : m_filePath(filePath), m_lineNo(lineNo), m_errorName(errorName), m_errorString(errorString)
+ {
+ }
SlangResult handle() const;
const char* m_filePath;
@@ -45,57 +46,56 @@ struct CUDAErrorInfo
SlangResult _handleCUDAError(CUresult cuResult, const char* file, int line);
-# define SLANG_CUDA_HANDLE_ERROR(x) _handleCUDAError(x, __FILE__, __LINE__)
-
-# define SLANG_CUDA_RETURN_ON_FAIL(x) \
- { \
- auto _res = x; \
- if (_isError(_res)) \
- return SLANG_CUDA_HANDLE_ERROR(_res); \
- }
-
-# define SLANG_CUDA_RETURN_WITH_REPORT_ON_FAIL(x, r) \
- { \
- auto _res = x; \
- if (_isError(_res)) \
- { \
- return (r == CUDAReportStyle::Normal) ? SLANG_CUDA_HANDLE_ERROR(_res) \
- : SLANG_FAIL; \
- } \
- }
-
-# define SLANG_CUDA_ASSERT_ON_FAIL(x) \
- { \
- auto _res = x; \
- if (_isError(_res)) \
- { \
- SLANG_ASSERT(!"Failed CUDA call"); \
- }; \
- }
-
-# ifdef RENDER_TEST_OPTIX
+#define SLANG_CUDA_HANDLE_ERROR(x) _handleCUDAError(x, __FILE__, __LINE__)
+
+#define SLANG_CUDA_RETURN_ON_FAIL(x) \
+ { \
+ auto _res = x; \
+ if (_isError(_res)) \
+ return SLANG_CUDA_HANDLE_ERROR(_res); \
+ }
+
+#define SLANG_CUDA_RETURN_WITH_REPORT_ON_FAIL(x, r) \
+ { \
+ auto _res = x; \
+ if (_isError(_res)) \
+ { \
+ return (r == CUDAReportStyle::Normal) ? SLANG_CUDA_HANDLE_ERROR(_res) : SLANG_FAIL; \
+ } \
+ }
+
+#define SLANG_CUDA_ASSERT_ON_FAIL(x) \
+ { \
+ auto _res = x; \
+ if (_isError(_res)) \
+ { \
+ SLANG_ASSERT(!"Failed CUDA call"); \
+ }; \
+ }
+
+#ifdef RENDER_TEST_OPTIX
bool _isError(OptixResult result);
-# if 1
+#if 1
SlangResult _handleOptixError(OptixResult result, char const* file, int line);
-# define SLANG_OPTIX_HANDLE_ERROR(RESULT) _handleOptixError(RESULT, __FILE__, __LINE__)
-# else
-# define SLANG_OPTIX_HANDLE_ERROR(RESULT) SLANG_FAIL
-# endif
+#define SLANG_OPTIX_HANDLE_ERROR(RESULT) _handleOptixError(RESULT, __FILE__, __LINE__)
+#else
+#define SLANG_OPTIX_HANDLE_ERROR(RESULT) SLANG_FAIL
+#endif
-# define SLANG_OPTIX_RETURN_ON_FAIL(EXPR) \
- do \
- { \
- auto _res = EXPR; \
- if (_isError(_res)) \
- return SLANG_OPTIX_HANDLE_ERROR(_res); \
- } while (0)
+#define SLANG_OPTIX_RETURN_ON_FAIL(EXPR) \
+ do \
+ { \
+ auto _res = EXPR; \
+ if (_isError(_res)) \
+ return SLANG_OPTIX_HANDLE_ERROR(_res); \
+ } while (0)
void _optixLogCallback(unsigned int level, const char* tag, const char* message, void* userData);
-# endif
+#endif
AdapterLUID getAdapterLUID(int deviceIndex);
diff --git a/tools/gfx/cuda/cuda-query.cpp b/tools/gfx/cuda/cuda-query.cpp
index 7e97699f8..a671d43fb 100644
--- a/tools/gfx/cuda/cuda-query.cpp
+++ b/tools/gfx/cuda/cuda-query.cpp
@@ -30,8 +30,8 @@ QueryPoolImpl::~QueryPoolImpl()
cuEventDestroy(m_startEvent);
}
-SLANG_NO_THROW Result SLANG_MCALL QueryPoolImpl::getResult(
- GfxIndex queryIndex, GfxCount count, uint64_t* data)
+SLANG_NO_THROW Result SLANG_MCALL
+QueryPoolImpl::getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data)
{
for (GfxIndex i = 0; i < count; i++)
{
diff --git a/tools/gfx/cuda/cuda-query.h b/tools/gfx/cuda/cuda-query.h
index db29f488d..04d7edc43 100644
--- a/tools/gfx/cuda/cuda-query.h
+++ b/tools/gfx/cuda/cuda-query.h
@@ -23,8 +23,8 @@ public:
~QueryPoolImpl();
- virtual SLANG_NO_THROW Result SLANG_MCALL getResult(
- GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
};
} // namespace cuda
diff --git a/tools/gfx/cuda/cuda-resource-views.h b/tools/gfx/cuda/cuda-resource-views.h
index 33bf557d7..b2f0441fe 100644
--- a/tools/gfx/cuda/cuda-resource-views.h
+++ b/tools/gfx/cuda/cuda-resource-views.h
@@ -1,7 +1,6 @@
// cuda-resource-views.h
#pragma once
#include "cuda-base.h"
-
#include "cuda-buffer.h"
#include "cuda-texture.h"
diff --git a/tools/gfx/cuda/cuda-shader-object-layout.cpp b/tools/gfx/cuda/cuda-shader-object-layout.cpp
index f527d78de..d00855972 100644
--- a/tools/gfx/cuda/cuda-shader-object-layout.cpp
+++ b/tools/gfx/cuda/cuda-shader-object-layout.cpp
@@ -9,7 +9,10 @@ using namespace Slang;
namespace cuda
{
-ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(RendererBase* renderer, slang::ISession* session, slang::TypeLayoutReflection* layout)
+ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::TypeLayoutReflection* layout)
{
m_elementTypeLayout = _unwrapParameterGroups(layout, m_containerType);
@@ -41,7 +44,8 @@ ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(RendererBase* renderer, slang::IS
// linear search over the descriptor ranges for a specific binding range.
//
auto uniformOffset = m_elementTypeLayout->getDescriptorSetDescriptorRangeIndexOffset(
- descriptorSetIndex, rangeIndexInDescriptorSet);
+ descriptorSetIndex,
+ rangeIndexInDescriptorSet);
Index baseIndex = 0;
Index subObjectIndex = 0;
@@ -79,7 +83,7 @@ ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(RendererBase* renderer, slang::IS
bindingRangeInfo.uniformOffset = uniformOffset;
bindingRangeInfo.subObjectIndex = subObjectIndex;
bindingRangeInfo.isSpecializable = m_elementTypeLayout->isBindingRangeSpecializable(r);
- m_bindingRanges.add(bindingRangeInfo);
+ m_bindingRanges.add(bindingRangeInfo);
}
SlangInt subObjectRangeCount = m_elementTypeLayout->getSubObjectRangeCount();
@@ -100,8 +104,10 @@ ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(RendererBase* renderer, slang::IS
RefPtr<ShaderObjectLayoutImpl> subObjectLayout;
if (slangBindingType != slang::BindingType::ExistentialValue)
{
- subObjectLayout =
- new ShaderObjectLayoutImpl(renderer, session, slangLeafTypeLayout->getElementTypeLayout());
+ subObjectLayout = new ShaderObjectLayoutImpl(
+ renderer,
+ session,
+ slangLeafTypeLayout->getElementTypeLayout());
}
SubObjectRangeInfo subObjectRange;
@@ -111,14 +117,34 @@ ShaderObjectLayoutImpl::ShaderObjectLayoutImpl(RendererBase* renderer, slang::IS
}
}
-Index ShaderObjectLayoutImpl::getResourceCount() const { return m_resourceCount; }
-Index ShaderObjectLayoutImpl::getSubObjectCount() const { return m_subObjectCount; }
-List<SubObjectRangeInfo>& ShaderObjectLayoutImpl::getSubObjectRanges() { return subObjectRanges; }
-BindingRangeInfo ShaderObjectLayoutImpl::getBindingRange(Index index) { return m_bindingRanges[index]; }
-Index ShaderObjectLayoutImpl::getBindingRangeCount() const { return m_bindingRanges.getCount(); }
+Index ShaderObjectLayoutImpl::getResourceCount() const
+{
+ return m_resourceCount;
+}
+Index ShaderObjectLayoutImpl::getSubObjectCount() const
+{
+ return m_subObjectCount;
+}
+List<SubObjectRangeInfo>& ShaderObjectLayoutImpl::getSubObjectRanges()
+{
+ return subObjectRanges;
+}
+BindingRangeInfo ShaderObjectLayoutImpl::getBindingRange(Index index)
+{
+ return m_bindingRanges[index];
+}
+Index ShaderObjectLayoutImpl::getBindingRangeCount() const
+{
+ return m_bindingRanges.getCount();
+}
-RootShaderObjectLayoutImpl::RootShaderObjectLayoutImpl(RendererBase* renderer, slang::ProgramLayout* inProgramLayout)
- : ShaderObjectLayoutImpl(renderer, inProgramLayout->getSession(), inProgramLayout->getGlobalParamsTypeLayout())
+RootShaderObjectLayoutImpl::RootShaderObjectLayoutImpl(
+ RendererBase* renderer,
+ slang::ProgramLayout* inProgramLayout)
+ : ShaderObjectLayoutImpl(
+ renderer,
+ inProgramLayout->getSession(),
+ inProgramLayout->getGlobalParamsTypeLayout())
, programLayout(inProgramLayout)
{
for (UInt i = 0; i < programLayout->getEntryPointCount(); i++)
@@ -128,7 +154,6 @@ RootShaderObjectLayoutImpl::RootShaderObjectLayoutImpl(RendererBase* renderer, s
programLayout->getSession(),
programLayout->getEntryPointByIndex(i)->getTypeLayout()));
}
-
}
int RootShaderObjectLayoutImpl::getKernelIndex(UnownedStringSlice kernelName)
diff --git a/tools/gfx/cuda/cuda-shader-object-layout.h b/tools/gfx/cuda/cuda-shader-object-layout.h
index edec0c352..4830fe975 100644
--- a/tools/gfx/cuda/cuda-shader-object-layout.h
+++ b/tools/gfx/cuda/cuda-shader-object-layout.h
@@ -50,7 +50,10 @@ public:
Index m_subObjectCount = 0;
Index m_resourceCount = 0;
- ShaderObjectLayoutImpl(RendererBase* renderer, slang::ISession* session, slang::TypeLayoutReflection* layout);
+ ShaderObjectLayoutImpl(
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::TypeLayoutReflection* layout);
Index getResourceCount() const;
Index getSubObjectCount() const;
diff --git a/tools/gfx/cuda/cuda-shader-object.cpp b/tools/gfx/cuda/cuda-shader-object.cpp
index 02b4cf695..e7033e403 100644
--- a/tools/gfx/cuda/cuda-shader-object.cpp
+++ b/tools/gfx/cuda/cuda-shader-object.cpp
@@ -1,10 +1,9 @@
// cuda-shader-object.cpp
#include "cuda-shader-object.h"
-#include "cuda-shader-object-layout.h"
-#include "cuda-resource-views.h"
-
#include "cuda-helper-functions.h"
+#include "cuda-resource-views.h"
+#include "cuda-shader-object-layout.h"
namespace gfx
{
@@ -37,7 +36,8 @@ Result ShaderObjectData::setCount(Index count)
m_bufferResource = new BufferResourceImpl(desc);
if (count)
{
- SLANG_CUDA_RETURN_ON_FAIL(cuMemAlloc((CUdeviceptr*)&m_bufferResource->m_cudaMemory, (size_t)count));
+ SLANG_CUDA_RETURN_ON_FAIL(
+ cuMemAlloc((CUdeviceptr*)&m_bufferResource->m_cudaMemory, (size_t)count));
}
IResourceView::Desc viewDesc = {};
viewDesc.type = IResourceView::Type::UnorderedAccess;
@@ -167,7 +167,7 @@ SLANG_NO_THROW GfxCount SLANG_MCALL ShaderObjectImpl::getEntryPointCount()
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
+ShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
{
*outEntryPoint = nullptr;
return SLANG_OK;
@@ -184,7 +184,7 @@ SLANG_NO_THROW Size SLANG_MCALL ShaderObjectImpl::getSize()
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setData(ShaderOffset const& offset, void const* data, Size size)
+ShaderObjectImpl::setData(ShaderOffset const& offset, void const* data, Size size)
{
Size temp = m_data.getCount() - (Size)offset.uniformOffset;
size = Math::Min(size, temp);
@@ -196,7 +196,7 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView* resourceView)
+ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView* resourceView)
{
if (!resourceView)
return SLANG_OK;
@@ -255,7 +255,7 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setObject(ShaderOffset const& offset, IShaderObject* object)
+ShaderObjectImpl::setObject(ShaderOffset const& offset, IShaderObject* object)
{
SLANG_RETURN_ON_FAIL(Super::setObject(offset, object));
@@ -266,21 +266,20 @@ SLANG_NO_THROW Result SLANG_MCALL
switch (bindingRange.bindingType)
{
default:
- {
- void* subObjectDataBuffer = subObject->getBuffer();
- SLANG_RETURN_ON_FAIL(setData(offset, &subObjectDataBuffer, sizeof(void*)));
- }
- break;
+ {
+ void* subObjectDataBuffer = subObject->getBuffer();
+ SLANG_RETURN_ON_FAIL(setData(offset, &subObjectDataBuffer, sizeof(void*)));
+ }
+ break;
case slang::BindingType::ExistentialValue:
case slang::BindingType::RawBuffer:
- case slang::BindingType::MutableRawBuffer:
- break;
+ case slang::BindingType::MutableRawBuffer: break;
}
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* sampler)
+ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* sampler)
{
SLANG_UNUSED(sampler);
SLANG_UNUSED(offset);
@@ -288,7 +287,9 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL ShaderObjectImpl::setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler)
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler)
{
SLANG_UNUSED(sampler);
setResource(offset, textureView);
@@ -329,7 +330,7 @@ SLANG_NO_THROW GfxCount SLANG_MCALL RootShaderObjectImpl::getEntryPointCount()
}
SLANG_NO_THROW Result SLANG_MCALL
- RootShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
+RootShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
{
returnComPtr(outEntryPoint, entryPointObjects[index]);
return SLANG_OK;
diff --git a/tools/gfx/cuda/cuda-shader-object.h b/tools/gfx/cuda/cuda-shader-object.h
index f564f5eb5..c1c00a821 100644
--- a/tools/gfx/cuda/cuda-shader-object.h
+++ b/tools/gfx/cuda/cuda-shader-object.h
@@ -1,7 +1,6 @@
// cuda-shader-object.h
#pragma once
#include "cuda-base.h"
-
#include "cuda-buffer.h"
#include "cuda-resource-views.h"
@@ -35,37 +34,40 @@ public:
class ShaderObjectImpl
: public ShaderObjectBaseImpl<ShaderObjectImpl, ShaderObjectLayoutImpl, ShaderObjectData>
{
- typedef ShaderObjectBaseImpl<ShaderObjectImpl, ShaderObjectLayoutImpl, ShaderObjectData>
- Super;
+ typedef ShaderObjectBaseImpl<ShaderObjectImpl, ShaderObjectLayoutImpl, ShaderObjectData> Super;
public:
List<RefPtr<ResourceViewImpl>> resources;
virtual SLANG_NO_THROW Result SLANG_MCALL
- init(IDevice* device, ShaderObjectLayoutImpl* typeLayout);
+ init(IDevice* device, ShaderObjectLayoutImpl* typeLayout);
virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override;
virtual SLANG_NO_THROW Size SLANG_MCALL getSize() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& offset, void const* data, Size size) override;
+ setData(ShaderOffset const& offset, void const* data, Size size) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* resourceView) override;
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setObject(ShaderOffset const& offset, IShaderObject* object) override;
+ setObject(ShaderOffset const& offset, IShaderObject* object) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
+ setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) override;
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) override;
};
-class MutableShaderObjectImpl : public MutableShaderObject< MutableShaderObjectImpl, ShaderObjectLayoutImpl>
-{};
+class MutableShaderObjectImpl
+ : public MutableShaderObject<MutableShaderObjectImpl, ShaderObjectLayoutImpl>
+{
+};
class EntryPointShaderObjectImpl : public ShaderObjectImpl
{
@@ -78,13 +80,14 @@ class RootShaderObjectImpl : public ShaderObjectImpl
public:
virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() override;
virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() override;
+
public:
List<RefPtr<EntryPointShaderObjectImpl>> entryPointObjects;
virtual SLANG_NO_THROW Result SLANG_MCALL
- init(IDevice* device, ShaderObjectLayoutImpl* typeLayout) override;
+ init(IDevice* device, ShaderObjectLayoutImpl* typeLayout) override;
virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override;
};
diff --git a/tools/gfx/cuda/cuda-shader-program.h b/tools/gfx/cuda/cuda-shader-program.h
index b0961bfc3..3f6117254 100644
--- a/tools/gfx/cuda/cuda-shader-program.h
+++ b/tools/gfx/cuda/cuda-shader-program.h
@@ -1,7 +1,6 @@
// cuda-shader-program.h
#pragma once
#include "cuda-base.h"
-
#include "cuda-context.h"
#include "cuda-shader-object-layout.h"
diff --git a/tools/gfx/cuda/cuda-texture.h b/tools/gfx/cuda/cuda-texture.h
index c9cc8569a..4af2b323b 100644
--- a/tools/gfx/cuda/cuda-texture.h
+++ b/tools/gfx/cuda/cuda-texture.h
@@ -1,7 +1,6 @@
// cuda-texture.h
#pragma once
#include "cuda-base.h"
-
#include "cuda-context.h"
namespace gfx
@@ -17,7 +16,8 @@ class TextureResourceImpl : public TextureResource
public:
TextureResourceImpl(const TextureResource::Desc& desc)
: TextureResource(desc)
- {}
+ {
+ }
~TextureResourceImpl();
uint64_t getBindlessHandle();
@@ -36,7 +36,8 @@ public:
RefPtr<CUDAContext> m_cudaContext;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeResourceHandle(InteropHandle* outHandle) override;
};
} // namespace cuda
diff --git a/tools/gfx/d3d/d3d-swapchain.h b/tools/gfx/d3d/d3d-swapchain.h
index c9e0de82a..49a4f1c99 100644
--- a/tools/gfx/d3d/d3d-swapchain.h
+++ b/tools/gfx/d3d/d3d-swapchain.h
@@ -1,16 +1,15 @@
#pragma once
-#include "slang-gfx.h"
-#include "core/slang-basic.h"
-#include <dxgi1_4.h>
#include "../renderer-shared.h"
+#include "core/slang-basic.h"
#include "d3d-util.h"
+#include "slang-gfx.h"
+
+#include <dxgi1_4.h>
namespace gfx
{
-class D3DSwapchainBase
- : public ISwapchain
- , public Slang::ComObject
+class D3DSwapchainBase : public ISwapchain, public Slang::ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -27,10 +26,8 @@ public:
// Return fail on non-supported platforms.
switch (window.type)
{
- case WindowHandle::Type::Win32Handle:
- break;
- default:
- return SLANG_FAIL;
+ case WindowHandle::Type::Win32Handle: break;
+ default: return SLANG_FAIL;
}
m_desc = desc;
@@ -60,9 +57,12 @@ public:
{
ComPtr<IDXGISwapChain> swapChain;
SLANG_RETURN_ON_FAIL(getDXGIFactory()->CreateSwapChain(
- getOwningDevice(), &swapChainDesc, swapChain.writeRef()));
+ getOwningDevice(),
+ &swapChainDesc,
+ swapChain.writeRef()));
SLANG_RETURN_ON_FAIL(getDXGIFactory()->MakeWindowAssociation(
- (HWND)window.handleValues[0], DXGI_MWA_NO_ALT_ENTER));
+ (HWND)window.handleValues[0],
+ DXGI_MWA_NO_ALT_ENTER));
SLANG_RETURN_ON_FAIL(swapChain->QueryInterface(m_swapChain.writeRef()));
}
else
@@ -92,7 +92,7 @@ public:
}
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override { return m_desc; }
virtual SLANG_NO_THROW Result SLANG_MCALL
- getImage(GfxIndex index, ITextureResource** outResource) override
+ getImage(GfxIndex index, ITextureResource** outResource) override
{
returnComPtr(outResource, m_images[index]);
return SLANG_OK;
@@ -126,17 +126,17 @@ public:
{
if (width == m_desc.width && height == m_desc.height)
return SLANG_OK;
-
+
m_desc.width = width;
m_desc.height = height;
for (auto& image : m_images)
image = nullptr;
m_images.clear();
auto result = m_swapChain->ResizeBuffers(
- m_desc.imageCount,
- width,
- height,
- D3DUtil::getMapFormat(m_desc.format),
+ m_desc.imageCount,
+ width,
+ height,
+ D3DUtil::getMapFormat(m_desc.format),
m_desc.enableVSync ? 0 : DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT);
if (result != 0)
return SLANG_FAIL;
@@ -153,4 +153,4 @@ public:
Slang::ShortList<Slang::RefPtr<TextureResource>> m_images;
};
-}
+} // namespace gfx
diff --git a/tools/gfx/d3d/d3d-util.cpp b/tools/gfx/d3d/d3d-util.cpp
index 8d76c74b3..9d32f8532 100644
--- a/tools/gfx/d3d/d3d-util.cpp
+++ b/tools/gfx/d3d/d3d-util.cpp
@@ -9,37 +9,32 @@
#endif
// We will use the C standard library just for printing error messages.
-#include <stdio.h>
-
#include "core/slang-basic.h"
#include "core/slang-platform.h"
-#ifdef GFX_NV_AFTERMATH
-# include "GFSDK_Aftermath.h"
-# include "GFSDK_Aftermath_Defines.h"
-# include "GFSDK_Aftermath_GpuCrashDump.h"
+#include <stdio.h>
-# include "core/slang-process.h"
+#ifdef GFX_NV_AFTERMATH
+#include "GFSDK_Aftermath.h"
+#include "GFSDK_Aftermath_Defines.h"
+#include "GFSDK_Aftermath_GpuCrashDump.h"
+#include "core/slang-process.h"
#endif
-namespace gfx {
+namespace gfx
+{
using namespace Slang;
-/* static */D3D_PRIMITIVE_TOPOLOGY D3DUtil::getPrimitiveTopology(PrimitiveTopology topology)
+/* static */ D3D_PRIMITIVE_TOPOLOGY D3DUtil::getPrimitiveTopology(PrimitiveTopology topology)
{
switch (topology)
{
- case PrimitiveTopology::TriangleList:
- return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
- case PrimitiveTopology::TriangleStrip:
- return D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
- case PrimitiveTopology::LineList:
- return D3D_PRIMITIVE_TOPOLOGY_LINELIST;
- case PrimitiveTopology::LineStrip:
- return D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
- case PrimitiveTopology::PointList:
- return D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
- default: break;
+ case PrimitiveTopology::TriangleList: return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
+ case PrimitiveTopology::TriangleStrip: return D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
+ case PrimitiveTopology::LineList: return D3D_PRIMITIVE_TOPOLOGY_LINELIST;
+ case PrimitiveTopology::LineStrip: return D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
+ case PrimitiveTopology::PointList: return D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
+ default: break;
}
return D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
}
@@ -49,15 +44,11 @@ D3D12_PRIMITIVE_TOPOLOGY_TYPE D3DUtil::getPrimitiveType(PrimitiveTopology topolo
switch (topology)
{
case PrimitiveTopology::TriangleList:
- case PrimitiveTopology::TriangleStrip:
- return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ case PrimitiveTopology::TriangleStrip: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
case PrimitiveTopology::LineList:
- case PrimitiveTopology::LineStrip:
- return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
- case PrimitiveTopology::PointList:
- return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
- default:
- break;
+ case PrimitiveTopology::LineStrip: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
+ case PrimitiveTopology::PointList: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
+ default: break;
}
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED;
}
@@ -66,16 +57,11 @@ D3D12_PRIMITIVE_TOPOLOGY_TYPE D3DUtil::getPrimitiveType(PrimitiveType type)
{
switch (type)
{
- case PrimitiveType::Point:
- return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
- case PrimitiveType::Line:
- return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
- case PrimitiveType::Triangle:
- return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
- case PrimitiveType::Patch:
- return D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH;
- default:
- break;
+ case PrimitiveType::Point: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
+ case PrimitiveType::Line: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
+ case PrimitiveType::Triangle: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ case PrimitiveType::Patch: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH;
+ default: break;
}
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED;
}
@@ -84,24 +70,15 @@ D3D12_COMPARISON_FUNC D3DUtil::getComparisonFunc(ComparisonFunc func)
{
switch (func)
{
- case gfx::ComparisonFunc::Never:
- return D3D12_COMPARISON_FUNC_NEVER;
- case gfx::ComparisonFunc::Less:
- return D3D12_COMPARISON_FUNC_LESS;
- case gfx::ComparisonFunc::Equal:
- return D3D12_COMPARISON_FUNC_EQUAL;
- case gfx::ComparisonFunc::LessEqual:
- return D3D12_COMPARISON_FUNC_LESS_EQUAL;
- case gfx::ComparisonFunc::Greater:
- return D3D12_COMPARISON_FUNC_GREATER;
- case gfx::ComparisonFunc::NotEqual:
- return D3D12_COMPARISON_FUNC_NOT_EQUAL;
- case gfx::ComparisonFunc::GreaterEqual:
- return D3D12_COMPARISON_FUNC_GREATER_EQUAL;
- case gfx::ComparisonFunc::Always:
- return D3D12_COMPARISON_FUNC_ALWAYS;
- default:
- return D3D12_COMPARISON_FUNC_NEVER;
+ case gfx::ComparisonFunc::Never: return D3D12_COMPARISON_FUNC_NEVER;
+ case gfx::ComparisonFunc::Less: return D3D12_COMPARISON_FUNC_LESS;
+ case gfx::ComparisonFunc::Equal: return D3D12_COMPARISON_FUNC_EQUAL;
+ case gfx::ComparisonFunc::LessEqual: return D3D12_COMPARISON_FUNC_LESS_EQUAL;
+ case gfx::ComparisonFunc::Greater: return D3D12_COMPARISON_FUNC_GREATER;
+ case gfx::ComparisonFunc::NotEqual: return D3D12_COMPARISON_FUNC_NOT_EQUAL;
+ case gfx::ComparisonFunc::GreaterEqual: return D3D12_COMPARISON_FUNC_GREATER_EQUAL;
+ case gfx::ComparisonFunc::Always: return D3D12_COMPARISON_FUNC_ALWAYS;
+ default: return D3D12_COMPARISON_FUNC_NEVER;
}
}
@@ -109,24 +86,15 @@ static D3D12_STENCIL_OP translateStencilOp(StencilOp op)
{
switch (op)
{
- case gfx::StencilOp::Keep:
- return D3D12_STENCIL_OP_KEEP;
- case gfx::StencilOp::Zero:
- return D3D12_STENCIL_OP_ZERO;
- case gfx::StencilOp::Replace:
- return D3D12_STENCIL_OP_REPLACE;
- case gfx::StencilOp::IncrementSaturate:
- return D3D12_STENCIL_OP_INCR_SAT;
- case gfx::StencilOp::DecrementSaturate:
- return D3D12_STENCIL_OP_DECR_SAT;
- case gfx::StencilOp::Invert:
- return D3D12_STENCIL_OP_INVERT;
- case gfx::StencilOp::IncrementWrap:
- return D3D12_STENCIL_OP_INCR;
- case gfx::StencilOp::DecrementWrap:
- return D3D12_STENCIL_OP_DECR;
- default:
- return D3D12_STENCIL_OP_KEEP;
+ case gfx::StencilOp::Keep: return D3D12_STENCIL_OP_KEEP;
+ case gfx::StencilOp::Zero: return D3D12_STENCIL_OP_ZERO;
+ case gfx::StencilOp::Replace: return D3D12_STENCIL_OP_REPLACE;
+ case gfx::StencilOp::IncrementSaturate: return D3D12_STENCIL_OP_INCR_SAT;
+ case gfx::StencilOp::DecrementSaturate: return D3D12_STENCIL_OP_DECR_SAT;
+ case gfx::StencilOp::Invert: return D3D12_STENCIL_OP_INVERT;
+ case gfx::StencilOp::IncrementWrap: return D3D12_STENCIL_OP_INCR;
+ case gfx::StencilOp::DecrementWrap: return D3D12_STENCIL_OP_DECR;
+ default: return D3D12_STENCIL_OP_KEEP;
}
}
@@ -140,188 +108,189 @@ D3D12_DEPTH_STENCILOP_DESC D3DUtil::translateStencilOpDesc(DepthStencilOpDesc de
return rs;
}
-/* static */DXGI_FORMAT D3DUtil::getMapFormat(Format format)
+/* static */ DXGI_FORMAT D3DUtil::getMapFormat(Format format)
{
switch (format)
{
- case Format::R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_TYPELESS;
- case Format::R32G32B32_TYPELESS: return DXGI_FORMAT_R32G32B32_TYPELESS;
- case Format::R32G32_TYPELESS: return DXGI_FORMAT_R32G32_TYPELESS;
- case Format::R32_TYPELESS: return DXGI_FORMAT_R32_TYPELESS;
-
- case Format::R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_TYPELESS;
- case Format::R16G16_TYPELESS: return DXGI_FORMAT_R16G16_TYPELESS;
- case Format::R16_TYPELESS: return DXGI_FORMAT_R16_TYPELESS;
-
- case Format::R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_TYPELESS;
- case Format::R8G8_TYPELESS: return DXGI_FORMAT_R8G8_TYPELESS;
- case Format::R8_TYPELESS: return DXGI_FORMAT_R8_TYPELESS;
- case Format::B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_TYPELESS;
-
- case Format::R32G32B32A32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
- case Format::R32G32B32_FLOAT: return DXGI_FORMAT_R32G32B32_FLOAT;
- case Format::R32G32_FLOAT: return DXGI_FORMAT_R32G32_FLOAT;
- case Format::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
-
- case Format::R16G16B16A16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
- case Format::R16G16_FLOAT: return DXGI_FORMAT_R16G16_FLOAT;
- case Format::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
-
- case Format::R64_UINT: return DXGI_FORMAT_R32G32_UINT;
-
- case Format::R32G32B32A32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
- case Format::R32G32B32_UINT: return DXGI_FORMAT_R32G32B32_UINT;
- case Format::R32G32_UINT: return DXGI_FORMAT_R32G32_UINT;
- case Format::R32_UINT: return DXGI_FORMAT_R32_UINT;
-
- case Format::R16G16B16A16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
- case Format::R16G16_UINT: return DXGI_FORMAT_R16G16_UINT;
- case Format::R16_UINT: return DXGI_FORMAT_R16_UINT;
-
- case Format::R8G8B8A8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
- case Format::R8G8_UINT: return DXGI_FORMAT_R8G8_UINT;
- case Format::R8_UINT: return DXGI_FORMAT_R8_UINT;
-
- case Format::R64_SINT: return DXGI_FORMAT_R32G32_SINT;
-
- case Format::R32G32B32A32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
- case Format::R32G32B32_SINT: return DXGI_FORMAT_R32G32B32_SINT;
- case Format::R32G32_SINT: return DXGI_FORMAT_R32G32_SINT;
- case Format::R32_SINT: return DXGI_FORMAT_R32_SINT;
-
- case Format::R16G16B16A16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
- case Format::R16G16_SINT: return DXGI_FORMAT_R16G16_SINT;
- case Format::R16_SINT: return DXGI_FORMAT_R16_SINT;
-
- case Format::R8G8B8A8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
- case Format::R8G8_SINT: return DXGI_FORMAT_R8G8_SINT;
- case Format::R8_SINT: return DXGI_FORMAT_R8_SINT;
-
- case Format::R16G16B16A16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
- case Format::R16G16_UNORM: return DXGI_FORMAT_R16G16_UNORM;
- case Format::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
-
- case Format::R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
- case Format::R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
- case Format::R8G8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
- case Format::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
- case Format::B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM;
- case Format::B8G8R8X8_UNORM: return DXGI_FORMAT_B8G8R8X8_UNORM;
- case Format::B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
- case Format::B8G8R8X8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
-
- case Format::R16G16B16A16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
- case Format::R16G16_SNORM: return DXGI_FORMAT_R16G16_SNORM;
- case Format::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
-
- case Format::R8G8B8A8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
- case Format::R8G8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
- case Format::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
-
- case Format::D32_FLOAT: return DXGI_FORMAT_D32_FLOAT;
- case Format::D16_UNORM: return DXGI_FORMAT_D16_UNORM;
- case Format::D32_FLOAT_S8_UINT: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
- case Format::R32_FLOAT_X32_TYPELESS: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
-
- case Format::B4G4R4A4_UNORM: return DXGI_FORMAT_B4G4R4A4_UNORM;
- case Format::B5G6R5_UNORM: return DXGI_FORMAT_B5G6R5_UNORM;
- case Format::B5G5R5A1_UNORM: return DXGI_FORMAT_B5G5R5A1_UNORM;
-
- case Format::R9G9B9E5_SHAREDEXP: return DXGI_FORMAT_R9G9B9E5_SHAREDEXP;
- case Format::R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_TYPELESS;
- case Format::R10G10B10A2_UINT: return DXGI_FORMAT_R10G10B10A2_UINT;
- case Format::R10G10B10A2_UNORM: return DXGI_FORMAT_R10G10B10A2_UNORM;
- case Format::R11G11B10_FLOAT: return DXGI_FORMAT_R11G11B10_FLOAT;
-
- case Format::BC1_UNORM: return DXGI_FORMAT_BC1_UNORM;
- case Format::BC1_UNORM_SRGB: return DXGI_FORMAT_BC1_UNORM_SRGB;
- case Format::BC2_UNORM: return DXGI_FORMAT_BC2_UNORM;
- case Format::BC2_UNORM_SRGB: return DXGI_FORMAT_BC2_UNORM_SRGB;
- case Format::BC3_UNORM: return DXGI_FORMAT_BC3_UNORM;
- case Format::BC3_UNORM_SRGB: return DXGI_FORMAT_BC3_UNORM_SRGB;
- case Format::BC4_UNORM: return DXGI_FORMAT_BC4_UNORM;
- case Format::BC4_SNORM: return DXGI_FORMAT_BC4_SNORM;
- case Format::BC5_UNORM: return DXGI_FORMAT_BC5_UNORM;
- case Format::BC5_SNORM: return DXGI_FORMAT_BC5_SNORM;
- case Format::BC6H_UF16: return DXGI_FORMAT_BC6H_UF16;
- case Format::BC6H_SF16: return DXGI_FORMAT_BC6H_SF16;
- case Format::BC7_UNORM: return DXGI_FORMAT_BC7_UNORM;
- case Format::BC7_UNORM_SRGB: return DXGI_FORMAT_BC7_UNORM_SRGB;
-
- default: return DXGI_FORMAT_UNKNOWN;
- }
-}
-
-/* static */DXGI_FORMAT D3DUtil::calcResourceFormat(UsageType usage, Int usageFlags, DXGI_FORMAT format)
+ case Format::R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_TYPELESS;
+ case Format::R32G32B32_TYPELESS: return DXGI_FORMAT_R32G32B32_TYPELESS;
+ case Format::R32G32_TYPELESS: return DXGI_FORMAT_R32G32_TYPELESS;
+ case Format::R32_TYPELESS: return DXGI_FORMAT_R32_TYPELESS;
+
+ case Format::R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_TYPELESS;
+ case Format::R16G16_TYPELESS: return DXGI_FORMAT_R16G16_TYPELESS;
+ case Format::R16_TYPELESS: return DXGI_FORMAT_R16_TYPELESS;
+
+ case Format::R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_TYPELESS;
+ case Format::R8G8_TYPELESS: return DXGI_FORMAT_R8G8_TYPELESS;
+ case Format::R8_TYPELESS: return DXGI_FORMAT_R8_TYPELESS;
+ case Format::B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_TYPELESS;
+
+ case Format::R32G32B32A32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
+ case Format::R32G32B32_FLOAT: return DXGI_FORMAT_R32G32B32_FLOAT;
+ case Format::R32G32_FLOAT: return DXGI_FORMAT_R32G32_FLOAT;
+ case Format::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
+
+ case Format::R16G16B16A16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
+ case Format::R16G16_FLOAT: return DXGI_FORMAT_R16G16_FLOAT;
+ case Format::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
+
+ case Format::R64_UINT: return DXGI_FORMAT_R32G32_UINT;
+
+ case Format::R32G32B32A32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
+ case Format::R32G32B32_UINT: return DXGI_FORMAT_R32G32B32_UINT;
+ case Format::R32G32_UINT: return DXGI_FORMAT_R32G32_UINT;
+ case Format::R32_UINT: return DXGI_FORMAT_R32_UINT;
+
+ case Format::R16G16B16A16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
+ case Format::R16G16_UINT: return DXGI_FORMAT_R16G16_UINT;
+ case Format::R16_UINT: return DXGI_FORMAT_R16_UINT;
+
+ case Format::R8G8B8A8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
+ case Format::R8G8_UINT: return DXGI_FORMAT_R8G8_UINT;
+ case Format::R8_UINT: return DXGI_FORMAT_R8_UINT;
+
+ case Format::R64_SINT: return DXGI_FORMAT_R32G32_SINT;
+
+ case Format::R32G32B32A32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
+ case Format::R32G32B32_SINT: return DXGI_FORMAT_R32G32B32_SINT;
+ case Format::R32G32_SINT: return DXGI_FORMAT_R32G32_SINT;
+ case Format::R32_SINT: return DXGI_FORMAT_R32_SINT;
+
+ case Format::R16G16B16A16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
+ case Format::R16G16_SINT: return DXGI_FORMAT_R16G16_SINT;
+ case Format::R16_SINT: return DXGI_FORMAT_R16_SINT;
+
+ case Format::R8G8B8A8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
+ case Format::R8G8_SINT: return DXGI_FORMAT_R8G8_SINT;
+ case Format::R8_SINT: return DXGI_FORMAT_R8_SINT;
+
+ case Format::R16G16B16A16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
+ case Format::R16G16_UNORM: return DXGI_FORMAT_R16G16_UNORM;
+ case Format::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
+
+ case Format::R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
+ case Format::R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
+ case Format::R8G8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
+ case Format::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
+ case Format::B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM;
+ case Format::B8G8R8X8_UNORM: return DXGI_FORMAT_B8G8R8X8_UNORM;
+ case Format::B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
+ case Format::B8G8R8X8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
+
+ case Format::R16G16B16A16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
+ case Format::R16G16_SNORM: return DXGI_FORMAT_R16G16_SNORM;
+ case Format::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
+
+ case Format::R8G8B8A8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
+ case Format::R8G8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
+ case Format::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
+
+ case Format::D32_FLOAT: return DXGI_FORMAT_D32_FLOAT;
+ case Format::D16_UNORM: return DXGI_FORMAT_D16_UNORM;
+ case Format::D32_FLOAT_S8_UINT: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
+ case Format::R32_FLOAT_X32_TYPELESS: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
+
+ case Format::B4G4R4A4_UNORM: return DXGI_FORMAT_B4G4R4A4_UNORM;
+ case Format::B5G6R5_UNORM: return DXGI_FORMAT_B5G6R5_UNORM;
+ case Format::B5G5R5A1_UNORM: return DXGI_FORMAT_B5G5R5A1_UNORM;
+
+ case Format::R9G9B9E5_SHAREDEXP: return DXGI_FORMAT_R9G9B9E5_SHAREDEXP;
+ case Format::R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_TYPELESS;
+ case Format::R10G10B10A2_UINT: return DXGI_FORMAT_R10G10B10A2_UINT;
+ case Format::R10G10B10A2_UNORM: return DXGI_FORMAT_R10G10B10A2_UNORM;
+ case Format::R11G11B10_FLOAT: return DXGI_FORMAT_R11G11B10_FLOAT;
+
+ case Format::BC1_UNORM: return DXGI_FORMAT_BC1_UNORM;
+ case Format::BC1_UNORM_SRGB: return DXGI_FORMAT_BC1_UNORM_SRGB;
+ case Format::BC2_UNORM: return DXGI_FORMAT_BC2_UNORM;
+ case Format::BC2_UNORM_SRGB: return DXGI_FORMAT_BC2_UNORM_SRGB;
+ case Format::BC3_UNORM: return DXGI_FORMAT_BC3_UNORM;
+ case Format::BC3_UNORM_SRGB: return DXGI_FORMAT_BC3_UNORM_SRGB;
+ case Format::BC4_UNORM: return DXGI_FORMAT_BC4_UNORM;
+ case Format::BC4_SNORM: return DXGI_FORMAT_BC4_SNORM;
+ case Format::BC5_UNORM: return DXGI_FORMAT_BC5_UNORM;
+ case Format::BC5_SNORM: return DXGI_FORMAT_BC5_SNORM;
+ case Format::BC6H_UF16: return DXGI_FORMAT_BC6H_UF16;
+ case Format::BC6H_SF16: return DXGI_FORMAT_BC6H_SF16;
+ case Format::BC7_UNORM: return DXGI_FORMAT_BC7_UNORM;
+ case Format::BC7_UNORM_SRGB: return DXGI_FORMAT_BC7_UNORM_SRGB;
+
+ default: return DXGI_FORMAT_UNKNOWN;
+ }
+}
+
+/* static */ DXGI_FORMAT
+D3DUtil::calcResourceFormat(UsageType usage, Int usageFlags, DXGI_FORMAT format)
{
SLANG_UNUSED(usage);
if (usageFlags)
{
switch (format)
{
- case DXGI_FORMAT_R32_FLOAT: /* fallthru */
- case DXGI_FORMAT_R32_UINT:
- case DXGI_FORMAT_D32_FLOAT:
+ case DXGI_FORMAT_R32_FLOAT: /* fallthru */
+ case DXGI_FORMAT_R32_UINT:
+ case DXGI_FORMAT_D32_FLOAT:
{
return DXGI_FORMAT_R32_TYPELESS;
}
- case DXGI_FORMAT_D24_UNORM_S8_UINT: return DXGI_FORMAT_R24G8_TYPELESS;
- default: break;
+ case DXGI_FORMAT_D24_UNORM_S8_UINT: return DXGI_FORMAT_R24G8_TYPELESS;
+ default: break;
}
return format;
}
return format;
}
-/* static */DXGI_FORMAT D3DUtil::calcFormat(UsageType usage, DXGI_FORMAT format)
+/* static */ DXGI_FORMAT D3DUtil::calcFormat(UsageType usage, DXGI_FORMAT format)
{
switch (usage)
{
- case USAGE_COUNT_OF:
- case USAGE_UNKNOWN:
+ case USAGE_COUNT_OF:
+ case USAGE_UNKNOWN:
{
return DXGI_FORMAT_UNKNOWN;
}
- case USAGE_DEPTH_STENCIL:
+ case USAGE_DEPTH_STENCIL:
{
switch (format)
{
- case DXGI_FORMAT_D32_FLOAT: /* fallthru */
- case DXGI_FORMAT_R32_TYPELESS:
+ case DXGI_FORMAT_D32_FLOAT: /* fallthru */
+ case DXGI_FORMAT_R32_TYPELESS:
{
return DXGI_FORMAT_D32_FLOAT;
}
- case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return DXGI_FORMAT_D24_UNORM_S8_UINT;
- case DXGI_FORMAT_R24G8_TYPELESS: return DXGI_FORMAT_D24_UNORM_S8_UINT;
- default: break;
+ case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return DXGI_FORMAT_D24_UNORM_S8_UINT;
+ case DXGI_FORMAT_R24G8_TYPELESS: return DXGI_FORMAT_D24_UNORM_S8_UINT;
+ default: break;
}
return format;
}
- case USAGE_TARGET:
+ case USAGE_TARGET:
{
switch (format)
{
- case DXGI_FORMAT_D32_FLOAT: /* fallthru */
- case DXGI_FORMAT_D24_UNORM_S8_UINT:
+ case DXGI_FORMAT_D32_FLOAT: /* fallthru */
+ case DXGI_FORMAT_D24_UNORM_S8_UINT:
{
return DXGI_FORMAT_UNKNOWN;
}
- case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT;
- default: break;
+ case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT;
+ default: break;
}
return format;
}
- case USAGE_SRV:
+ case USAGE_SRV:
{
switch (format)
{
- case DXGI_FORMAT_D32_FLOAT: /* fallthru */
- case DXGI_FORMAT_R32_TYPELESS:
+ case DXGI_FORMAT_D32_FLOAT: /* fallthru */
+ case DXGI_FORMAT_R32_TYPELESS:
{
return DXGI_FORMAT_R32_FLOAT;
}
- case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
- default: break;
+ case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
+ default: break;
}
return format;
@@ -336,101 +305,105 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
{
switch (format)
{
- case DXGI_FORMAT_R32G32B32A32_TYPELESS:
- case DXGI_FORMAT_R32G32B32_TYPELESS:
- case DXGI_FORMAT_R16G16B16A16_TYPELESS:
- case DXGI_FORMAT_R32G32_TYPELESS:
- case DXGI_FORMAT_R32G8X24_TYPELESS:
- case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
- case DXGI_FORMAT_R10G10B10A2_TYPELESS:
- case DXGI_FORMAT_R8G8B8A8_TYPELESS:
- case DXGI_FORMAT_R16G16_TYPELESS:
- case DXGI_FORMAT_R32_TYPELESS:
- case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
- case DXGI_FORMAT_R24G8_TYPELESS:
- case DXGI_FORMAT_R8G8_TYPELESS:
- case DXGI_FORMAT_R16_TYPELESS:
- case DXGI_FORMAT_R8_TYPELESS:
- case DXGI_FORMAT_BC1_TYPELESS:
- case DXGI_FORMAT_BC2_TYPELESS:
- case DXGI_FORMAT_BC3_TYPELESS:
- case DXGI_FORMAT_BC4_TYPELESS:
- case DXGI_FORMAT_BC5_TYPELESS:
- case DXGI_FORMAT_B8G8R8A8_TYPELESS:
- case DXGI_FORMAT_BC6H_TYPELESS:
- case DXGI_FORMAT_BC7_TYPELESS:
+ case DXGI_FORMAT_R32G32B32A32_TYPELESS:
+ case DXGI_FORMAT_R32G32B32_TYPELESS:
+ case DXGI_FORMAT_R16G16B16A16_TYPELESS:
+ case DXGI_FORMAT_R32G32_TYPELESS:
+ case DXGI_FORMAT_R32G8X24_TYPELESS:
+ case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
+ case DXGI_FORMAT_R10G10B10A2_TYPELESS:
+ case DXGI_FORMAT_R8G8B8A8_TYPELESS:
+ case DXGI_FORMAT_R16G16_TYPELESS:
+ case DXGI_FORMAT_R32_TYPELESS:
+ case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
+ case DXGI_FORMAT_R24G8_TYPELESS:
+ case DXGI_FORMAT_R8G8_TYPELESS:
+ case DXGI_FORMAT_R16_TYPELESS:
+ case DXGI_FORMAT_R8_TYPELESS:
+ case DXGI_FORMAT_BC1_TYPELESS:
+ case DXGI_FORMAT_BC2_TYPELESS:
+ case DXGI_FORMAT_BC3_TYPELESS:
+ case DXGI_FORMAT_BC4_TYPELESS:
+ case DXGI_FORMAT_BC5_TYPELESS:
+ case DXGI_FORMAT_B8G8R8A8_TYPELESS:
+ case DXGI_FORMAT_BC6H_TYPELESS:
+ case DXGI_FORMAT_BC7_TYPELESS:
{
return true;
}
- default: break;
+ default: break;
}
return false;
}
-/* static */Int D3DUtil::getNumColorChannelBits(DXGI_FORMAT fmt)
+/* static */ Int D3DUtil::getNumColorChannelBits(DXGI_FORMAT fmt)
{
switch (fmt)
{
- case DXGI_FORMAT_R32G32B32A32_TYPELESS:
- case DXGI_FORMAT_R32G32B32A32_FLOAT:
- case DXGI_FORMAT_R32G32B32A32_UINT:
- case DXGI_FORMAT_R32G32B32A32_SINT:
- case DXGI_FORMAT_R32G32B32_TYPELESS:
- case DXGI_FORMAT_R32G32B32_FLOAT:
- case DXGI_FORMAT_R32G32B32_UINT:
- case DXGI_FORMAT_R32G32B32_SINT:
+ case DXGI_FORMAT_R32G32B32A32_TYPELESS:
+ case DXGI_FORMAT_R32G32B32A32_FLOAT:
+ case DXGI_FORMAT_R32G32B32A32_UINT:
+ case DXGI_FORMAT_R32G32B32A32_SINT:
+ case DXGI_FORMAT_R32G32B32_TYPELESS:
+ case DXGI_FORMAT_R32G32B32_FLOAT:
+ case DXGI_FORMAT_R32G32B32_UINT:
+ case DXGI_FORMAT_R32G32B32_SINT:
{
return 32;
}
- case DXGI_FORMAT_R16G16B16A16_TYPELESS:
- case DXGI_FORMAT_R16G16B16A16_FLOAT:
- case DXGI_FORMAT_R16G16B16A16_UNORM:
- case DXGI_FORMAT_R16G16B16A16_UINT:
- case DXGI_FORMAT_R16G16B16A16_SNORM:
- case DXGI_FORMAT_R16G16B16A16_SINT:
+ case DXGI_FORMAT_R16G16B16A16_TYPELESS:
+ case DXGI_FORMAT_R16G16B16A16_FLOAT:
+ case DXGI_FORMAT_R16G16B16A16_UNORM:
+ case DXGI_FORMAT_R16G16B16A16_UINT:
+ case DXGI_FORMAT_R16G16B16A16_SNORM:
+ case DXGI_FORMAT_R16G16B16A16_SINT:
{
return 16;
}
- case DXGI_FORMAT_R10G10B10A2_TYPELESS:
- case DXGI_FORMAT_R10G10B10A2_UNORM:
- case DXGI_FORMAT_R10G10B10A2_UINT:
- case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
+ case DXGI_FORMAT_R10G10B10A2_TYPELESS:
+ case DXGI_FORMAT_R10G10B10A2_UNORM:
+ case DXGI_FORMAT_R10G10B10A2_UINT:
+ case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
{
return 10;
}
- case DXGI_FORMAT_R8G8B8A8_TYPELESS:
- case DXGI_FORMAT_R8G8B8A8_UNORM:
- case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
- case DXGI_FORMAT_R8G8B8A8_UINT:
- case DXGI_FORMAT_R8G8B8A8_SNORM:
- case DXGI_FORMAT_R8G8B8A8_SINT:
- case DXGI_FORMAT_B8G8R8A8_UNORM:
- case DXGI_FORMAT_B8G8R8X8_UNORM:
- case DXGI_FORMAT_B8G8R8A8_TYPELESS:
- case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
- case DXGI_FORMAT_B8G8R8X8_TYPELESS:
- case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
+ case DXGI_FORMAT_R8G8B8A8_TYPELESS:
+ case DXGI_FORMAT_R8G8B8A8_UNORM:
+ case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
+ case DXGI_FORMAT_R8G8B8A8_UINT:
+ case DXGI_FORMAT_R8G8B8A8_SNORM:
+ case DXGI_FORMAT_R8G8B8A8_SINT:
+ case DXGI_FORMAT_B8G8R8A8_UNORM:
+ case DXGI_FORMAT_B8G8R8X8_UNORM:
+ case DXGI_FORMAT_B8G8R8A8_TYPELESS:
+ case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
+ case DXGI_FORMAT_B8G8R8X8_TYPELESS:
+ case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
{
return 8;
}
- case DXGI_FORMAT_B5G6R5_UNORM:
- case DXGI_FORMAT_B5G5R5A1_UNORM:
+ case DXGI_FORMAT_B5G6R5_UNORM:
+ case DXGI_FORMAT_B5G5R5A1_UNORM:
{
return 5;
}
- case DXGI_FORMAT_B4G4R4A4_UNORM:
- return 4;
+ case DXGI_FORMAT_B4G4R4A4_UNORM: return 4;
- default:
- return 0;
+ default: return 0;
}
}
// Note: this subroutine is now only used by D3D11 for generating bytecode to go into input layouts.
//
-// TODO: we can probably remove that code completely by switching to a PSO-like model across all APIs.
+// TODO: we can probably remove that code completely by switching to a PSO-like model across all
+// APIs.
//
-/* static */Result D3DUtil::compileHLSLShader(char const* sourcePath, char const* source, char const* entryPointName, char const* dxProfileName, ComPtr<ID3DBlob>& shaderBlobOut)
+/* static */ Result D3DUtil::compileHLSLShader(
+ char const* sourcePath,
+ char const* source,
+ char const* entryPointName,
+ char const* dxProfileName,
+ ComPtr<ID3DBlob>& shaderBlobOut)
{
#if !SLANG_ENABLE_DXBC_SUPPORT
return SLANG_E_NOT_IMPLEMENTED;
@@ -458,7 +431,8 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
return SLANG_FAIL;
}
- compileFunc = (pD3DCompile)SharedLibrary::findSymbolAddressByName(compilerModule, "D3DCompile");
+ compileFunc =
+ (pD3DCompile)SharedLibrary::findSymbolAddressByName(compilerModule, "D3DCompile");
if (!compileFunc)
{
fprintf(stderr, "error: failed load symbol 'D3DCompile'\n");
@@ -476,8 +450,8 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
// We will always define `__HLSL__` when compiling here, so that
// input code can react differently to being compiled as pure HLSL.
D3D_SHADER_MACRO defines[] = {
- { "__HLSL__", "1" },
- { nullptr, nullptr },
+ {"__HLSL__", "1"},
+ {nullptr, nullptr},
};
// The `D3DCompile` entry point takes a bunch of parameters, but we
@@ -485,8 +459,18 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
ComPtr<ID3DBlob> shaderBlob;
ComPtr<ID3DBlob> errorBlob;
- HRESULT hr = compileFunc(source, strlen(source), sourcePath, &defines[0], nullptr, entryPointName, dxProfileName, flags, 0,
- shaderBlob.writeRef(), errorBlob.writeRef());
+ HRESULT hr = compileFunc(
+ source,
+ strlen(source),
+ sourcePath,
+ &defines[0],
+ nullptr,
+ entryPointName,
+ dxProfileName,
+ flags,
+ 0,
+ shaderBlob.writeRef(),
+ errorBlob.writeRef());
// If the HLSL-to-bytecode compilation produced any diagnostic messages
// then we will print them out (whether or not the compilation failed).
@@ -505,11 +489,12 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
#endif // SLANG_ENABLE_DXBC_SUPPORT
}
-/* static */SharedLibrary::Handle D3DUtil::getDxgiModule()
+/* static */ SharedLibrary::Handle D3DUtil::getDxgiModule()
{
const char* const libName = SLANG_ENABLE_DXVK ? "dxvk_dxgi" : "dxgi";
- static SharedLibrary::Handle s_dxgiModule = [&](){
+ static SharedLibrary::Handle s_dxgiModule = [&]()
+ {
SharedLibrary::Handle h = nullptr;
SharedLibrary::load(libName, h);
if (!h)
@@ -521,19 +506,23 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
return s_dxgiModule;
}
-/* static */SlangResult D3DUtil::createFactory(DeviceCheckFlags flags, ComPtr<IDXGIFactory>& outFactory)
+/* static */ SlangResult D3DUtil::createFactory(
+ DeviceCheckFlags flags,
+ ComPtr<IDXGIFactory>& outFactory)
{
- auto dxgiModule = getDxgiModule();
+ auto dxgiModule = getDxgiModule();
if (!dxgiModule)
{
return SLANG_FAIL;
}
- typedef HRESULT(WINAPI *PFN_DXGI_CREATE_FACTORY)(REFIID riid, void **ppFactory);
- typedef HRESULT(WINAPI *PFN_DXGI_CREATE_FACTORY_2)(UINT Flags, REFIID riid, void **ppFactory);
+ typedef HRESULT(WINAPI * PFN_DXGI_CREATE_FACTORY)(REFIID riid, void** ppFactory);
+ typedef HRESULT(WINAPI * PFN_DXGI_CREATE_FACTORY_2)(UINT Flags, REFIID riid, void** ppFactory);
{
- auto createFactory2 = (PFN_DXGI_CREATE_FACTORY_2)SharedLibrary::findSymbolAddressByName(dxgiModule, "CreateDXGIFactory2");
+ auto createFactory2 = (PFN_DXGI_CREATE_FACTORY_2)SharedLibrary::findSymbolAddressByName(
+ dxgiModule,
+ "CreateDXGIFactory2");
if (createFactory2)
{
UINT dxgiFlags = 0;
@@ -552,7 +541,9 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
}
{
- auto createFactory = (PFN_DXGI_CREATE_FACTORY)SharedLibrary::findSymbolAddressByName(dxgiModule, "CreateDXGIFactory");
+ auto createFactory = (PFN_DXGI_CREATE_FACTORY)SharedLibrary::findSymbolAddressByName(
+ dxgiModule,
+ "CreateDXGIFactory");
if (!createFactory)
{
fprintf(stderr, "error: failed load symbol '%s'\n", "CreateDXGIFactory");
@@ -562,7 +553,10 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
}
}
-/* static */SlangResult D3DUtil::findAdapters(DeviceCheckFlags flags, const AdapterLUID* adapterLUID, List<ComPtr<IDXGIAdapter>>& outDxgiAdapters)
+/* static */ SlangResult D3DUtil::findAdapters(
+ DeviceCheckFlags flags,
+ const AdapterLUID* adapterLUID,
+ List<ComPtr<IDXGIAdapter>>& outDxgiAdapters)
{
ComPtr<IDXGIFactory> factory;
SLANG_RETURN_ON_FAIL(createFactory(flags, factory));
@@ -579,7 +573,7 @@ bool D3DUtil::isTypeless(DXGI_FORMAT format)
return luid;
}
-/* static */bool D3DUtil::isWarp(IDXGIFactory* dxgiFactory, IDXGIAdapter* adapterIn)
+/* static */ bool D3DUtil::isWarp(IDXGIFactory* dxgiFactory, IDXGIAdapter* adapterIn)
{
ComPtr<IDXGIFactory4> dxgiFactory4;
if (SLANG_SUCCEEDED(dxgiFactory->QueryInterface(IID_PPV_ARGS(dxgiFactory4.writeRef()))))
@@ -599,10 +593,8 @@ bool D3DUtil::isUAVBinding(slang::BindingType bindingType)
{
case slang::BindingType::MutableRawBuffer:
case slang::BindingType::MutableTexture:
- case slang::BindingType::MutableTypedBuffer:
- return true;
- default:
- return false;
+ case slang::BindingType::MutableTypedBuffer: return true;
+ default: return false;
}
}
@@ -636,10 +628,8 @@ uint32_t D3DUtil::getPlaneSliceCount(DXGI_FORMAT format)
switch (format)
{
case DXGI_FORMAT_D24_UNORM_S8_UINT:
- case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
- return 2;
- default:
- return 1;
+ case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return 2;
+ default: return 1;
}
}
@@ -648,28 +638,19 @@ uint32_t D3DUtil::getPlaneSlice(DXGI_FORMAT format, TextureAspect aspect)
switch (aspect)
{
case TextureAspect::Default:
- case TextureAspect::Color:
- return 0;
- case TextureAspect::Depth:
- return 0;
+ case TextureAspect::Color: return 0;
+ case TextureAspect::Depth: return 0;
case TextureAspect::Stencil:
switch (format)
{
case DXGI_FORMAT_D24_UNORM_S8_UINT:
- case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
- return 1;
- default:
- return 0;
+ case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return 1;
+ default: return 0;
}
- case TextureAspect::Plane0:
- return 0;
- case TextureAspect::Plane1:
- return 1;
- case TextureAspect::Plane2:
- return 2;
- default:
- SLANG_ASSERT_FAILURE("Unknown texture aspect.");
- return 0;
+ case TextureAspect::Plane0: return 0;
+ case TextureAspect::Plane1: return 1;
+ case TextureAspect::Plane2: return 2;
+ default: SLANG_ASSERT_FAILURE("Unknown texture aspect."); return 0;
}
}
@@ -677,10 +658,8 @@ D3D12_INPUT_CLASSIFICATION D3DUtil::getInputSlotClass(InputSlotClass slotClass)
{
switch (slotClass)
{
- case InputSlotClass::PerVertex:
- return D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
- case InputSlotClass::PerInstance:
- return D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA;
+ case InputSlotClass::PerVertex: return D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
+ case InputSlotClass::PerInstance: return D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA;
default:
SLANG_ASSERT_FAILURE("Unknown input slot class.");
return D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
@@ -691,13 +670,9 @@ D3D12_FILL_MODE D3DUtil::getFillMode(FillMode mode)
{
switch (mode)
{
- case FillMode::Solid:
- return D3D12_FILL_MODE_SOLID;
- case FillMode::Wireframe:
- return D3D12_FILL_MODE_WIREFRAME;
- default:
- SLANG_ASSERT_FAILURE("Unknown fill mode.");
- return D3D12_FILL_MODE_SOLID;
+ case FillMode::Solid: return D3D12_FILL_MODE_SOLID;
+ case FillMode::Wireframe: return D3D12_FILL_MODE_WIREFRAME;
+ default: SLANG_ASSERT_FAILURE("Unknown fill mode."); return D3D12_FILL_MODE_SOLID;
}
}
@@ -705,15 +680,10 @@ D3D12_CULL_MODE D3DUtil::getCullMode(CullMode mode)
{
switch (mode)
{
- case CullMode::None:
- return D3D12_CULL_MODE_NONE;
- case CullMode::Front:
- return D3D12_CULL_MODE_FRONT;
- case CullMode::Back:
- return D3D12_CULL_MODE_BACK;
- default:
- SLANG_ASSERT_FAILURE("Unknown cull mode.");
- return D3D12_CULL_MODE_NONE;
+ case CullMode::None: return D3D12_CULL_MODE_NONE;
+ case CullMode::Front: return D3D12_CULL_MODE_FRONT;
+ case CullMode::Back: return D3D12_CULL_MODE_BACK;
+ default: SLANG_ASSERT_FAILURE("Unknown cull mode."); return D3D12_CULL_MODE_NONE;
}
}
@@ -721,19 +691,12 @@ D3D12_BLEND_OP D3DUtil::getBlendOp(BlendOp op)
{
switch (op)
{
- case BlendOp::Add:
- return D3D12_BLEND_OP_ADD;
- case BlendOp::Subtract:
- return D3D12_BLEND_OP_SUBTRACT;
- case BlendOp::ReverseSubtract:
- return D3D12_BLEND_OP_REV_SUBTRACT;
- case BlendOp::Min:
- return D3D12_BLEND_OP_MIN;
- case BlendOp::Max:
- return D3D12_BLEND_OP_MAX;
- default:
- SLANG_ASSERT_FAILURE("Unknown blend op.");
- return D3D12_BLEND_OP_ADD;
+ case BlendOp::Add: return D3D12_BLEND_OP_ADD;
+ case BlendOp::Subtract: return D3D12_BLEND_OP_SUBTRACT;
+ case BlendOp::ReverseSubtract: return D3D12_BLEND_OP_REV_SUBTRACT;
+ case BlendOp::Min: return D3D12_BLEND_OP_MIN;
+ case BlendOp::Max: return D3D12_BLEND_OP_MAX;
+ default: SLANG_ASSERT_FAILURE("Unknown blend op."); return D3D12_BLEND_OP_ADD;
}
}
@@ -741,43 +704,24 @@ D3D12_BLEND D3DUtil::getBlendFactor(BlendFactor factor)
{
switch (factor)
{
- case BlendFactor::Zero:
- return D3D12_BLEND_ZERO;
- case BlendFactor::One:
- return D3D12_BLEND_ONE;
- case BlendFactor::SrcColor:
- return D3D12_BLEND_SRC_COLOR;
- case BlendFactor::InvSrcColor:
- return D3D12_BLEND_INV_SRC_COLOR;
- case BlendFactor::SrcAlpha:
- return D3D12_BLEND_SRC_ALPHA;
- case BlendFactor::InvSrcAlpha:
- return D3D12_BLEND_INV_SRC_ALPHA;
- case BlendFactor::DestAlpha:
- return D3D12_BLEND_DEST_ALPHA;
- case BlendFactor::InvDestAlpha:
- return D3D12_BLEND_INV_DEST_ALPHA;
- case BlendFactor::DestColor:
- return D3D12_BLEND_DEST_COLOR;
- case BlendFactor::InvDestColor:
- return D3D12_BLEND_INV_DEST_COLOR;
- case BlendFactor::SrcAlphaSaturate:
- return D3D12_BLEND_SRC_ALPHA_SAT;
- case BlendFactor::BlendColor:
- return D3D12_BLEND_BLEND_FACTOR;
- case BlendFactor::InvBlendColor:
- return D3D12_BLEND_INV_BLEND_FACTOR;
- case BlendFactor::SecondarySrcColor:
- return D3D12_BLEND_SRC1_COLOR;
- case BlendFactor::InvSecondarySrcColor:
- return D3D12_BLEND_INV_SRC1_COLOR;
- case BlendFactor::SecondarySrcAlpha:
- return D3D12_BLEND_SRC1_ALPHA;
- case BlendFactor::InvSecondarySrcAlpha:
- return D3D12_BLEND_INV_SRC1_ALPHA;
- default:
- SLANG_ASSERT_FAILURE("Unknown blend factor.");
- return D3D12_BLEND_ZERO;
+ case BlendFactor::Zero: return D3D12_BLEND_ZERO;
+ case BlendFactor::One: return D3D12_BLEND_ONE;
+ case BlendFactor::SrcColor: return D3D12_BLEND_SRC_COLOR;
+ case BlendFactor::InvSrcColor: return D3D12_BLEND_INV_SRC_COLOR;
+ case BlendFactor::SrcAlpha: return D3D12_BLEND_SRC_ALPHA;
+ case BlendFactor::InvSrcAlpha: return D3D12_BLEND_INV_SRC_ALPHA;
+ case BlendFactor::DestAlpha: return D3D12_BLEND_DEST_ALPHA;
+ case BlendFactor::InvDestAlpha: return D3D12_BLEND_INV_DEST_ALPHA;
+ case BlendFactor::DestColor: return D3D12_BLEND_DEST_COLOR;
+ case BlendFactor::InvDestColor: return D3D12_BLEND_INV_DEST_COLOR;
+ case BlendFactor::SrcAlphaSaturate: return D3D12_BLEND_SRC_ALPHA_SAT;
+ case BlendFactor::BlendColor: return D3D12_BLEND_BLEND_FACTOR;
+ case BlendFactor::InvBlendColor: return D3D12_BLEND_INV_BLEND_FACTOR;
+ case BlendFactor::SecondarySrcColor: return D3D12_BLEND_SRC1_COLOR;
+ case BlendFactor::InvSecondarySrcColor: return D3D12_BLEND_INV_SRC1_COLOR;
+ case BlendFactor::SecondarySrcAlpha: return D3D12_BLEND_SRC1_ALPHA;
+ case BlendFactor::InvSecondarySrcAlpha: return D3D12_BLEND_INV_SRC1_ALPHA;
+ default: SLANG_ASSERT_FAILURE("Unknown blend factor."); return D3D12_BLEND_ZERO;
}
}
@@ -800,55 +744,37 @@ D3D12_RESOURCE_STATES D3DUtil::getResourceState(ResourceState state)
{
switch (state)
{
- case ResourceState::Undefined:
- return D3D12_RESOURCE_STATE_COMMON;
- case ResourceState::General:
- return D3D12_RESOURCE_STATE_COMMON;
- case ResourceState::PreInitialized:
- return D3D12_RESOURCE_STATE_COMMON;
- case ResourceState::VertexBuffer:
- return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
- case ResourceState::IndexBuffer:
- return D3D12_RESOURCE_STATE_INDEX_BUFFER;
- case ResourceState::ConstantBuffer:
- return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
- case ResourceState::StreamOutput:
- return D3D12_RESOURCE_STATE_STREAM_OUT;
+ case ResourceState::Undefined: return D3D12_RESOURCE_STATE_COMMON;
+ case ResourceState::General: return D3D12_RESOURCE_STATE_COMMON;
+ case ResourceState::PreInitialized: return D3D12_RESOURCE_STATE_COMMON;
+ case ResourceState::VertexBuffer: return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
+ case ResourceState::IndexBuffer: return D3D12_RESOURCE_STATE_INDEX_BUFFER;
+ case ResourceState::ConstantBuffer: return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
+ case ResourceState::StreamOutput: return D3D12_RESOURCE_STATE_STREAM_OUT;
case ResourceState::ShaderResource:
case ResourceState::AccelerationStructureBuildInput:
- return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
- case ResourceState::PixelShaderResource:
- return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
+ return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE |
+ D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
+ case ResourceState::PixelShaderResource: return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
case ResourceState::NonPixelShaderResource:
return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
- case ResourceState::UnorderedAccess:
- return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
- case ResourceState::RenderTarget:
- return D3D12_RESOURCE_STATE_RENDER_TARGET;
- case ResourceState::DepthRead:
- return D3D12_RESOURCE_STATE_DEPTH_READ;
- case ResourceState::DepthWrite:;
- return D3D12_RESOURCE_STATE_DEPTH_WRITE;
- case ResourceState::Present:
- return D3D12_RESOURCE_STATE_PRESENT;
- case ResourceState::IndirectArgument:
- return D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
- case ResourceState::CopySource:
- return D3D12_RESOURCE_STATE_COPY_SOURCE;
- case ResourceState::CopyDestination:
- return D3D12_RESOURCE_STATE_COPY_DEST;
- case ResourceState::ResolveSource:
- return D3D12_RESOURCE_STATE_RESOLVE_SOURCE;
- case ResourceState::ResolveDestination:
- return D3D12_RESOURCE_STATE_RESOLVE_DEST;
+ case ResourceState::UnorderedAccess: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
+ case ResourceState::RenderTarget: return D3D12_RESOURCE_STATE_RENDER_TARGET;
+ case ResourceState::DepthRead: return D3D12_RESOURCE_STATE_DEPTH_READ;
+ case ResourceState::DepthWrite: ; return D3D12_RESOURCE_STATE_DEPTH_WRITE;
+ case ResourceState::Present: return D3D12_RESOURCE_STATE_PRESENT;
+ case ResourceState::IndirectArgument: return D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
+ case ResourceState::CopySource: return D3D12_RESOURCE_STATE_COPY_SOURCE;
+ case ResourceState::CopyDestination: return D3D12_RESOURCE_STATE_COPY_DEST;
+ case ResourceState::ResolveSource: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE;
+ case ResourceState::ResolveDestination: return D3D12_RESOURCE_STATE_RESOLVE_DEST;
case ResourceState::AccelerationStructure:
return D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE;
- default:
- return D3D12_RESOURCE_STATE_COMMON;
+ default: return D3D12_RESOURCE_STATE_COMMON;
}
}
-/* static */SlangResult D3DUtil::reportLiveObjects()
+/* static */ SlangResult D3DUtil::reportLiveObjects()
{
static IDXGIDebug* dxgiDebug = nullptr;
@@ -858,7 +784,8 @@ D3D12_RESOURCE_STATES D3DUtil::getResourceState(ResourceState state)
HMODULE debugModule = LoadLibraryA("dxgidebug.dll");
if (debugModule != INVALID_HANDLE_VALUE)
{
- auto fun = reinterpret_cast<decltype(&DXGIGetDebugInterface)>(GetProcAddress(debugModule, "DXGIGetDebugInterface"));
+ auto fun = reinterpret_cast<decltype(&DXGIGetDebugInterface)>(
+ GetProcAddress(debugModule, "DXGIGetDebugInterface"));
if (fun)
{
fun(__uuidof(IDXGIDebug), (void**)&dxgiDebug);
@@ -869,7 +796,8 @@ D3D12_RESOURCE_STATES D3DUtil::getResourceState(ResourceState state)
if (dxgiDebug)
{
- const GUID DXGI_DEBUG_ALL_ = { 0xe48ae283, 0xda80, 0x490b, { 0x87, 0xe6, 0x43, 0xe9, 0xa9, 0xcf, 0xda, 0x8 } };
+ const GUID DXGI_DEBUG_ALL_ =
+ {0xe48ae283, 0xda80, 0x490b, {0x87, 0xe6, 0x43, 0xe9, 0xa9, 0xcf, 0xda, 0x8}};
dxgiDebug->ReportLiveObjects(DXGI_DEBUG_ALL_, DXGI_DEBUG_RLO_ALL);
return SLANG_OK;
}
@@ -883,7 +811,7 @@ Result SLANG_MCALL reportD3DLiveObjects()
}
-/* static */SlangResult D3DUtil::waitForCrashDumpCompletion(HRESULT res)
+/* static */ SlangResult D3DUtil::waitForCrashDumpCompletion(HRESULT res)
{
// If it's not a device remove/reset then theres nothing to wait for
if (!(res == DXGI_ERROR_DEVICE_REMOVED || res == DXGI_ERROR_DEVICE_RESET))
@@ -909,8 +837,8 @@ Result SLANG_MCALL reportD3DLiveObjects()
// Loop while Aftermath crash dump data collection has not finished or
// the application is still processing the crash dump data.
while (status != GFSDK_Aftermath_CrashDump_Status_CollectingDataFailed &&
- status != GFSDK_Aftermath_CrashDump_Status_Finished &&
- Process::getClockTick() - startTick < timeOutTicks)
+ status != GFSDK_Aftermath_CrashDump_Status_Finished &&
+ Process::getClockTick() - startTick < timeOutTicks)
{
// Sleep a couple of milliseconds and poll the status again.
Process::sleepCurrentThread(50);
@@ -934,7 +862,11 @@ Result SLANG_MCALL reportD3DLiveObjects()
return SLANG_OK;
}
-/* static */SlangResult D3DUtil::findAdapters(DeviceCheckFlags flags, const AdapterLUID* adapterLUID, IDXGIFactory* dxgiFactory, List<ComPtr<IDXGIAdapter>>& outDxgiAdapters)
+/* static */ SlangResult D3DUtil::findAdapters(
+ DeviceCheckFlags flags,
+ const AdapterLUID* adapterLUID,
+ IDXGIFactory* dxgiFactory,
+ List<ComPtr<IDXGIAdapter>>& outDxgiAdapters)
{
outDxgiAdapters.clear();
@@ -979,7 +911,8 @@ Result SLANG_MCALL reportD3DLiveObjects()
}
// If the right type then add it
- if ((deviceFlags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0 && (flags & DeviceCheckFlag::UseHardwareDevice) != 0)
+ if ((deviceFlags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0 &&
+ (flags & DeviceCheckFlag::UseHardwareDevice) != 0)
{
outDxgiAdapters.add(dxgiAdapter);
}
diff --git a/tools/gfx/d3d/d3d-util.h b/tools/gfx/d3d/d3d-util.h
index ce40ec722..af186a336 100644
--- a/tools/gfx/d3d/d3d-util.h
+++ b/tools/gfx/d3d/d3d-util.h
@@ -1,52 +1,49 @@
// d3d-util.h
#pragma once
-#include <stdint.h>
-
-#include "slang-com-helper.h"
-
-#include "slang-com-ptr.h"
+#include "../flag-combiner.h"
#include "core/slang-basic.h"
#include "core/slang-platform.h"
-
-#include "../flag-combiner.h"
-
+#include "slang-com-helper.h"
+#include "slang-com-ptr.h"
#include "slang-gfx.h"
+#include <d3d12.h>
#include <d3dcommon.h>
-#include <dxgiformat.h>
#include <dxgi.h>
-#include <d3d12.h>
+#include <dxgiformat.h>
+#include <stdint.h>
#if defined(__ID3D12Device5_FWD_DEFINED__) && defined(__ID3D12GraphicsCommandList4_FWD_DEFINED__)
-# define SLANG_GFX_HAS_DXR_SUPPORT 1
+#define SLANG_GFX_HAS_DXR_SUPPORT 1
#else
-# define SLANG_GFX_HAS_DXR_SUPPORT 0
+#define SLANG_GFX_HAS_DXR_SUPPORT 0
typedef ISlangUnknown ID3D12Device5;
typedef ISlangUnknown ID3D12GraphicsCommandList4;
#endif
-namespace gfx {
+namespace gfx
+{
class D3DUtil
{
- public:
+public:
enum UsageType
{
- USAGE_UNKNOWN, ///< Generally used to mark an error
- USAGE_TARGET, ///< Format should be used when written as target
- USAGE_DEPTH_STENCIL, ///< Format should be used when written as depth stencil
- USAGE_SRV, ///< Format if being read as srv
+ USAGE_UNKNOWN, ///< Generally used to mark an error
+ USAGE_TARGET, ///< Format should be used when written as target
+ USAGE_DEPTH_STENCIL, ///< Format should be used when written as depth stencil
+ USAGE_SRV, ///< Format if being read as srv
USAGE_COUNT_OF,
};
enum UsageFlag
{
- USAGE_FLAG_MULTI_SAMPLE = 0x1, ///< If set will be used form multi sampling (such as MSAA)
- USAGE_FLAG_SRV = 0x2, ///< If set means will be used as a shader resource view (SRV)
+ USAGE_FLAG_MULTI_SAMPLE = 0x1, ///< If set will be used form multi sampling (such as MSAA)
+ USAGE_FLAG_SRV = 0x2, ///< If set means will be used as a shader resource view (SRV)
};
- /// Get primitive topology as D3D primitive topology
+ /// Get primitive topology as D3D primitive topology
static D3D_PRIMITIVE_TOPOLOGY getPrimitiveTopology(PrimitiveTopology prim);
static D3D12_PRIMITIVE_TOPOLOGY_TYPE getPrimitiveType(PrimitiveType type);
@@ -57,38 +54,58 @@ class D3DUtil
static D3D12_DEPTH_STENCILOP_DESC translateStencilOpDesc(DepthStencilOpDesc desc);
- /// Calculate size taking into account alignment. Alignment must be a power of 2
- static UInt calcAligned(UInt size, UInt alignment) { return (size + alignment - 1) & ~(alignment - 1); }
+ /// Calculate size taking into account alignment. Alignment must be a power of 2
+ static UInt calcAligned(UInt size, UInt alignment)
+ {
+ return (size + alignment - 1) & ~(alignment - 1);
+ }
- /// Compile HLSL code to DXBC
- static Slang::Result compileHLSLShader(char const* sourcePath, char const* source, char const* entryPointName, char const* dxProfileName, Slang::ComPtr<ID3DBlob>& shaderBlobOut);
+ /// Compile HLSL code to DXBC
+ static Slang::Result compileHLSLShader(
+ char const* sourcePath,
+ char const* source,
+ char const* entryPointName,
+ char const* dxProfileName,
+ Slang::ComPtr<ID3DBlob>& shaderBlobOut);
- /// Given a slang pixel format returns the equivalent DXGI_ pixel format. If the format is not known, will return DXGI_FORMAT_UNKNOWN
+ /// Given a slang pixel format returns the equivalent DXGI_ pixel format. If the format is not
+ /// known, will return DXGI_FORMAT_UNKNOWN
static DXGI_FORMAT getMapFormat(Format format);
- /// Given the usage, flags, and format will return the most suitable format. Will return DXGI_UNKNOWN if combination is not possible
+ /// Given the usage, flags, and format will return the most suitable format. Will return
+ /// DXGI_UNKNOWN if combination is not possible
static DXGI_FORMAT calcFormat(UsageType usage, DXGI_FORMAT format);
- /// Calculate appropriate format for creating a buffer for usage and flags
+ /// Calculate appropriate format for creating a buffer for usage and flags
static DXGI_FORMAT calcResourceFormat(UsageType usage, Int usageFlags, DXGI_FORMAT format);
- /// True if the type is 'typeless'
+ /// True if the type is 'typeless'
static bool isTypeless(DXGI_FORMAT format);
- /// Returns number of bits used for color channel for format (for channels with multiple sizes, returns smallest ie RGB565 -> 5)
+ /// Returns number of bits used for color channel for format (for channels with multiple sizes,
+ /// returns smallest ie RGB565 -> 5)
static Int getNumColorChannelBits(DXGI_FORMAT fmt);
- static SlangResult createFactory(DeviceCheckFlags flags, Slang::ComPtr<IDXGIFactory>& outFactory);
+ static SlangResult createFactory(
+ DeviceCheckFlags flags,
+ Slang::ComPtr<IDXGIFactory>& outFactory);
- /// Get the dxgiModule
+ /// Get the dxgiModule
static Slang::SharedLibrary::Handle getDxgiModule();
- /// Find adapters
- static SlangResult findAdapters(DeviceCheckFlags flags, const AdapterLUID* adapterLUID, IDXGIFactory* dxgiFactory, Slang::List<Slang::ComPtr<IDXGIAdapter>>& dxgiAdapters);
- /// Find adapters
- static SlangResult findAdapters(DeviceCheckFlags flags, const AdapterLUID* adapterLUID, Slang::List<Slang::ComPtr<IDXGIAdapter>>& dxgiAdapters);
+ /// Find adapters
+ static SlangResult findAdapters(
+ DeviceCheckFlags flags,
+ const AdapterLUID* adapterLUID,
+ IDXGIFactory* dxgiFactory,
+ Slang::List<Slang::ComPtr<IDXGIAdapter>>& dxgiAdapters);
+ /// Find adapters
+ static SlangResult findAdapters(
+ DeviceCheckFlags flags,
+ const AdapterLUID* adapterLUID,
+ Slang::List<Slang::ComPtr<IDXGIAdapter>>& dxgiAdapters);
static AdapterLUID getAdapterLUID(IDXGIAdapter* dxgiAdapter);
- /// True if the adapter is warp
+ /// True if the adapter is warp
static bool isWarp(IDXGIFactory* dxgiFactory, IDXGIAdapter* adapter);
static bool isUAVBinding(slang::BindingType bindingType);
@@ -122,8 +139,8 @@ class D3DUtil
static SlangResult reportLiveObjects();
- /// Call after a DXGI_ERROR_DEVICE_REMOVED/DXGI_ERROR_DEVICE_RESET on present, to wait for
- /// dumping to complete. Will return SLANG_OK if wait happened successfully
+ /// Call after a DXGI_ERROR_DEVICE_REMOVED/DXGI_ERROR_DEVICE_RESET on present, to wait for
+ /// dumping to complete. Will return SLANG_OK if wait happened successfully
static SlangResult waitForCrashDumpCompletion(HRESULT res);
};
@@ -138,11 +155,11 @@ struct D3DAccelerationStructureInputsBuilder
IDebugCallback* callback);
private:
- D3D12_RAYTRACING_GEOMETRY_FLAGS translateGeometryFlags(
- IAccelerationStructure::GeometryFlags::Enum flags)
+ D3D12_RAYTRACING_GEOMETRY_FLAGS
+ translateGeometryFlags(IAccelerationStructure::GeometryFlags::Enum flags)
{
return (D3D12_RAYTRACING_GEOMETRY_FLAGS)flags;
}
};
#endif
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/d3d11/d3d11-base.h b/tools/gfx/d3d11/d3d11-base.h
index ce38bb174..084654991 100644
--- a/tools/gfx/d3d11/d3d11-base.h
+++ b/tools/gfx/d3d11/d3d11-base.h
@@ -2,16 +2,15 @@
// Shared header file for D3D11 implementation
#pragma once
-#include "../immediate-renderer-base.h"
-#include "../d3d/d3d-util.h"
#include "../d3d/d3d-swapchain.h"
-#include "../nvapi/nvapi-util.h"
+#include "../d3d/d3d-util.h"
+#include "../flag-combiner.h"
+#include "../immediate-renderer-base.h"
#include "../mutable-shader-object.h"
+#include "../nvapi/nvapi-util.h"
#include "core/slang-basic.h"
#include "core/slang-blob.h"
-
#include "slang-com-ptr.h"
-#include "../flag-combiner.h"
#pragma push_macro("WIN32_LEAN_AND_MEAN")
#pragma push_macro("NOMINMAX")
@@ -30,7 +29,7 @@
// NVAPI integration is described here
// https://developer.nvidia.com/unlocking-gpu-intrinsics-hlsl
-# include "../nvapi/nvapi-include.h"
+#include "../nvapi/nvapi-include.h"
#endif
// We will use the C standard library just for printing error messages.
@@ -47,28 +46,28 @@ namespace gfx
{
namespace d3d11
{
- class DeviceImpl;
- class ShaderProgramImpl;
- class BufferResourceImpl;
- class TextureResourceImpl;
- class SamplerStateImpl;
- class ResourceViewImpl;
- class ShaderResourceViewImpl;
- class UnorderedAccessViewImpl;
- class DepthStencilViewImpl;
- class RenderTargetViewImpl;
- class FramebufferLayoutImpl;
- class FramebufferImpl;
- class SwapchainImpl;
- class InputLayoutImpl;
- class QueryPoolImpl;
- class PipelineStateImpl;
- class GraphicsPipelineStateImpl;
- class ComputePipelineStateImpl;
- class ShaderObjectLayoutImpl;
- class RootShaderObjectLayoutImpl;
- class ShaderObjectImpl;
- class MutableShaderObjectImpl;
- class RootShaderObjectImpl;
-}
-}
+class DeviceImpl;
+class ShaderProgramImpl;
+class BufferResourceImpl;
+class TextureResourceImpl;
+class SamplerStateImpl;
+class ResourceViewImpl;
+class ShaderResourceViewImpl;
+class UnorderedAccessViewImpl;
+class DepthStencilViewImpl;
+class RenderTargetViewImpl;
+class FramebufferLayoutImpl;
+class FramebufferImpl;
+class SwapchainImpl;
+class InputLayoutImpl;
+class QueryPoolImpl;
+class PipelineStateImpl;
+class GraphicsPipelineStateImpl;
+class ComputePipelineStateImpl;
+class ShaderObjectLayoutImpl;
+class RootShaderObjectLayoutImpl;
+class ShaderObjectImpl;
+class MutableShaderObjectImpl;
+class RootShaderObjectImpl;
+} // namespace d3d11
+} // namespace gfx
diff --git a/tools/gfx/d3d11/d3d11-buffer.cpp b/tools/gfx/d3d11/d3d11-buffer.cpp
index aa51b999f..42c4c698c 100644
--- a/tools/gfx/d3d11/d3d11-buffer.cpp
+++ b/tools/gfx/d3d11/d3d11-buffer.cpp
@@ -15,7 +15,7 @@ SLANG_NO_THROW DeviceAddress SLANG_MCALL BufferResourceImpl::getDeviceAddress()
}
SLANG_NO_THROW Result SLANG_MCALL
- BufferResourceImpl::map(MemoryRange* rangeToRead, void** outPointer)
+BufferResourceImpl::map(MemoryRange* rangeToRead, void** outPointer)
{
SLANG_UNUSED(rangeToRead);
SLANG_UNUSED(outPointer);
diff --git a/tools/gfx/d3d11/d3d11-buffer.h b/tools/gfx/d3d11/d3d11-buffer.h
index f5462b029..237e33fd6 100644
--- a/tools/gfx/d3d11/d3d11-buffer.h
+++ b/tools/gfx/d3d11/d3d11-buffer.h
@@ -16,8 +16,8 @@ class BufferResourceImpl : public BufferResource
public:
typedef BufferResource Parent;
- BufferResourceImpl(const IBufferResource::Desc& desc) :
- Parent(desc)
+ BufferResourceImpl(const IBufferResource::Desc& desc)
+ : Parent(desc)
{
}
@@ -29,7 +29,7 @@ public:
virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- map(MemoryRange* rangeToRead, void** outPointer) override;
+ map(MemoryRange* rangeToRead, void** outPointer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL unmap(MemoryRange* writtenRange) override;
};
diff --git a/tools/gfx/d3d11/d3d11-device.cpp b/tools/gfx/d3d11/d3d11-device.cpp
index 148590831..8fe3bf589 100644
--- a/tools/gfx/d3d11/d3d11-device.cpp
+++ b/tools/gfx/d3d11/d3d11-device.cpp
@@ -3,23 +3,22 @@
#include "d3d11-device.h"
#include "d3d11-buffer.h"
+#include "d3d11-helper-functions.h"
#include "d3d11-query.h"
#include "d3d11-resource-views.h"
#include "d3d11-sampler.h"
#include "d3d11-scopeNVAPI.h"
-#include "d3d11-shader-object.h"
#include "d3d11-shader-object-layout.h"
+#include "d3d11-shader-object.h"
#include "d3d11-shader-program.h"
#include "d3d11-swap-chain.h"
#include "d3d11-texture.h"
#include "d3d11-vertex-layout.h"
-#include "d3d11-helper-functions.h"
-
#ifdef GFX_NV_AFTERMATH
-# include "GFSDK_Aftermath.h"
-# include "GFSDK_Aftermath_Defines.h"
-# include "GFSDK_Aftermath_GpuCrashDump.h"
+#include "GFSDK_Aftermath.h"
+#include "GFSDK_Aftermath_Defines.h"
+#include "GFSDK_Aftermath_GpuCrashDump.h"
#endif
namespace gfx
@@ -38,7 +37,7 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
desc.extendedDescs,
SLANG_DXBC,
"sm_5_0",
- makeArray(slang::PreprocessorMacroDesc{ "__D3D11__", "1" }).getView()));
+ makeArray(slang::PreprocessorMacroDesc{"__D3D11__", "1"}).getView()));
SLANG_RETURN_ON_FAIL(RendererBase::initialize(desc));
@@ -48,7 +47,7 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
m_info.bindingStyle = BindingStyle::DirectX;
m_info.projectionStyle = ProjectionStyle::DirectX;
m_info.apiName = "Direct3D 11";
- static const float kIdentity[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
+ static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
::memcpy(m_info.identityProjectionMatrix, kIdentity, sizeof(kIdentity));
}
@@ -64,20 +63,20 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
}
PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN D3D11CreateDeviceAndSwapChain_ =
- (PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN)SharedLibrary::findSymbolAddressByName(d3dModule, "D3D11CreateDeviceAndSwapChain");
+ (PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN)SharedLibrary::findSymbolAddressByName(
+ d3dModule,
+ "D3D11CreateDeviceAndSwapChain");
if (!D3D11CreateDeviceAndSwapChain_)
{
- fprintf(stderr,
- "error: failed load symbol 'D3D11CreateDeviceAndSwapChain'\n");
+ fprintf(stderr, "error: failed load symbol 'D3D11CreateDeviceAndSwapChain'\n");
return SLANG_FAIL;
}
- PFN_D3D11_CREATE_DEVICE D3D11CreateDevice_ =
- (PFN_D3D11_CREATE_DEVICE)SharedLibrary::findSymbolAddressByName(d3dModule, "D3D11CreateDevice");
+ PFN_D3D11_CREATE_DEVICE D3D11CreateDevice_ = (PFN_D3D11_CREATE_DEVICE)
+ SharedLibrary::findSymbolAddressByName(d3dModule, "D3D11CreateDevice");
if (!D3D11CreateDevice_)
{
- fprintf(stderr,
- "error: failed load symbol 'D3D11CreateDevice'\n");
+ fprintf(stderr, "error: failed load symbol 'D3D11CreateDevice'\n");
return SLANG_FAIL;
}
@@ -107,12 +106,18 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
// up to each back-end to specify.
#if _DEBUG
- combiner.add(DeviceCheckFlag::UseDebug, ChangeType::OnOff); ///< First try debug then non debug
+ combiner.add(
+ DeviceCheckFlag::UseDebug,
+ ChangeType::OnOff); ///< First try debug then non debug
#else
- combiner.add(DeviceCheckFlag::UseDebug, ChangeType::Off); ///< Don't bother with debug
+ combiner.add(DeviceCheckFlag::UseDebug, ChangeType::Off); ///< Don't bother with debug
#endif
- combiner.add(DeviceCheckFlag::UseHardwareDevice, ChangeType::OnOff); ///< First try hardware, then reference
- combiner.add(DeviceCheckFlag::UseFullFeatureLevel, ChangeType::OnOff); ///< First try fully featured, then degrade features
+ combiner.add(
+ DeviceCheckFlag::UseHardwareDevice,
+ ChangeType::OnOff); ///< First try hardware, then reference
+ combiner.add(
+ DeviceCheckFlag::UseFullFeatureLevel,
+ ChangeType::OnOff); ///< First try fully featured, then degrade features
const int numCombinations = combiner.getNumCombinations();
@@ -127,7 +132,11 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
if (desc.adapterLUID)
{
List<ComPtr<IDXGIAdapter>> dxgiAdapters;
- D3DUtil::findAdapters(deviceCheckFlags, desc.adapterLUID, m_dxgiFactory, dxgiAdapters);
+ D3DUtil::findAdapters(
+ deviceCheckFlags,
+ desc.adapterLUID,
+ m_dxgiFactory,
+ dxgiAdapters);
if (dxgiAdapters.getCount() == 0)
{
continue;
@@ -135,16 +144,21 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
adapter = dxgiAdapters[0];
}
- // The adapter can be nullptr - that just means 'default', but when so we need to select the driver type
+ // The adapter can be nullptr - that just means 'default', but when so we need to select
+ // the driver type
D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_UNKNOWN;
if (adapter == nullptr)
{
// If we don't have an adapter, select directly
- driverType = (deviceCheckFlags & DeviceCheckFlag::UseHardwareDevice) ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_REFERENCE;
+ driverType = (deviceCheckFlags & DeviceCheckFlag::UseHardwareDevice)
+ ? D3D_DRIVER_TYPE_HARDWARE
+ : D3D_DRIVER_TYPE_REFERENCE;
}
- const int startFeatureIndex = (deviceCheckFlags & DeviceCheckFlag::UseFullFeatureLevel) ? 0 : 1;
- const UINT deviceFlags = (deviceCheckFlags & DeviceCheckFlag::UseDebug) ? D3D11_CREATE_DEVICE_DEBUG : 0;
+ const int startFeatureIndex =
+ (deviceCheckFlags & DeviceCheckFlag::UseFullFeatureLevel) ? 0 : 1;
+ const UINT deviceFlags =
+ (deviceCheckFlags & DeviceCheckFlag::UseDebug) ? D3D11_CREATE_DEVICE_DEBUG : 0;
res = D3D11CreateDevice_(
adapter,
@@ -161,16 +175,24 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
#ifdef GFX_NV_AFTERMATH
if (SLANG_SUCCEEDED(res))
{
- if (deviceCheckFlags & DeviceCheckFlag::UseDebug)
+ if (deviceCheckFlags & DeviceCheckFlag::UseDebug)
{
// Initialize Nsight Aftermath for this device.
- // This combination of flags is not necessarily appropriate for real world usage
+ // This combination of flags is not necessarily appropriate for real world usage
const uint32_t aftermathFlags =
- GFSDK_Aftermath_FeatureFlags_EnableMarkers | // Enable event marker tracking.
- GFSDK_Aftermath_FeatureFlags_CallStackCapturing | // Enable automatic call stack event markers.
- GFSDK_Aftermath_FeatureFlags_EnableResourceTracking | // Enable tracking of resources.
- GFSDK_Aftermath_FeatureFlags_GenerateShaderDebugInfo | // Generate debug information for shaders.
- GFSDK_Aftermath_FeatureFlags_EnableShaderErrorReporting; // Enable additional runtime shader error reporting.
+ GFSDK_Aftermath_FeatureFlags_EnableMarkers | // Enable event marker
+ // tracking.
+ GFSDK_Aftermath_FeatureFlags_CallStackCapturing | // Enable automatic call
+ // stack event markers.
+ GFSDK_Aftermath_FeatureFlags_EnableResourceTracking | // Enable tracking of
+ // resources.
+ GFSDK_Aftermath_FeatureFlags_GenerateShaderDebugInfo | // Generate debug
+ // information for
+ // shaders.
+ GFSDK_Aftermath_FeatureFlags_EnableShaderErrorReporting; // Enable
+ // additional
+ // runtime shader
+ // error reporting.
auto initResult = GFSDK_Aftermath_DX11_Initialize(
GFSDK_Aftermath_Version_API,
@@ -192,7 +214,6 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
{
break;
}
-
}
// If res is failure, means all styles have have failed, and so initialization fails.
if (SLANG_FAILED(res))
@@ -250,8 +271,7 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
// Create a TIMESTAMP_DISJOINT query object to query/update frequency info.
D3D11_QUERY_DESC disjointQueryDesc = {};
disjointQueryDesc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
- SLANG_RETURN_ON_FAIL(m_device->CreateQuery(
- &disjointQueryDesc, m_disjointQuery.writeRef()));
+ SLANG_RETURN_ON_FAIL(m_device->CreateQuery(&disjointQueryDesc, m_disjointQuery.writeRef()));
m_immediateContext->Begin(m_disjointQuery);
m_immediateContext->End(m_disjointQuery);
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT disjointData = {};
@@ -310,15 +330,17 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
limits.maxVertexInputElements = maxInputElements;
limits.maxVertexInputElementOffset = 256; // TODO
- limits.maxVertexStreams = D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT ;
+ limits.maxVertexStreams = D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT;
limits.maxVertexStreamStride = D3D11_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES;
limits.maxComputeThreadsPerGroup = D3D11_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP;
limits.maxComputeThreadGroupSize[0] = maxComputeThreadGroupSizeXY;
limits.maxComputeThreadGroupSize[1] = maxComputeThreadGroupSizeXY;
limits.maxComputeThreadGroupSize[2] = maxComputeThreadGroupSizeZ;
- limits.maxComputeDispatchThreadGroups[0] = D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
- limits.maxComputeDispatchThreadGroups[1] = D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
+ limits.maxComputeDispatchThreadGroups[0] =
+ D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
+ limits.maxComputeDispatchThreadGroups[1] =
+ D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
limits.maxComputeDispatchThreadGroups[2] = maxComputeDispatchThreadGroupsZ;
limits.maxViewports = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
@@ -365,7 +387,9 @@ void DeviceImpl::clearFrame(uint32_t colorBufferMask, bool clearDepth, bool clea
}
Result DeviceImpl::createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain)
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain)
{
RefPtr<SwapchainImpl> swapchain = new SwapchainImpl();
SLANG_RETURN_ON_FAIL(swapchain->init(this, desc, window));
@@ -374,7 +398,8 @@ Result DeviceImpl::createSwapchain(
}
Result DeviceImpl::createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout)
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout)
{
RefPtr<FramebufferLayoutImpl> layout = new FramebufferLayoutImpl();
layout->m_renderTargets.setCount(desc.renderTargetCount);
@@ -396,19 +421,20 @@ Result DeviceImpl::createFramebufferLayout(
return SLANG_OK;
}
-Result DeviceImpl::createFramebuffer(
- const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer)
+Result DeviceImpl::createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer)
{
RefPtr<FramebufferImpl> framebuffer = new FramebufferImpl();
framebuffer->renderTargetViews.setCount(desc.renderTargetCount);
framebuffer->d3dRenderTargetViews.setCount(desc.renderTargetCount);
for (GfxIndex i = 0; i < desc.renderTargetCount; i++)
{
- framebuffer->renderTargetViews[i] = static_cast<RenderTargetViewImpl*>(desc.renderTargetViews[i]);
+ framebuffer->renderTargetViews[i] =
+ static_cast<RenderTargetViewImpl*>(desc.renderTargetViews[i]);
framebuffer->d3dRenderTargetViews[i] = framebuffer->renderTargetViews[i]->m_rtv;
}
framebuffer->depthStencilView = static_cast<DepthStencilViewImpl*>(desc.depthStencilView);
- framebuffer->d3dDepthStencilView = framebuffer->depthStencilView ? framebuffer->depthStencilView->m_dsv : nullptr;
+ framebuffer->d3dDepthStencilView =
+ framebuffer->depthStencilView ? framebuffer->depthStencilView->m_dsv : nullptr;
returnComPtr(outFramebuffer, framebuffer);
return SLANG_OK;
}
@@ -491,7 +517,8 @@ SlangResult DeviceImpl::readTextureResource(
// Now just read back texels from the staging textures
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
- SLANG_RETURN_ON_FAIL(m_immediateContext->Map(stagingTexture, 0, D3D11_MAP_READ, 0, &mappedResource));
+ SLANG_RETURN_ON_FAIL(
+ m_immediateContext->Map(stagingTexture, 0, D3D11_MAP_READ, 0, &mappedResource));
List<uint8_t> data;
@@ -514,7 +541,10 @@ SlangResult DeviceImpl::readTextureResource(
}
}
-Result DeviceImpl::createTextureResource(const ITextureResource::Desc& descIn, const ITextureResource::SubresourceData* initData, ITextureResource** outResource)
+Result DeviceImpl::createTextureResource(
+ const ITextureResource::Desc& descIn,
+ const ITextureResource::SubresourceData* initData,
+ ITextureResource** outResource)
{
TextureResource::Desc srcDesc = fixupTextureDesc(descIn);
@@ -563,79 +593,84 @@ Result DeviceImpl::createTextureResource(const ITextureResource::Desc& descIn, c
switch (srcDesc.type)
{
case IResource::Type::Texture1D:
- {
- D3D11_TEXTURE1D_DESC desc = { 0 };
- desc.BindFlags = bindFlags;
- desc.CPUAccessFlags = accessFlags;
- desc.Format = format;
- desc.MiscFlags = 0;
- desc.MipLevels = srcDesc.numMipLevels;
- desc.ArraySize = effectiveArraySize;
- desc.Width = srcDesc.size.width;
- desc.Usage = D3D11_USAGE_DEFAULT;
-
- ComPtr<ID3D11Texture1D> texture1D;
- SLANG_RETURN_ON_FAIL(m_device->CreateTexture1D(&desc, subResourcesPtr, texture1D.writeRef()));
-
- texture->m_resource = texture1D;
- break;
- }
+ {
+ D3D11_TEXTURE1D_DESC desc = {0};
+ desc.BindFlags = bindFlags;
+ desc.CPUAccessFlags = accessFlags;
+ desc.Format = format;
+ desc.MiscFlags = 0;
+ desc.MipLevels = srcDesc.numMipLevels;
+ desc.ArraySize = effectiveArraySize;
+ desc.Width = srcDesc.size.width;
+ desc.Usage = D3D11_USAGE_DEFAULT;
+
+ ComPtr<ID3D11Texture1D> texture1D;
+ SLANG_RETURN_ON_FAIL(
+ m_device->CreateTexture1D(&desc, subResourcesPtr, texture1D.writeRef()));
+
+ texture->m_resource = texture1D;
+ break;
+ }
case IResource::Type::TextureCube:
case IResource::Type::Texture2D:
- {
- D3D11_TEXTURE2D_DESC desc = { 0 };
- desc.BindFlags = bindFlags;
- desc.CPUAccessFlags = accessFlags;
- desc.Format = format;
- desc.MiscFlags = 0;
- desc.MipLevels = srcDesc.numMipLevels;
- desc.ArraySize = effectiveArraySize;
-
- desc.Width = srcDesc.size.width;
- desc.Height = srcDesc.size.height;
- desc.Usage = D3D11_USAGE_DEFAULT;
- desc.SampleDesc.Count = srcDesc.sampleDesc.numSamples;
- desc.SampleDesc.Quality = srcDesc.sampleDesc.quality;
-
- if (srcDesc.type == IResource::Type::TextureCube)
{
- desc.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE;
- }
+ D3D11_TEXTURE2D_DESC desc = {0};
+ desc.BindFlags = bindFlags;
+ desc.CPUAccessFlags = accessFlags;
+ desc.Format = format;
+ desc.MiscFlags = 0;
+ desc.MipLevels = srcDesc.numMipLevels;
+ desc.ArraySize = effectiveArraySize;
+
+ desc.Width = srcDesc.size.width;
+ desc.Height = srcDesc.size.height;
+ desc.Usage = D3D11_USAGE_DEFAULT;
+ desc.SampleDesc.Count = srcDesc.sampleDesc.numSamples;
+ desc.SampleDesc.Quality = srcDesc.sampleDesc.quality;
+
+ if (srcDesc.type == IResource::Type::TextureCube)
+ {
+ desc.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE;
+ }
- ComPtr<ID3D11Texture2D> texture2D;
- SLANG_RETURN_ON_FAIL(m_device->CreateTexture2D(&desc, subResourcesPtr, texture2D.writeRef()));
+ ComPtr<ID3D11Texture2D> texture2D;
+ SLANG_RETURN_ON_FAIL(
+ m_device->CreateTexture2D(&desc, subResourcesPtr, texture2D.writeRef()));
- texture->m_resource = texture2D;
- break;
- }
+ texture->m_resource = texture2D;
+ break;
+ }
case IResource::Type::Texture3D:
- {
- D3D11_TEXTURE3D_DESC desc = { 0 };
- desc.BindFlags = bindFlags;
- desc.CPUAccessFlags = accessFlags;
- desc.Format = format;
- desc.MiscFlags = 0;
- desc.MipLevels = srcDesc.numMipLevels;
- desc.Width = srcDesc.size.width;
- desc.Height = srcDesc.size.height;
- desc.Depth = srcDesc.size.depth;
- desc.Usage = D3D11_USAGE_DEFAULT;
-
- ComPtr<ID3D11Texture3D> texture3D;
- SLANG_RETURN_ON_FAIL(m_device->CreateTexture3D(&desc, subResourcesPtr, texture3D.writeRef()));
-
- texture->m_resource = texture3D;
- break;
- }
- default:
- return SLANG_FAIL;
+ {
+ D3D11_TEXTURE3D_DESC desc = {0};
+ desc.BindFlags = bindFlags;
+ desc.CPUAccessFlags = accessFlags;
+ desc.Format = format;
+ desc.MiscFlags = 0;
+ desc.MipLevels = srcDesc.numMipLevels;
+ desc.Width = srcDesc.size.width;
+ desc.Height = srcDesc.size.height;
+ desc.Depth = srcDesc.size.depth;
+ desc.Usage = D3D11_USAGE_DEFAULT;
+
+ ComPtr<ID3D11Texture3D> texture3D;
+ SLANG_RETURN_ON_FAIL(
+ m_device->CreateTexture3D(&desc, subResourcesPtr, texture3D.writeRef()));
+
+ texture->m_resource = texture3D;
+ break;
+ }
+ default: return SLANG_FAIL;
}
returnComPtr(outResource, texture);
return SLANG_OK;
}
-Result DeviceImpl::createBufferResource(const IBufferResource::Desc& descIn, const void* initData, IBufferResource** outResource)
+Result DeviceImpl::createBufferResource(
+ const IBufferResource::Desc& descIn,
+ const void* initData,
+ IBufferResource** outResource)
{
IBufferResource::Desc srcDesc = fixupBufferDesc(descIn);
@@ -649,7 +684,8 @@ Result DeviceImpl::createBufferResource(const IBufferResource::Desc& descIn, con
alignedSizeInBytes = D3DUtil::calcAligned(alignedSizeInBytes, 256);
}
- // Hack to make the initialization never read from out of bounds memory, by copying into a buffer
+ // Hack to make the initialization never read from out of bounds memory, by copying into a
+ // buffer
List<uint8_t> initDataBuffer;
if (initData && alignedSizeInBytes > srcDesc.sizeInBytes)
{
@@ -658,7 +694,7 @@ Result DeviceImpl::createBufferResource(const IBufferResource::Desc& descIn, con
initData = initDataBuffer.getBuffer();
}
- D3D11_BUFFER_DESC bufferDesc = { 0 };
+ D3D11_BUFFER_DESC bufferDesc = {0};
bufferDesc.ByteWidth = UINT(alignedSizeInBytes);
bufferDesc.BindFlags = d3dBindFlags;
// For read we'll need to do some staging
@@ -681,17 +717,17 @@ Result DeviceImpl::createBufferResource(const IBufferResource::Desc& descIn, con
switch (descIn.defaultState)
{
case ResourceState::ConstantBuffer:
- {
- // We'll just assume ConstantBuffers are dynamic for now
- bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
- break;
- }
+ {
+ // We'll just assume ConstantBuffers are dynamic for now
+ bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
+ break;
+ }
default: break;
}
if (bufferDesc.BindFlags & (D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE))
{
- //desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE;
+ // desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE;
if (srcDesc.elementSize != 0)
{
bufferDesc.StructureByteStride = (UINT)srcDesc.elementSize;
@@ -708,12 +744,15 @@ Result DeviceImpl::createBufferResource(const IBufferResource::Desc& descIn, con
bufferDesc.CPUAccessFlags |= D3D11_CPU_ACCESS_WRITE;
}
- D3D11_SUBRESOURCE_DATA subResourceData = { 0 };
+ D3D11_SUBRESOURCE_DATA subResourceData = {0};
subResourceData.pSysMem = initData;
RefPtr<BufferResourceImpl> buffer(new BufferResourceImpl(srcDesc));
- SLANG_RETURN_ON_FAIL(m_device->CreateBuffer(&bufferDesc, initData ? &subResourceData : nullptr, buffer->m_buffer.writeRef()));
+ SLANG_RETURN_ON_FAIL(m_device->CreateBuffer(
+ &bufferDesc,
+ initData ? &subResourceData : nullptr,
+ buffer->m_buffer.writeRef()));
buffer->m_d3dUsage = bufferDesc.Usage;
if (srcDesc.memoryType == MemoryType::ReadBack || bufferDesc.Usage != D3D11_USAGE_DYNAMIC)
@@ -724,7 +763,8 @@ Result DeviceImpl::createBufferResource(const IBufferResource::Desc& descIn, con
bufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
bufDesc.Usage = D3D11_USAGE_STAGING;
- SLANG_RETURN_ON_FAIL(m_device->CreateBuffer(&bufDesc, nullptr, buffer->m_staging.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ m_device->CreateBuffer(&bufDesc, nullptr, buffer->m_staging.writeRef()));
}
returnComPtr(outResource, buffer);
return SLANG_OK;
@@ -761,9 +801,7 @@ Result DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerS
dxDesc.MaxLOD = desc.maxLOD;
ComPtr<ID3D11SamplerState> sampler;
- SLANG_RETURN_ON_FAIL(m_device->CreateSamplerState(
- &dxDesc,
- sampler.writeRef()));
+ SLANG_RETURN_ON_FAIL(m_device->CreateSamplerState(&dxDesc, sampler.writeRef()));
RefPtr<SamplerStateImpl> samplerImpl = new SamplerStateImpl();
samplerImpl->m_sampler = sampler;
@@ -771,85 +809,103 @@ Result DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerS
return SLANG_OK;
}
-Result DeviceImpl::createTextureView(ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView)
+Result DeviceImpl::createTextureView(
+ ITextureResource* texture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView)
{
auto resourceImpl = (TextureResourceImpl*)texture;
switch (desc.type)
{
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
case IResourceView::Type::RenderTarget:
- {
- ComPtr<ID3D11RenderTargetView> rtv;
- SLANG_RETURN_ON_FAIL(m_device->CreateRenderTargetView(resourceImpl->m_resource, nullptr, rtv.writeRef()));
-
- RefPtr<RenderTargetViewImpl> viewImpl = new RenderTargetViewImpl();
- viewImpl->m_type = ResourceViewImpl::Type::RTV;
- viewImpl->m_rtv = rtv;
- viewImpl->m_desc = desc;
- if (resourceImpl->getDesc()->optimalClearValue)
{
- memcpy(
- viewImpl->m_clearValue,
- &resourceImpl->getDesc()->optimalClearValue->color,
- sizeof(float) * 4);
+ ComPtr<ID3D11RenderTargetView> rtv;
+ SLANG_RETURN_ON_FAIL(m_device->CreateRenderTargetView(
+ resourceImpl->m_resource,
+ nullptr,
+ rtv.writeRef()));
+
+ RefPtr<RenderTargetViewImpl> viewImpl = new RenderTargetViewImpl();
+ viewImpl->m_type = ResourceViewImpl::Type::RTV;
+ viewImpl->m_rtv = rtv;
+ viewImpl->m_desc = desc;
+ if (resourceImpl->getDesc()->optimalClearValue)
+ {
+ memcpy(
+ viewImpl->m_clearValue,
+ &resourceImpl->getDesc()->optimalClearValue->color,
+ sizeof(float) * 4);
+ }
+ returnComPtr(outView, viewImpl);
+ return SLANG_OK;
}
- returnComPtr(outView, viewImpl);
- return SLANG_OK;
- }
- break;
+ break;
case IResourceView::Type::DepthStencil:
- {
- ComPtr<ID3D11DepthStencilView> dsv;
- SLANG_RETURN_ON_FAIL(m_device->CreateDepthStencilView(resourceImpl->m_resource, nullptr, dsv.writeRef()));
+ {
+ ComPtr<ID3D11DepthStencilView> dsv;
+ SLANG_RETURN_ON_FAIL(m_device->CreateDepthStencilView(
+ resourceImpl->m_resource,
+ nullptr,
+ dsv.writeRef()));
- RefPtr<DepthStencilViewImpl> viewImpl = new DepthStencilViewImpl();
- viewImpl->m_type = ResourceViewImpl::Type::DSV;
- viewImpl->m_dsv = dsv;
- if (resourceImpl->getDesc()->optimalClearValue)
- viewImpl->m_clearValue = resourceImpl->getDesc()->optimalClearValue->depthStencil;
- viewImpl->m_desc = desc;
+ RefPtr<DepthStencilViewImpl> viewImpl = new DepthStencilViewImpl();
+ viewImpl->m_type = ResourceViewImpl::Type::DSV;
+ viewImpl->m_dsv = dsv;
+ if (resourceImpl->getDesc()->optimalClearValue)
+ viewImpl->m_clearValue = resourceImpl->getDesc()->optimalClearValue->depthStencil;
+ viewImpl->m_desc = desc;
- returnComPtr(outView, viewImpl);
- return SLANG_OK;
- }
- break;
+ returnComPtr(outView, viewImpl);
+ return SLANG_OK;
+ }
+ break;
case IResourceView::Type::UnorderedAccess:
- {
- ComPtr<ID3D11UnorderedAccessView> uav;
- SLANG_RETURN_ON_FAIL(m_device->CreateUnorderedAccessView(resourceImpl->m_resource, nullptr, uav.writeRef()));
+ {
+ ComPtr<ID3D11UnorderedAccessView> uav;
+ SLANG_RETURN_ON_FAIL(m_device->CreateUnorderedAccessView(
+ resourceImpl->m_resource,
+ nullptr,
+ uav.writeRef()));
- RefPtr<UnorderedAccessViewImpl> viewImpl = new UnorderedAccessViewImpl();
- viewImpl->m_type = ResourceViewImpl::Type::UAV;
- viewImpl->m_uav = uav;
- viewImpl->m_desc = desc;
+ RefPtr<UnorderedAccessViewImpl> viewImpl = new UnorderedAccessViewImpl();
+ viewImpl->m_type = ResourceViewImpl::Type::UAV;
+ viewImpl->m_uav = uav;
+ viewImpl->m_desc = desc;
- returnComPtr(outView, viewImpl);
- return SLANG_OK;
- }
- break;
+ returnComPtr(outView, viewImpl);
+ return SLANG_OK;
+ }
+ break;
case IResourceView::Type::ShaderResource:
- {
- D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
- initSrvDesc(resourceImpl->getType(), *resourceImpl->getDesc(), D3DUtil::getMapFormat(desc.format), srvDesc);
-
- ComPtr<ID3D11ShaderResourceView> srv;
- SLANG_RETURN_ON_FAIL(m_device->CreateShaderResourceView(resourceImpl->m_resource, &srvDesc, srv.writeRef()));
-
- RefPtr<ShaderResourceViewImpl> viewImpl = new ShaderResourceViewImpl();
- viewImpl->m_type = ResourceViewImpl::Type::SRV;
- viewImpl->m_srv = srv;
- viewImpl->m_desc = desc;
-
- returnComPtr(outView, viewImpl);
- return SLANG_OK;
- }
- break;
+ {
+ D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
+ initSrvDesc(
+ resourceImpl->getType(),
+ *resourceImpl->getDesc(),
+ D3DUtil::getMapFormat(desc.format),
+ srvDesc);
+
+ ComPtr<ID3D11ShaderResourceView> srv;
+ SLANG_RETURN_ON_FAIL(m_device->CreateShaderResourceView(
+ resourceImpl->m_resource,
+ &srvDesc,
+ srv.writeRef()));
+
+ RefPtr<ShaderResourceViewImpl> viewImpl = new ShaderResourceViewImpl();
+ viewImpl->m_type = ResourceViewImpl::Type::SRV;
+ viewImpl->m_srv = srv;
+ viewImpl->m_desc = desc;
+
+ returnComPtr(outView, viewImpl);
+ return SLANG_OK;
+ }
+ break;
}
}
@@ -864,93 +920,104 @@ Result DeviceImpl::createBufferView(
switch (desc.type)
{
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
case IResourceView::Type::UnorderedAccess:
- {
- D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
- uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
- uavDesc.Format = D3DUtil::getMapFormat(desc.format);
- uavDesc.Buffer.FirstElement = 0;
-
- if (resourceDesc.elementSize)
{
- uavDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / resourceDesc.elementSize);
- }
- else if (desc.format == Format::Unknown)
- {
- uavDesc.Buffer.Flags |= D3D11_BUFFER_UAV_FLAG_RAW;
- uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
- uavDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / 4);
- }
- else
- {
- FormatInfo sizeInfo;
- gfxGetFormatInfo(desc.format, &sizeInfo);
- uavDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / (sizeInfo.blockSizeInBytes / sizeInfo.pixelsPerBlock));
- }
-
- ComPtr<ID3D11UnorderedAccessView> uav;
- SLANG_RETURN_ON_FAIL(m_device->CreateUnorderedAccessView(resourceImpl->m_buffer, &uavDesc, uav.writeRef()));
+ D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
+ uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
+ uavDesc.Format = D3DUtil::getMapFormat(desc.format);
+ uavDesc.Buffer.FirstElement = 0;
- RefPtr<UnorderedAccessViewImpl> viewImpl = new UnorderedAccessViewImpl();
- viewImpl->m_type = ResourceViewImpl::Type::UAV;
- viewImpl->m_uav = uav;
- viewImpl->m_desc = desc;
+ if (resourceDesc.elementSize)
+ {
+ uavDesc.Buffer.NumElements =
+ UINT(resourceDesc.sizeInBytes / resourceDesc.elementSize);
+ }
+ else if (desc.format == Format::Unknown)
+ {
+ uavDesc.Buffer.Flags |= D3D11_BUFFER_UAV_FLAG_RAW;
+ uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
+ uavDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / 4);
+ }
+ else
+ {
+ FormatInfo sizeInfo;
+ gfxGetFormatInfo(desc.format, &sizeInfo);
+ uavDesc.Buffer.NumElements = UINT(
+ resourceDesc.sizeInBytes /
+ (sizeInfo.blockSizeInBytes / sizeInfo.pixelsPerBlock));
+ }
- returnComPtr(outView, viewImpl);
- return SLANG_OK;
- }
- break;
+ ComPtr<ID3D11UnorderedAccessView> uav;
+ SLANG_RETURN_ON_FAIL(m_device->CreateUnorderedAccessView(
+ resourceImpl->m_buffer,
+ &uavDesc,
+ uav.writeRef()));
- case IResourceView::Type::ShaderResource:
- {
- D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
- srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
- srvDesc.Format = D3DUtil::getMapFormat(desc.format);
- srvDesc.Buffer.FirstElement = 0;
+ RefPtr<UnorderedAccessViewImpl> viewImpl = new UnorderedAccessViewImpl();
+ viewImpl->m_type = ResourceViewImpl::Type::UAV;
+ viewImpl->m_uav = uav;
+ viewImpl->m_desc = desc;
- if (resourceDesc.elementSize)
- {
- srvDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / resourceDesc.elementSize);
+ returnComPtr(outView, viewImpl);
+ return SLANG_OK;
}
- else if (desc.format == Format::Unknown)
- {
- // We need to switch to a different member of the `union`,
- // so that we can set the `BufferEx.Flags` member.
- //
- srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
-
- // Because we've switched, we need to re-set the `FirstElement`
- // field to be valid, since we can't count on all compilers
- // to respect that `Buffer.FirstElement` and `BufferEx.FirstElement`
- // alias in memory.
- //
- srvDesc.BufferEx.FirstElement = 0;
+ break;
- srvDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW;
- srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
- srvDesc.BufferEx.NumElements = UINT(resourceDesc.sizeInBytes / 4);
- }
- else
+ case IResourceView::Type::ShaderResource:
{
- FormatInfo sizeInfo;
- gfxGetFormatInfo(desc.format, &sizeInfo);
- srvDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / (sizeInfo.blockSizeInBytes / sizeInfo.pixelsPerBlock));
- }
+ D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
+ srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
+ srvDesc.Format = D3DUtil::getMapFormat(desc.format);
+ srvDesc.Buffer.FirstElement = 0;
- ComPtr<ID3D11ShaderResourceView> srv;
- SLANG_RETURN_ON_FAIL(m_device->CreateShaderResourceView(resourceImpl->m_buffer, &srvDesc, srv.writeRef()));
+ if (resourceDesc.elementSize)
+ {
+ srvDesc.Buffer.NumElements =
+ UINT(resourceDesc.sizeInBytes / resourceDesc.elementSize);
+ }
+ else if (desc.format == Format::Unknown)
+ {
+ // We need to switch to a different member of the `union`,
+ // so that we can set the `BufferEx.Flags` member.
+ //
+ srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
+
+ // Because we've switched, we need to re-set the `FirstElement`
+ // field to be valid, since we can't count on all compilers
+ // to respect that `Buffer.FirstElement` and `BufferEx.FirstElement`
+ // alias in memory.
+ //
+ srvDesc.BufferEx.FirstElement = 0;
+
+ srvDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW;
+ srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
+ srvDesc.BufferEx.NumElements = UINT(resourceDesc.sizeInBytes / 4);
+ }
+ else
+ {
+ FormatInfo sizeInfo;
+ gfxGetFormatInfo(desc.format, &sizeInfo);
+ srvDesc.Buffer.NumElements = UINT(
+ resourceDesc.sizeInBytes /
+ (sizeInfo.blockSizeInBytes / sizeInfo.pixelsPerBlock));
+ }
- RefPtr<ShaderResourceViewImpl> viewImpl = new ShaderResourceViewImpl();
- viewImpl->m_type = ResourceViewImpl::Type::SRV;
- viewImpl->m_srv = srv;
- viewImpl->m_desc = desc;
- returnComPtr(outView, viewImpl);
- return SLANG_OK;
- }
- break;
+ ComPtr<ID3D11ShaderResourceView> srv;
+ SLANG_RETURN_ON_FAIL(m_device->CreateShaderResourceView(
+ resourceImpl->m_buffer,
+ &srvDesc,
+ srv.writeRef()));
+
+ RefPtr<ShaderResourceViewImpl> viewImpl = new ShaderResourceViewImpl();
+ viewImpl->m_type = ResourceViewImpl::Type::SRV;
+ viewImpl->m_srv = srv;
+ viewImpl->m_desc = desc;
+ returnComPtr(outView, viewImpl);
+ return SLANG_OK;
+ }
+ break;
}
}
@@ -975,8 +1042,9 @@ Result DeviceImpl::createInputLayout(IInputLayout::Desc const& desc, IInputLayou
inputElements[ii].Format = D3DUtil::getMapFormat(inputElementsIn[ii].format);
inputElements[ii].InputSlot = (UINT)vertexStreamIndex;
inputElements[ii].AlignedByteOffset = (UINT)inputElementsIn[ii].offset;
- inputElements[ii].InputSlotClass =
- (vertexStream.slotClass == InputSlotClass::PerInstance) ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA;
+ inputElements[ii].InputSlotClass = (vertexStream.slotClass == InputSlotClass::PerInstance)
+ ? D3D11_INPUT_PER_INSTANCE_DATA
+ : D3D11_INPUT_PER_VERTEX_DATA;
inputElements[ii].InstanceDataStepRate = (UINT)vertexStream.instanceDataStepRate;
if (ii != 0)
@@ -988,23 +1056,16 @@ Result DeviceImpl::createInputLayout(IInputLayout::Desc const& desc, IInputLayou
switch (inputElementsIn[ii].format)
{
case Format::R32G32B32A32_FLOAT:
- case Format::R8G8B8A8_UNORM:
- typeName = "float4";
- break;
- case Format::R32G32B32_FLOAT:
- typeName = "float3";
- break;
- case Format::R32G32_FLOAT:
- typeName = "float2";
- break;
- case Format::R32_FLOAT:
- typeName = "float";
- break;
- default:
- return SLANG_FAIL;
+ case Format::R8G8B8A8_UNORM: typeName = "float4"; break;
+ case Format::R32G32B32_FLOAT: typeName = "float3"; break;
+ case Format::R32G32_FLOAT: typeName = "float2"; break;
+ case Format::R32_FLOAT: typeName = "float"; break;
+ default: return SLANG_FAIL;
}
- hlslCursor += sprintf(hlslCursor, "%s a%d : %s%d",
+ hlslCursor += sprintf(
+ hlslCursor,
+ "%s a%d : %s%d",
typeName,
(int)ii,
inputElementsIn[ii].semanticName,
@@ -1014,10 +1075,15 @@ Result DeviceImpl::createInputLayout(IInputLayout::Desc const& desc, IInputLayou
hlslCursor += sprintf(hlslCursor, "\n) : SV_Position { return 0; }");
ComPtr<ID3DBlob> vertexShaderBlob;
- SLANG_RETURN_ON_FAIL(D3DUtil::compileHLSLShader("inputLayout", hlslBuffer, "main", "vs_5_0", vertexShaderBlob));
+ SLANG_RETURN_ON_FAIL(
+ D3DUtil::compileHLSLShader("inputLayout", hlslBuffer, "main", "vs_5_0", vertexShaderBlob));
ComPtr<ID3D11InputLayout> inputLayout;
- SLANG_RETURN_ON_FAIL(m_device->CreateInputLayout(&inputElements[0], (UINT)inputElementCount, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(),
+ SLANG_RETURN_ON_FAIL(m_device->CreateInputLayout(
+ &inputElements[0],
+ (UINT)inputElementCount,
+ vertexShaderBlob->GetBufferPointer(),
+ vertexShaderBlob->GetBufferSize(),
inputLayout.writeRef()));
RefPtr<InputLayoutImpl> impl = new InputLayoutImpl;
@@ -1051,17 +1117,10 @@ void* DeviceImpl::map(IBufferResource* bufferIn, MapFlavor flavor)
switch (flavor)
{
- case MapFlavor::WriteDiscard:
- mapType = D3D11_MAP_WRITE_DISCARD;
- break;
- case MapFlavor::HostWrite:
- mapType = D3D11_MAP_WRITE_NO_OVERWRITE;
- break;
- case MapFlavor::HostRead:
- mapType = D3D11_MAP_READ;
- break;
- default:
- return nullptr;
+ case MapFlavor::WriteDiscard: mapType = D3D11_MAP_WRITE_DISCARD; break;
+ case MapFlavor::HostWrite: mapType = D3D11_MAP_WRITE_NO_OVERWRITE; break;
+ case MapFlavor::HostRead: mapType = D3D11_MAP_READ; break;
+ default: return nullptr;
}
bufferResource->m_mapFlavor = flavor;
@@ -1086,7 +1145,6 @@ void* DeviceImpl::map(IBufferResource* bufferIn, MapFlavor flavor)
// Okay copy the data over
m_immediateContext->CopyResource(buffer, bufferResource->m_buffer);
-
}
// We update our constant buffer per-frame, just for the purposes
@@ -1124,7 +1182,10 @@ void DeviceImpl::unmap(IBufferResource* bufferIn, size_t offsetWritten, size_t s
return;
}
}
- m_immediateContext->Unmap(bufferResource->m_mapFlavor == MapFlavor::HostRead ? bufferResource->m_staging : bufferResource->m_buffer, 0);
+ m_immediateContext->Unmap(
+ bufferResource->m_mapFlavor == MapFlavor::HostRead ? bufferResource->m_staging
+ : bufferResource->m_buffer,
+ 0);
}
#if 0
@@ -1148,7 +1209,8 @@ void DeviceImpl::setVertexBuffers(
{
static const int kMaxVertexBuffers = 16;
assert(slotCount <= kMaxVertexBuffers);
- assert(m_currentPipelineState); // The pipeline state should be created before setting vertex buffers.
+ assert(m_currentPipelineState); // The pipeline state should be created before setting vertex
+ // buffers.
UINT vertexStrides[kMaxVertexBuffers];
UINT vertexOffsets[kMaxVertexBuffers];
@@ -1164,13 +1226,21 @@ void DeviceImpl::setVertexBuffers(
dxBuffers[ii] = buffers[ii]->m_buffer;
}
- m_immediateContext->IASetVertexBuffers((UINT)startSlot, (UINT)slotCount, dxBuffers, &vertexStrides[0], &vertexOffsets[0]);
+ m_immediateContext->IASetVertexBuffers(
+ (UINT)startSlot,
+ (UINT)slotCount,
+ dxBuffers,
+ &vertexStrides[0],
+ &vertexOffsets[0]);
}
void DeviceImpl::setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset)
{
DXGI_FORMAT dxFormat = D3DUtil::getMapFormat(indexFormat);
- m_immediateContext->IASetIndexBuffer(((BufferResourceImpl*)buffer)->m_buffer, dxFormat, UINT(offset));
+ m_immediateContext->IASetIndexBuffer(
+ ((BufferResourceImpl*)buffer)->m_buffer,
+ dxFormat,
+ UINT(offset));
}
void DeviceImpl::setViewports(GfxCount count, Viewport const* viewports)
@@ -1222,66 +1292,69 @@ void DeviceImpl::setPipelineState(IPipelineState* state)
switch (pipelineType)
{
- default:
- break;
+ default: break;
case PipelineType::Graphics:
- {
- auto stateImpl = (GraphicsPipelineStateImpl*)state;
- auto programImpl = static_cast<ShaderProgramImpl*>(stateImpl->m_program.Ptr());
+ {
+ auto stateImpl = (GraphicsPipelineStateImpl*)state;
+ auto programImpl = static_cast<ShaderProgramImpl*>(stateImpl->m_program.Ptr());
- // TODO: We could conceivably do some lightweight state
- // differencing here (e.g., check if `programImpl` is the
- // same as the program that is currently bound).
- //
- // It isn't clear how much that would pay off given that
- // the D3D11 runtime seems to do its own state diffing.
+ // TODO: We could conceivably do some lightweight state
+ // differencing here (e.g., check if `programImpl` is the
+ // same as the program that is currently bound).
+ //
+ // It isn't clear how much that would pay off given that
+ // the D3D11 runtime seems to do its own state diffing.
- // IA
+ // IA
- m_immediateContext->IASetInputLayout(stateImpl->m_inputLayout->m_layout);
+ m_immediateContext->IASetInputLayout(stateImpl->m_inputLayout->m_layout);
- // VS
+ // VS
- // TODO(tfoley): Why the conditional here? If somebody is trying to disable the VS or PS, shouldn't we respect that?
- if (programImpl->m_vertexShader)
- m_immediateContext->VSSetShader(programImpl->m_vertexShader, nullptr, 0);
+ // TODO(tfoley): Why the conditional here? If somebody is trying to disable the VS or
+ // PS, shouldn't we respect that?
+ if (programImpl->m_vertexShader)
+ m_immediateContext->VSSetShader(programImpl->m_vertexShader, nullptr, 0);
- // HS
+ // HS
- // DS
+ // DS
- // GS
+ // GS
- // RS
+ // RS
- m_immediateContext->RSSetState(stateImpl->m_rasterizerState);
+ m_immediateContext->RSSetState(stateImpl->m_rasterizerState);
- // PS
- if (programImpl->m_pixelShader)
- m_immediateContext->PSSetShader(programImpl->m_pixelShader, nullptr, 0);
+ // PS
+ if (programImpl->m_pixelShader)
+ m_immediateContext->PSSetShader(programImpl->m_pixelShader, nullptr, 0);
- // OM
+ // OM
- m_immediateContext->OMSetBlendState(stateImpl->m_blendState, stateImpl->m_blendColor, stateImpl->m_sampleMask);
+ m_immediateContext->OMSetBlendState(
+ stateImpl->m_blendState,
+ stateImpl->m_blendColor,
+ stateImpl->m_sampleMask);
- m_currentPipelineState = stateImpl;
+ m_currentPipelineState = stateImpl;
- m_depthStencilStateDirty = true;
- }
- break;
+ m_depthStencilStateDirty = true;
+ }
+ break;
case PipelineType::Compute:
- {
- auto stateImpl = (ComputePipelineStateImpl*)state;
- auto programImpl = static_cast<ShaderProgramImpl*>(stateImpl->m_program.Ptr());
+ {
+ auto stateImpl = (ComputePipelineStateImpl*)state;
+ auto programImpl = static_cast<ShaderProgramImpl*>(stateImpl->m_program.Ptr());
- // CS
+ // CS
- m_immediateContext->CSSetShader(programImpl->m_computeShader, nullptr, 0);
- m_currentPipelineState = stateImpl;
- }
- break;
+ m_immediateContext->CSSetShader(programImpl->m_computeShader, nullptr, 0);
+ m_currentPipelineState = stateImpl;
+ }
+ break;
}
/// ...
@@ -1306,11 +1379,8 @@ void DeviceImpl::drawInstanced(
GfxIndex startInstanceLocation)
{
_flushGraphicsState();
- m_immediateContext->DrawInstanced(
- vertexCount,
- instanceCount,
- startVertex,
- startInstanceLocation);
+ m_immediateContext
+ ->DrawInstanced(vertexCount, instanceCount, startVertex, startInstanceLocation);
}
void DeviceImpl::drawIndexedInstanced(
@@ -1330,7 +1400,9 @@ void DeviceImpl::drawIndexedInstanced(
}
Result DeviceImpl::createProgram(
- const IShaderProgram::Desc& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnosticBlob)
+ const IShaderProgram::Desc& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnosticBlob)
{
SLANG_ASSERT(desc.slangGlobalScope);
@@ -1363,8 +1435,12 @@ Result DeviceImpl::createProgram(
ComPtr<ISlangBlob> kernelCode;
ComPtr<ISlangBlob> diagnostics;
- auto compileResult = getEntryPointCodeFromShaderCache(slangGlobalScope,
- (SlangInt)i, 0, kernelCode.writeRef(), diagnostics.writeRef());
+ auto compileResult = getEntryPointCodeFromShaderCache(
+ slangGlobalScope,
+ (SlangInt)i,
+ 0,
+ kernelCode.writeRef(),
+ diagnostics.writeRef());
if (diagnostics)
{
@@ -1406,8 +1482,7 @@ Result DeviceImpl::createProgram(
nullptr,
shaderProgram->m_pixelShader.writeRef()));
break;
- default:
- SLANG_ASSERT(!"pipeline stage not implemented");
+ default: SLANG_ASSERT(!"pipeline stage not implemented");
}
}
returnComPtr(outProgram, shaderProgram);
@@ -1420,8 +1495,8 @@ Result DeviceImpl::createShaderObjectLayout(
ShaderObjectLayoutBase** outLayout)
{
RefPtr<ShaderObjectLayoutImpl> layout;
- SLANG_RETURN_ON_FAIL(ShaderObjectLayoutImpl::createForElementType(
- this, session, typeLayout, layout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ ShaderObjectLayoutImpl::createForElementType(this, session, typeLayout, layout.writeRef()));
returnRefPtrMove(outLayout, layout);
return SLANG_OK;
}
@@ -1429,8 +1504,10 @@ Result DeviceImpl::createShaderObjectLayout(
Result DeviceImpl::createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
{
RefPtr<ShaderObjectImpl> shaderObject;
- SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(this,
- static_cast<ShaderObjectLayoutImpl*>(layout), shaderObject.writeRef()));
+ SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(
+ this,
+ static_cast<ShaderObjectLayoutImpl*>(layout),
+ shaderObject.writeRef()));
returnComPtr(outObject, shaderObject);
return SLANG_OK;
}
@@ -1454,9 +1531,12 @@ Result DeviceImpl::createRootShaderObject(IShaderProgram* program, ShaderObjectB
RefPtr<RootShaderObjectImpl> shaderObject;
RefPtr<RootShaderObjectLayoutImpl> rootLayout;
SLANG_RETURN_ON_FAIL(RootShaderObjectLayoutImpl::create(
- this, programImpl->slangGlobalScope, programImpl->slangGlobalScope->getLayout(), rootLayout.writeRef()));
- SLANG_RETURN_ON_FAIL(RootShaderObjectImpl::create(
- this, rootLayout.Ptr(), shaderObject.writeRef()));
+ this,
+ programImpl->slangGlobalScope,
+ programImpl->slangGlobalScope->getLayout(),
+ rootLayout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ RootShaderObjectImpl::create(this, rootLayout.Ptr(), shaderObject.writeRef()));
returnRefPtrMove(outObject, shaderObject);
return SLANG_OK;
}
@@ -1466,9 +1546,11 @@ void DeviceImpl::bindRootShaderObject(IShaderObject* shaderObject)
RootShaderObjectImpl* rootShaderObjectImpl = static_cast<RootShaderObjectImpl*>(shaderObject);
RefPtr<PipelineStateBase> specializedPipeline;
// TODO: Do something less crappy than just asserting on failure here
- SLANG_ASSERT_VOID_ON_FAIL(maybeSpecializePipeline(m_currentPipelineState, rootShaderObjectImpl, specializedPipeline));
+ SLANG_ASSERT_VOID_ON_FAIL(
+ maybeSpecializePipeline(m_currentPipelineState, rootShaderObjectImpl, specializedPipeline));
maybeSpecializePipeline(m_currentPipelineState, rootShaderObjectImpl, specializedPipeline);
- PipelineStateImpl* specializedPipelineImpl = static_cast<PipelineStateImpl*>(specializedPipeline.Ptr());
+ PipelineStateImpl* specializedPipelineImpl =
+ static_cast<PipelineStateImpl*>(specializedPipeline.Ptr());
setPipelineState(specializedPipelineImpl);
// In order to bind the root object we must compute its specialized layout.
@@ -1478,7 +1560,8 @@ void DeviceImpl::bindRootShaderObject(IShaderObject* shaderObject)
//
RefPtr<ShaderObjectLayoutImpl> specializedRootLayout;
rootShaderObjectImpl->_getSpecializedLayout(specializedRootLayout.writeRef());
- RootShaderObjectLayoutImpl* specializedRootLayoutImpl = static_cast<RootShaderObjectLayoutImpl*>(specializedRootLayout.Ptr());
+ RootShaderObjectLayoutImpl* specializedRootLayoutImpl =
+ static_cast<RootShaderObjectLayoutImpl*>(specializedRootLayout.Ptr());
// Depending on whether we are binding a compute or a graphics/rasterization
// pipeline, we will need to bind any SRVs/UAVs/CBs/samplers using different
@@ -1488,76 +1571,79 @@ void DeviceImpl::bindRootShaderObject(IShaderObject* shaderObject)
switch (m_currentPipelineState->desc.type)
{
case PipelineType::Compute:
- {
- ComputeBindingContext context(this, m_immediateContext);
- rootShaderObjectImpl->bindAsRoot(&context, specializedRootLayoutImpl);
-
- // Because D3D11 requires all UAVs to be set at once, we did *not* issue
- // actual binding calls during the `bindAsRoot` step, and instead we
- // batch them up and set them here.
- //
- m_immediateContext->CSSetUnorderedAccessViews(0, context.uavCount, context.uavs, nullptr);
- }
- break;
+ {
+ ComputeBindingContext context(this, m_immediateContext);
+ rootShaderObjectImpl->bindAsRoot(&context, specializedRootLayoutImpl);
+
+ // Because D3D11 requires all UAVs to be set at once, we did *not* issue
+ // actual binding calls during the `bindAsRoot` step, and instead we
+ // batch them up and set them here.
+ //
+ m_immediateContext
+ ->CSSetUnorderedAccessViews(0, context.uavCount, context.uavs, nullptr);
+ }
+ break;
default:
- {
- GraphicsBindingContext context(this, m_immediateContext);
- rootShaderObjectImpl->bindAsRoot(&context, specializedRootLayoutImpl);
-
- // Similar to the compute case above, the rasteirzation case needs to
- // set the UAVs after the call to `bindAsRoot()` completes, but we
- // also have a few extra wrinkles here that are specific to the D3D 11.0
- // rasterization pipeline.
- //
- // In D3D 11.0, the RTV and UAV binding slots alias, so that a shader
- // that binds an RTV for `SV_Target0` cannot also bind a UAV for `u0`.
- // The Slang layout algorithm already accounts for this rule, and assigns
- // all UAVs to slots taht won't alias the RTVs it knows about.
- //
- // In order to account for the aliasing, we need to consider how many
- // RTVs are bound as part of the active framebuffer, and then adjust
- // the UAVs that we bind accordingly.
- //
- auto rtvCount = (UINT)m_currentFramebuffer->renderTargetViews.getCount();
- //
- // The `context` we are using will have computed the number of UAV registers
- // that might need to be bound, as a range from 0 to `context.uavCount`.
- // However we need to skip over the first `rtvCount` of those, so the
- // actual number of UAVs we wnat to bind is smaller:
- //
- // Note: As a result we expect that either there were no UAVs bound,
- // *or* the number of UAV slots bound is higher than the number of
- // RTVs so that there is something left to actually bind.
- //
- SLANG_ASSERT((context.uavCount == 0) || (context.uavCount >= rtvCount));
- auto bindableUAVCount = context.uavCount - rtvCount;
- //
- // Similarly, the actual UAVs we intend to bind will come after the first
- // `rtvCount` in the array.
- //
- auto bindableUAVs = context.uavs + rtvCount;
-
- // Once the offsetting is accounted for, we set all of the RTVs, DSV,
- // and UAVs with one call.
- //
- // TODO: We may want to use the capability for `OMSetRenderTargetsAnd...`
- // to only set the UAVs and leave the RTVs/UAVs alone, so that we don't
- // needlessly re-bind RTVs during a pass.
- //
- m_immediateContext->OMSetRenderTargetsAndUnorderedAccessViews(
- rtvCount,
- m_currentFramebuffer->d3dRenderTargetViews.getArrayView().getBuffer(),
- m_currentFramebuffer->d3dDepthStencilView,
- rtvCount,
- bindableUAVCount,
- bindableUAVs,
- nullptr);
- }
- break;
+ {
+ GraphicsBindingContext context(this, m_immediateContext);
+ rootShaderObjectImpl->bindAsRoot(&context, specializedRootLayoutImpl);
+
+ // Similar to the compute case above, the rasteirzation case needs to
+ // set the UAVs after the call to `bindAsRoot()` completes, but we
+ // also have a few extra wrinkles here that are specific to the D3D 11.0
+ // rasterization pipeline.
+ //
+ // In D3D 11.0, the RTV and UAV binding slots alias, so that a shader
+ // that binds an RTV for `SV_Target0` cannot also bind a UAV for `u0`.
+ // The Slang layout algorithm already accounts for this rule, and assigns
+ // all UAVs to slots taht won't alias the RTVs it knows about.
+ //
+ // In order to account for the aliasing, we need to consider how many
+ // RTVs are bound as part of the active framebuffer, and then adjust
+ // the UAVs that we bind accordingly.
+ //
+ auto rtvCount = (UINT)m_currentFramebuffer->renderTargetViews.getCount();
+ //
+ // The `context` we are using will have computed the number of UAV registers
+ // that might need to be bound, as a range from 0 to `context.uavCount`.
+ // However we need to skip over the first `rtvCount` of those, so the
+ // actual number of UAVs we wnat to bind is smaller:
+ //
+ // Note: As a result we expect that either there were no UAVs bound,
+ // *or* the number of UAV slots bound is higher than the number of
+ // RTVs so that there is something left to actually bind.
+ //
+ SLANG_ASSERT((context.uavCount == 0) || (context.uavCount >= rtvCount));
+ auto bindableUAVCount = context.uavCount - rtvCount;
+ //
+ // Similarly, the actual UAVs we intend to bind will come after the first
+ // `rtvCount` in the array.
+ //
+ auto bindableUAVs = context.uavs + rtvCount;
+
+ // Once the offsetting is accounted for, we set all of the RTVs, DSV,
+ // and UAVs with one call.
+ //
+ // TODO: We may want to use the capability for `OMSetRenderTargetsAnd...`
+ // to only set the UAVs and leave the RTVs/UAVs alone, so that we don't
+ // needlessly re-bind RTVs during a pass.
+ //
+ m_immediateContext->OMSetRenderTargetsAndUnorderedAccessViews(
+ rtvCount,
+ m_currentFramebuffer->d3dRenderTargetViews.getArrayView().getBuffer(),
+ m_currentFramebuffer->d3dDepthStencilView,
+ rtvCount,
+ bindableUAVCount,
+ bindableUAVs,
+ nullptr);
+ }
+ break;
}
}
-Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc& inDesc, IPipelineState** outState)
+Result DeviceImpl::createGraphicsPipelineState(
+ const GraphicsPipelineStateDesc& inDesc,
+ IPipelineState** outState)
{
GraphicsPipelineStateDesc desc = inDesc;
@@ -1567,25 +1653,25 @@ Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc&
{
D3D11_DEPTH_STENCIL_DESC dsDesc;
dsDesc.DepthEnable = desc.depthStencil.depthTestEnable;
- dsDesc.DepthWriteMask = desc.depthStencil.depthWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
+ dsDesc.DepthWriteMask = desc.depthStencil.depthWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL
+ : D3D11_DEPTH_WRITE_MASK_ZERO;
dsDesc.DepthFunc = translateComparisonFunc(desc.depthStencil.depthFunc);
dsDesc.StencilEnable = desc.depthStencil.stencilEnable;
dsDesc.StencilReadMask = desc.depthStencil.stencilReadMask;
dsDesc.StencilWriteMask = desc.depthStencil.stencilWriteMask;
-#define FACE(DST, SRC) \
- dsDesc.DST.StencilFailOp = translateStencilOp( desc.depthStencil.SRC.stencilFailOp); \
- dsDesc.DST.StencilDepthFailOp = translateStencilOp( desc.depthStencil.SRC.stencilDepthFailOp); \
- dsDesc.DST.StencilPassOp = translateStencilOp( desc.depthStencil.SRC.stencilPassOp); \
- dsDesc.DST.StencilFunc = translateComparisonFunc(desc.depthStencil.SRC.stencilFunc); \
+#define FACE(DST, SRC) \
+ dsDesc.DST.StencilFailOp = translateStencilOp(desc.depthStencil.SRC.stencilFailOp); \
+ dsDesc.DST.StencilDepthFailOp = translateStencilOp(desc.depthStencil.SRC.stencilDepthFailOp); \
+ dsDesc.DST.StencilPassOp = translateStencilOp(desc.depthStencil.SRC.stencilPassOp); \
+ dsDesc.DST.StencilFunc = translateComparisonFunc(desc.depthStencil.SRC.stencilFunc); \
/* end */
FACE(FrontFace, frontFace);
FACE(BackFace, backFace);
- SLANG_RETURN_ON_FAIL(m_device->CreateDepthStencilState(
- &dsDesc,
- depthStencilState.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ m_device->CreateDepthStencilState(&dsDesc, depthStencilState.writeRef()));
}
ComPtr<ID3D11RasterizerState> rasterizerState;
@@ -1602,10 +1688,7 @@ Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc&
rsDesc.MultisampleEnable = desc.rasterizer.multisampleEnable;
rsDesc.AntialiasedLineEnable = desc.rasterizer.antialiasedLineEnable;
- SLANG_RETURN_ON_FAIL(m_device->CreateRasterizerState(
- &rsDesc,
- rasterizerState.writeRef()));
-
+ SLANG_RETURN_ON_FAIL(m_device->CreateRasterizerState(&rsDesc, rasterizerState.writeRef()));
}
ComPtr<ID3D11BlendState> blendState;
@@ -1616,7 +1699,8 @@ Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc&
TargetBlendDesc defaultTargetBlendDesc;
static const UInt kMaxTargets = D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT;
- if (srcDesc.targetCount > kMaxTargets) return SLANG_FAIL;
+ if (srcDesc.targetCount > kMaxTargets)
+ return SLANG_FAIL;
for (GfxIndex ii = 0; ii < kMaxTargets; ++ii)
{
@@ -1652,21 +1736,24 @@ Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc&
dstTargetBlendDesc.BlendEnable = true;
dstTargetBlendDesc.BlendOp = translateBlendOp(srcTargetBlendDesc.color.op);
dstTargetBlendDesc.BlendOpAlpha = translateBlendOp(srcTargetBlendDesc.alpha.op);
- dstTargetBlendDesc.SrcBlend = translateBlendFactor(srcTargetBlendDesc.color.srcFactor);
- dstTargetBlendDesc.SrcBlendAlpha = translateBlendFactor(srcTargetBlendDesc.alpha.srcFactor);
- dstTargetBlendDesc.DestBlend = translateBlendFactor(srcTargetBlendDesc.color.dstFactor);
- dstTargetBlendDesc.DestBlendAlpha = translateBlendFactor(srcTargetBlendDesc.alpha.dstFactor);
+ dstTargetBlendDesc.SrcBlend =
+ translateBlendFactor(srcTargetBlendDesc.color.srcFactor);
+ dstTargetBlendDesc.SrcBlendAlpha =
+ translateBlendFactor(srcTargetBlendDesc.alpha.srcFactor);
+ dstTargetBlendDesc.DestBlend =
+ translateBlendFactor(srcTargetBlendDesc.color.dstFactor);
+ dstTargetBlendDesc.DestBlendAlpha =
+ translateBlendFactor(srcTargetBlendDesc.alpha.dstFactor);
}
- dstTargetBlendDesc.RenderTargetWriteMask = translateRenderTargetWriteMask(srcTargetBlendDesc.writeMask);
+ dstTargetBlendDesc.RenderTargetWriteMask =
+ translateRenderTargetWriteMask(srcTargetBlendDesc.writeMask);
}
dstDesc.IndependentBlendEnable = srcDesc.targetCount > 1;
dstDesc.AlphaToCoverageEnable = srcDesc.alphaToCoverageEnable;
- SLANG_RETURN_ON_FAIL(m_device->CreateBlendState(
- &dstDesc,
- blendState.writeRef()));
+ SLANG_RETURN_ON_FAIL(m_device->CreateBlendState(&dstDesc, blendState.writeRef()));
}
RefPtr<GraphicsPipelineStateImpl> state = new GraphicsPipelineStateImpl();
@@ -1675,7 +1762,7 @@ Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc&
state->m_blendState = blendState;
state->m_inputLayout = static_cast<InputLayoutImpl*>(desc.inputLayout);
state->m_rtvCount = (UINT) static_cast<FramebufferLayoutImpl*>(desc.framebufferLayout)
- ->m_renderTargets.getCount();
+ ->m_renderTargets.getCount();
state->m_blendColor[0] = 0;
state->m_blendColor[1] = 0;
state->m_blendColor[2] = 0;
@@ -1686,7 +1773,9 @@ Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc&
return SLANG_OK;
}
-Result DeviceImpl::createComputePipelineState(const ComputePipelineStateDesc& inDesc, IPipelineState** outState)
+Result DeviceImpl::createComputePipelineState(
+ const ComputePipelineStateDesc& inDesc,
+ IPipelineState** outState)
{
ComputePipelineStateDesc desc = inDesc;
@@ -1710,7 +1799,14 @@ void DeviceImpl::copyBuffer(
srcBox.right = (UINT)(srcOffset + size);
srcBox.bottom = srcBox.back = 1;
m_immediateContext->CopySubresourceRegion(
- dstImpl->m_buffer, 0, (UINT)dstOffset, 0, 0, srcImpl->m_buffer, 0, &srcBox);
+ dstImpl->m_buffer,
+ 0,
+ (UINT)dstOffset,
+ 0,
+ 0,
+ srcImpl->m_buffer,
+ 0,
+ &srcBox);
}
void DeviceImpl::dispatchCompute(int x, int y, int z)
@@ -1725,7 +1821,8 @@ void DeviceImpl::_flushGraphicsState()
m_depthStencilStateDirty = false;
auto pipelineState = static_cast<GraphicsPipelineStateImpl*>(m_currentPipelineState.Ptr());
m_immediateContext->OMSetDepthStencilState(
- pipelineState->m_depthStencilState, m_stencilRef);
+ pipelineState->m_depthStencilState,
+ m_stencilRef);
}
}
diff --git a/tools/gfx/d3d11/d3d11-device.h b/tools/gfx/d3d11/d3d11-device.h
index 42fffa3c9..0f79e82a5 100644
--- a/tools/gfx/d3d11/d3d11-device.h
+++ b/tools/gfx/d3d11/d3d11-device.h
@@ -14,18 +14,20 @@ namespace d3d11
class DeviceImpl : public ImmediateRendererBase
{
public:
-
~DeviceImpl() {}
// Renderer implementation
virtual SLANG_NO_THROW Result SLANG_MCALL initialize(const Desc& desc) override;
virtual void clearFrame(uint32_t colorBufferMask, bool clearDepth, bool clearStencil) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain) override;
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout) override;
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
+ createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
virtual void setFramebuffer(IFramebuffer* frameBuffer) override;
virtual void setStencilReference(uint32_t referenceValue) override;
@@ -38,7 +40,7 @@ public:
const void* initData,
IBufferResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
+ createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
ITextureResource* texture,
@@ -51,12 +53,11 @@ public:
IResourceView::Desc const& desc,
IResourceView** outView) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL createInputLayout(
- IInputLayout::Desc const& desc,
- IInputLayout** outLayout) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL createQueryPool(
- const IQueryPool::Desc& desc, IQueryPool** outPool) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool) override;
virtual Result createShaderObjectLayout(
slang::ISession* session,
@@ -64,7 +65,9 @@ public:
ShaderObjectLayoutBase** outLayout) override;
virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
override;
- virtual Result createMutableShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
+ virtual Result createMutableShaderObject(
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject) override;
virtual Result createRootShaderObject(IShaderProgram* program, ShaderObjectBase** outObject)
override;
virtual void bindRootShaderObject(IShaderObject* shaderObject) override;
@@ -74,9 +77,11 @@ public:
IShaderProgram** outProgram,
ISlangBlob** outDiagnosticBlob) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& desc, IPipelineState** outState) override;
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState) override;
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual void* map(IBufferResource* buffer, MapFlavor flavor) override;
virtual void unmap(IBufferResource* buffer, size_t offsetWritten, size_t sizeWritten) override;
@@ -87,7 +92,11 @@ public:
size_t srcOffset,
size_t size) override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL readTextureResource(
- ITextureResource* texture, ResourceState state, ISlangBlob** outBlob, size_t* outRowPitch, size_t* outPixelSize) override;
+ ITextureResource* texture,
+ ResourceState state,
+ ISlangBlob** outBlob,
+ size_t* outRowPitch,
+ size_t* outPixelSize) override;
virtual void setPrimitiveTopology(PrimitiveTopology topology) override;
@@ -96,14 +105,14 @@ public:
GfxCount slotCount,
IBufferResource* const* buffers,
const Offset* offsets) override;
- virtual void setIndexBuffer(
- IBufferResource* buffer, Format indexFormat, Offset offset) override;
+ virtual void setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset)
+ override;
virtual void setViewports(GfxCount count, Viewport const* viewports) override;
virtual void setScissorRects(GfxCount count, ScissorRect const* rects) override;
virtual void setPipelineState(IPipelineState* state) override;
virtual void draw(GfxCount vertexCount, GfxIndex startVertex) override;
- virtual void drawIndexed(
- GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex) override;
+ virtual void drawIndexed(GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex)
+ override;
virtual void drawInstanced(
GfxCount vertexCount,
GfxCount instanceCount,
@@ -117,10 +126,7 @@ public:
GfxIndex startInstanceLocation) override;
virtual void dispatchCompute(int x, int y, int z) override;
virtual void submitGpuWork() override {}
- virtual void waitForGpu() override
- {
-
- }
+ virtual void waitForGpu() override {}
virtual SLANG_NO_THROW const DeviceInfo& SLANG_MCALL getDeviceInfo() const override
{
return m_info;
@@ -153,7 +159,7 @@ public:
Desc m_desc;
- float m_clearColor[4] = { 0, 0, 0, 0 };
+ float m_clearColor[4] = {0, 0, 0, 0};
bool m_nvapi = false;
};
diff --git a/tools/gfx/d3d11/d3d11-helper-functions.cpp b/tools/gfx/d3d11/d3d11-helper-functions.cpp
index 6774b7d93..76b339880 100644
--- a/tools/gfx/d3d11/d3d11-helper-functions.cpp
+++ b/tools/gfx/d3d11/d3d11-helper-functions.cpp
@@ -10,345 +10,346 @@ using namespace Slang;
namespace d3d11
{
- bool isSupportedNVAPIOp(IUnknown* dev, uint32_t op)
- {
+bool isSupportedNVAPIOp(IUnknown* dev, uint32_t op)
+{
#ifdef GFX_NVAPI
- {
- bool isSupported;
- NvAPI_Status status = NvAPI_D3D11_IsNvShaderExtnOpCodeSupported(dev, NvU32(op), &isSupported);
- return status == NVAPI_OK && isSupported;
- }
+ {
+ bool isSupported;
+ NvAPI_Status status =
+ NvAPI_D3D11_IsNvShaderExtnOpCodeSupported(dev, NvU32(op), &isSupported);
+ return status == NVAPI_OK && isSupported;
+ }
#else
- return false;
+ return false;
#endif
- }
+}
- D3D11_BIND_FLAG calcResourceFlag(ResourceState state)
+D3D11_BIND_FLAG calcResourceFlag(ResourceState state)
+{
+ switch (state)
{
- switch (state)
- {
- case ResourceState::VertexBuffer:
- return D3D11_BIND_VERTEX_BUFFER;
- case ResourceState::IndexBuffer:
- return D3D11_BIND_INDEX_BUFFER;
- case ResourceState::ConstantBuffer:
- return D3D11_BIND_CONSTANT_BUFFER;
- case ResourceState::StreamOutput:
- return D3D11_BIND_STREAM_OUTPUT;
- case ResourceState::RenderTarget:
- return D3D11_BIND_RENDER_TARGET;
- case ResourceState::DepthRead:
- case ResourceState::DepthWrite:
- return D3D11_BIND_DEPTH_STENCIL;
- case ResourceState::UnorderedAccess:
- return D3D11_BIND_UNORDERED_ACCESS;
- case ResourceState::ShaderResource:
- case ResourceState::PixelShaderResource:
- case ResourceState::NonPixelShaderResource:
- return D3D11_BIND_SHADER_RESOURCE;
- default:
- return D3D11_BIND_FLAG(0);
- }
+ case ResourceState::VertexBuffer: return D3D11_BIND_VERTEX_BUFFER;
+ case ResourceState::IndexBuffer: return D3D11_BIND_INDEX_BUFFER;
+ case ResourceState::ConstantBuffer: return D3D11_BIND_CONSTANT_BUFFER;
+ case ResourceState::StreamOutput: return D3D11_BIND_STREAM_OUTPUT;
+ case ResourceState::RenderTarget: return D3D11_BIND_RENDER_TARGET;
+ case ResourceState::DepthRead:
+ case ResourceState::DepthWrite: return D3D11_BIND_DEPTH_STENCIL;
+ case ResourceState::UnorderedAccess: return D3D11_BIND_UNORDERED_ACCESS;
+ case ResourceState::ShaderResource:
+ case ResourceState::PixelShaderResource:
+ case ResourceState::NonPixelShaderResource: return D3D11_BIND_SHADER_RESOURCE;
+ default: return D3D11_BIND_FLAG(0);
}
+}
- int _calcResourceBindFlags(ResourceStateSet allowedStates)
+int _calcResourceBindFlags(ResourceStateSet allowedStates)
+{
+ int dstFlags = 0;
+ for (uint32_t i = 0; i < (uint32_t)ResourceState::_Count; i++)
{
- int dstFlags = 0;
- for (uint32_t i = 0; i < (uint32_t)ResourceState::_Count; i++)
- {
- auto state = (ResourceState)i;
- if (allowedStates.contains(state))
- dstFlags |= calcResourceFlag(state);
- }
- return dstFlags;
+ auto state = (ResourceState)i;
+ if (allowedStates.contains(state))
+ dstFlags |= calcResourceFlag(state);
}
+ return dstFlags;
+}
- int _calcResourceAccessFlags(MemoryType memType)
+int _calcResourceAccessFlags(MemoryType memType)
+{
+ switch (memType)
{
- switch (memType)
- {
- case MemoryType::DeviceLocal:
- return 0;
- case MemoryType::ReadBack:
- return D3D11_CPU_ACCESS_READ;
- case MemoryType::Upload:
- return D3D11_CPU_ACCESS_WRITE;
- default:
- assert(!"Invalid flags");
- return 0;
- }
+ case MemoryType::DeviceLocal: return 0;
+ case MemoryType::ReadBack: return D3D11_CPU_ACCESS_READ;
+ case MemoryType::Upload: return D3D11_CPU_ACCESS_WRITE;
+ default: assert(!"Invalid flags"); return 0;
}
+}
- D3D11_FILTER_TYPE translateFilterMode(TextureFilteringMode mode)
+D3D11_FILTER_TYPE translateFilterMode(TextureFilteringMode mode)
+{
+ switch (mode)
{
- switch (mode)
- {
- default:
- return D3D11_FILTER_TYPE(0);
+ default: return D3D11_FILTER_TYPE(0);
#define CASE(SRC, DST) \
case TextureFilteringMode::SRC: return D3D11_FILTER_TYPE_##DST
- CASE(Point, POINT);
- CASE(Linear, LINEAR);
+ CASE(Point, POINT);
+ CASE(Linear, LINEAR);
#undef CASE
- }
}
+}
- D3D11_FILTER_REDUCTION_TYPE translateFilterReduction(TextureReductionOp op)
+D3D11_FILTER_REDUCTION_TYPE translateFilterReduction(TextureReductionOp op)
+{
+ switch (op)
{
- switch (op)
- {
- default:
- return D3D11_FILTER_REDUCTION_TYPE(0);
+ default: return D3D11_FILTER_REDUCTION_TYPE(0);
#define CASE(SRC, DST) \
case TextureReductionOp::SRC: return D3D11_FILTER_REDUCTION_TYPE_##DST
- CASE(Average, STANDARD);
- CASE(Comparison, COMPARISON);
- CASE(Minimum, MINIMUM);
- CASE(Maximum, MAXIMUM);
+ CASE(Average, STANDARD);
+ CASE(Comparison, COMPARISON);
+ CASE(Minimum, MINIMUM);
+ CASE(Maximum, MAXIMUM);
#undef CASE
- }
}
+}
- D3D11_TEXTURE_ADDRESS_MODE translateAddressingMode(TextureAddressingMode mode)
+D3D11_TEXTURE_ADDRESS_MODE translateAddressingMode(TextureAddressingMode mode)
+{
+ switch (mode)
{
- switch (mode)
- {
- default:
- return D3D11_TEXTURE_ADDRESS_MODE(0);
+ default: return D3D11_TEXTURE_ADDRESS_MODE(0);
#define CASE(SRC, DST) \
case TextureAddressingMode::SRC: return D3D11_TEXTURE_ADDRESS_##DST
- CASE(Wrap, WRAP);
- CASE(ClampToEdge, CLAMP);
- CASE(ClampToBorder, BORDER);
- CASE(MirrorRepeat, MIRROR);
- CASE(MirrorOnce, MIRROR_ONCE);
+ CASE(Wrap, WRAP);
+ CASE(ClampToEdge, CLAMP);
+ CASE(ClampToBorder, BORDER);
+ CASE(MirrorRepeat, MIRROR);
+ CASE(MirrorOnce, MIRROR_ONCE);
#undef CASE
- }
}
+}
- D3D11_COMPARISON_FUNC translateComparisonFunc(ComparisonFunc func)
+D3D11_COMPARISON_FUNC translateComparisonFunc(ComparisonFunc func)
+{
+ switch (func)
{
- switch (func)
- {
- default:
- // TODO: need to report failures
- return D3D11_COMPARISON_ALWAYS;
+ default:
+ // TODO: need to report failures
+ return D3D11_COMPARISON_ALWAYS;
#define CASE(FROM, TO) \
case ComparisonFunc::FROM: return D3D11_COMPARISON_##TO
- CASE(Never, NEVER);
- CASE(Less, LESS);
- CASE(Equal, EQUAL);
- CASE(LessEqual, LESS_EQUAL);
- CASE(Greater, GREATER);
- CASE(NotEqual, NOT_EQUAL);
- CASE(GreaterEqual, GREATER_EQUAL);
- CASE(Always, ALWAYS);
+ CASE(Never, NEVER);
+ CASE(Less, LESS);
+ CASE(Equal, EQUAL);
+ CASE(LessEqual, LESS_EQUAL);
+ CASE(Greater, GREATER);
+ CASE(NotEqual, NOT_EQUAL);
+ CASE(GreaterEqual, GREATER_EQUAL);
+ CASE(Always, ALWAYS);
#undef CASE
- }
}
+}
- D3D11_STENCIL_OP translateStencilOp(StencilOp op)
+D3D11_STENCIL_OP translateStencilOp(StencilOp op)
+{
+ switch (op)
{
- switch (op)
- {
- default:
- // TODO: need to report failures
- return D3D11_STENCIL_OP_KEEP;
+ default:
+ // TODO: need to report failures
+ return D3D11_STENCIL_OP_KEEP;
#define CASE(FROM, TO) \
case StencilOp::FROM: return D3D11_STENCIL_OP_##TO
- CASE(Keep, KEEP);
- CASE(Zero, ZERO);
- CASE(Replace, REPLACE);
- CASE(IncrementSaturate, INCR_SAT);
- CASE(DecrementSaturate, DECR_SAT);
- CASE(Invert, INVERT);
- CASE(IncrementWrap, INCR);
- CASE(DecrementWrap, DECR);
+ CASE(Keep, KEEP);
+ CASE(Zero, ZERO);
+ CASE(Replace, REPLACE);
+ CASE(IncrementSaturate, INCR_SAT);
+ CASE(DecrementSaturate, DECR_SAT);
+ CASE(Invert, INVERT);
+ CASE(IncrementWrap, INCR);
+ CASE(DecrementWrap, DECR);
#undef CASE
-
- }
}
+}
- D3D11_FILL_MODE translateFillMode(FillMode mode)
+D3D11_FILL_MODE translateFillMode(FillMode mode)
+{
+ switch (mode)
{
- switch (mode)
- {
- default:
- // TODO: need to report failures
- return D3D11_FILL_SOLID;
+ default:
+ // TODO: need to report failures
+ return D3D11_FILL_SOLID;
- case FillMode::Solid: return D3D11_FILL_SOLID;
- case FillMode::Wireframe: return D3D11_FILL_WIREFRAME;
- }
+ case FillMode::Solid: return D3D11_FILL_SOLID;
+ case FillMode::Wireframe: return D3D11_FILL_WIREFRAME;
}
+}
- D3D11_CULL_MODE translateCullMode(CullMode mode)
+D3D11_CULL_MODE translateCullMode(CullMode mode)
+{
+ switch (mode)
{
- switch (mode)
- {
- default:
- // TODO: need to report failures
- return D3D11_CULL_NONE;
+ default:
+ // TODO: need to report failures
+ return D3D11_CULL_NONE;
- case CullMode::None: return D3D11_CULL_NONE;
- case CullMode::Back: return D3D11_CULL_BACK;
- case CullMode::Front: return D3D11_CULL_FRONT;
- }
+ case CullMode::None: return D3D11_CULL_NONE;
+ case CullMode::Back: return D3D11_CULL_BACK;
+ case CullMode::Front: return D3D11_CULL_FRONT;
}
+}
- bool isBlendDisabled(AspectBlendDesc const& desc)
- {
- return desc.op == BlendOp::Add
- && desc.srcFactor == BlendFactor::One
- && desc.dstFactor == BlendFactor::Zero;
- }
+bool isBlendDisabled(AspectBlendDesc const& desc)
+{
+ return desc.op == BlendOp::Add && desc.srcFactor == BlendFactor::One &&
+ desc.dstFactor == BlendFactor::Zero;
+}
- bool isBlendDisabled(TargetBlendDesc const& desc)
- {
- return isBlendDisabled(desc.color)
- && isBlendDisabled(desc.alpha);
- }
+bool isBlendDisabled(TargetBlendDesc const& desc)
+{
+ return isBlendDisabled(desc.color) && isBlendDisabled(desc.alpha);
+}
- D3D11_BLEND_OP translateBlendOp(BlendOp op)
+D3D11_BLEND_OP translateBlendOp(BlendOp op)
+{
+ switch (op)
{
- switch (op)
- {
- default:
- assert(!"unimplemented");
- return (D3D11_BLEND_OP)-1;
-
-#define CASE(FROM, TO) case BlendOp::FROM: return D3D11_BLEND_OP_##TO
- CASE(Add, ADD);
- CASE(Subtract, SUBTRACT);
- CASE(ReverseSubtract, REV_SUBTRACT);
- CASE(Min, MIN);
- CASE(Max, MAX);
+ default: assert(!"unimplemented"); return (D3D11_BLEND_OP)-1;
+
+#define CASE(FROM, TO) \
+ case BlendOp::FROM: return D3D11_BLEND_OP_##TO
+ CASE(Add, ADD);
+ CASE(Subtract, SUBTRACT);
+ CASE(ReverseSubtract, REV_SUBTRACT);
+ CASE(Min, MIN);
+ CASE(Max, MAX);
#undef CASE
- }
}
+}
- D3D11_BLEND translateBlendFactor(BlendFactor factor)
+D3D11_BLEND translateBlendFactor(BlendFactor factor)
+{
+ switch (factor)
{
- switch (factor)
- {
- default:
- assert(!"unimplemented");
- return (D3D11_BLEND)-1;
-
-#define CASE(FROM, TO) case BlendFactor::FROM: return D3D11_BLEND_##TO
- CASE(Zero, ZERO);
- CASE(One, ONE);
- CASE(SrcColor, SRC_COLOR);
- CASE(InvSrcColor, INV_SRC_COLOR);
- CASE(SrcAlpha, SRC_ALPHA);
- CASE(InvSrcAlpha, INV_SRC_ALPHA);
- CASE(DestAlpha, DEST_ALPHA);
- CASE(InvDestAlpha, INV_DEST_ALPHA);
- CASE(DestColor, DEST_COLOR);
- CASE(InvDestColor, INV_DEST_ALPHA);
- CASE(SrcAlphaSaturate, SRC_ALPHA_SAT);
- CASE(BlendColor, BLEND_FACTOR);
- CASE(InvBlendColor, INV_BLEND_FACTOR);
- CASE(SecondarySrcColor, SRC1_COLOR);
- CASE(InvSecondarySrcColor, INV_SRC1_COLOR);
- CASE(SecondarySrcAlpha, SRC1_ALPHA);
- CASE(InvSecondarySrcAlpha, INV_SRC1_ALPHA);
+ default: assert(!"unimplemented"); return (D3D11_BLEND)-1;
+
+#define CASE(FROM, TO) \
+ case BlendFactor::FROM: return D3D11_BLEND_##TO
+ CASE(Zero, ZERO);
+ CASE(One, ONE);
+ CASE(SrcColor, SRC_COLOR);
+ CASE(InvSrcColor, INV_SRC_COLOR);
+ CASE(SrcAlpha, SRC_ALPHA);
+ CASE(InvSrcAlpha, INV_SRC_ALPHA);
+ CASE(DestAlpha, DEST_ALPHA);
+ CASE(InvDestAlpha, INV_DEST_ALPHA);
+ CASE(DestColor, DEST_COLOR);
+ CASE(InvDestColor, INV_DEST_ALPHA);
+ CASE(SrcAlphaSaturate, SRC_ALPHA_SAT);
+ CASE(BlendColor, BLEND_FACTOR);
+ CASE(InvBlendColor, INV_BLEND_FACTOR);
+ CASE(SecondarySrcColor, SRC1_COLOR);
+ CASE(InvSecondarySrcColor, INV_SRC1_COLOR);
+ CASE(SecondarySrcAlpha, SRC1_ALPHA);
+ CASE(InvSecondarySrcAlpha, INV_SRC1_ALPHA);
#undef CASE
- }
}
+}
- D3D11_COLOR_WRITE_ENABLE translateRenderTargetWriteMask(RenderTargetWriteMaskT mask)
- {
- UINT result = 0;
-#define CASE(FROM, TO) if(mask & RenderTargetWriteMask::Enable##FROM) result |= D3D11_COLOR_WRITE_ENABLE_##TO
+D3D11_COLOR_WRITE_ENABLE translateRenderTargetWriteMask(RenderTargetWriteMaskT mask)
+{
+ UINT result = 0;
+#define CASE(FROM, TO) \
+ if (mask & RenderTargetWriteMask::Enable##FROM) \
+ result |= D3D11_COLOR_WRITE_ENABLE_##TO
- CASE(Red, RED);
- CASE(Green, GREEN);
- CASE(Blue, BLUE);
- CASE(Alpha, ALPHA);
+ CASE(Red, RED);
+ CASE(Green, GREEN);
+ CASE(Blue, BLUE);
+ CASE(Alpha, ALPHA);
#undef CASE
- return D3D11_COLOR_WRITE_ENABLE(result);
- }
+ return D3D11_COLOR_WRITE_ENABLE(result);
+}
- void initSrvDesc(IResource::Type resourceType, const ITextureResource::Desc& textureDesc, DXGI_FORMAT pixelFormat, D3D11_SHADER_RESOURCE_VIEW_DESC& descOut)
+void initSrvDesc(
+ IResource::Type resourceType,
+ const ITextureResource::Desc& textureDesc,
+ DXGI_FORMAT pixelFormat,
+ D3D11_SHADER_RESOURCE_VIEW_DESC& descOut)
+{
+ // create SRV
+ descOut = D3D11_SHADER_RESOURCE_VIEW_DESC();
+
+ descOut.Format =
+ (pixelFormat == DXGI_FORMAT_UNKNOWN)
+ ? D3DUtil::calcFormat(D3DUtil::USAGE_SRV, D3DUtil::getMapFormat(textureDesc.format))
+ : pixelFormat;
+ const int arraySize = calcEffectiveArraySize(textureDesc);
+ if (arraySize <= 1)
{
- // create SRV
- descOut = D3D11_SHADER_RESOURCE_VIEW_DESC();
-
- descOut.Format = (pixelFormat == DXGI_FORMAT_UNKNOWN) ? D3DUtil::calcFormat(D3DUtil::USAGE_SRV, D3DUtil::getMapFormat(textureDesc.format)) : pixelFormat;
- const int arraySize = calcEffectiveArraySize(textureDesc);
- if (arraySize <= 1)
+ switch (textureDesc.type)
{
- switch (textureDesc.type)
- {
- case IResource::Type::Texture1D: descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; break;
- case IResource::Type::Texture2D: descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; break;
- case IResource::Type::Texture3D: descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; break;
- default: assert(!"Unknown dimension");
- }
-
- descOut.Texture2D.MipLevels = textureDesc.numMipLevels;
- descOut.Texture2D.MostDetailedMip = 0;
+ case IResource::Type::Texture1D:
+ descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D;
+ break;
+ case IResource::Type::Texture2D:
+ descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
+ break;
+ case IResource::Type::Texture3D:
+ descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
+ break;
+ default: assert(!"Unknown dimension");
}
- else if (resourceType == IResource::Type::TextureCube)
+
+ descOut.Texture2D.MipLevels = textureDesc.numMipLevels;
+ descOut.Texture2D.MostDetailedMip = 0;
+ }
+ else if (resourceType == IResource::Type::TextureCube)
+ {
+ if (textureDesc.arraySize > 1)
{
- if (textureDesc.arraySize > 1)
- {
- descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY;
-
- descOut.TextureCubeArray.NumCubes = textureDesc.arraySize;
- descOut.TextureCubeArray.First2DArrayFace = 0;
- descOut.TextureCubeArray.MipLevels = textureDesc.numMipLevels;
- descOut.TextureCubeArray.MostDetailedMip = 0;
- }
- else
- {
- descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
-
- descOut.TextureCube.MipLevels = textureDesc.numMipLevels;
- descOut.TextureCube.MostDetailedMip = 0;
- }
+ descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY;
+
+ descOut.TextureCubeArray.NumCubes = textureDesc.arraySize;
+ descOut.TextureCubeArray.First2DArrayFace = 0;
+ descOut.TextureCubeArray.MipLevels = textureDesc.numMipLevels;
+ descOut.TextureCubeArray.MostDetailedMip = 0;
}
else
{
- assert(textureDesc.size.depth > 1 || arraySize > 1);
+ descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
- switch (textureDesc.type)
- {
- case IResource::Type::Texture1D: descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; break;
- case IResource::Type::Texture2D: descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; break;
- case IResource::Type::Texture3D: descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; break;
-
- default: assert(!"Unknown dimension");
- }
+ descOut.TextureCube.MipLevels = textureDesc.numMipLevels;
+ descOut.TextureCube.MostDetailedMip = 0;
+ }
+ }
+ else
+ {
+ assert(textureDesc.size.depth > 1 || arraySize > 1);
- descOut.Texture2DArray.ArraySize = std::max(textureDesc.size.depth, arraySize);
- descOut.Texture2DArray.MostDetailedMip = 0;
- descOut.Texture2DArray.MipLevels = textureDesc.numMipLevels;
- descOut.Texture2DArray.FirstArraySlice = 0;
+ switch (textureDesc.type)
+ {
+ case IResource::Type::Texture1D:
+ descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY;
+ break;
+ case IResource::Type::Texture2D:
+ descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
+ break;
+ case IResource::Type::Texture3D:
+ descOut.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
+ break;
+
+ default: assert(!"Unknown dimension");
}
+
+ descOut.Texture2DArray.ArraySize = std::max(textureDesc.size.depth, arraySize);
+ descOut.Texture2DArray.MostDetailedMip = 0;
+ descOut.Texture2DArray.MipLevels = textureDesc.numMipLevels;
+ descOut.Texture2DArray.FirstArraySlice = 0;
}
+}
} // namespace d3d11
Result SLANG_MCALL getD3D11Adapters(List<AdapterInfo>& outAdapters)
{
List<ComPtr<IDXGIAdapter>> dxgiAdapters;
- SLANG_RETURN_ON_FAIL(D3DUtil::findAdapters(DeviceCheckFlag::UseHardwareDevice, nullptr, dxgiAdapters));
+ SLANG_RETURN_ON_FAIL(
+ D3DUtil::findAdapters(DeviceCheckFlag::UseHardwareDevice, nullptr, dxgiAdapters));
outAdapters.clear();
for (const auto& dxgiAdapter : dxgiAdapters)
@@ -357,7 +358,10 @@ Result SLANG_MCALL getD3D11Adapters(List<AdapterInfo>& outAdapters)
dxgiAdapter->GetDesc(&desc);
AdapterInfo info = {};
auto name = String::fromWString(desc.Description);
- memcpy(info.name, name.getBuffer(), Math::Min(name.getLength(), (Index)sizeof(AdapterInfo::name) - 1));
+ memcpy(
+ info.name,
+ name.getBuffer(),
+ Math::Min(name.getLength(), (Index)sizeof(AdapterInfo::name) - 1));
info.vendorID = desc.VendorId;
info.deviceID = desc.DeviceId;
info.luid = D3DUtil::getAdapterLUID(dxgiAdapter);
diff --git a/tools/gfx/d3d11/d3d11-helper-functions.h b/tools/gfx/d3d11/d3d11-helper-functions.h
index 9f115d88d..cca49de14 100644
--- a/tools/gfx/d3d11/d3d11-helper-functions.h
+++ b/tools/gfx/d3d11/d3d11-helper-functions.h
@@ -1,9 +1,9 @@
// d3d11-helper-functions.h
#pragma once
-#include "slang-gfx.h"
-#include "d3d11-base.h"
#include "../../../source/core/slang-list.h"
+#include "d3d11-base.h"
+#include "slang-gfx.h"
namespace gfx
{
@@ -12,274 +12,265 @@ using namespace Slang;
namespace d3d11
{
- /// Contextual data and operations required when binding shader objects to the pipeline state
- struct BindingContext
+/// Contextual data and operations required when binding shader objects to the pipeline state
+struct BindingContext
+{
+ // One key service that the `BindingContext` provides is abstracting over
+ // the difference between the D3D11 compute and graphics/rasteriation pipelines.
+ // D3D11 has distinct operations for, e.g., `CSSetShaderResources`
+ // for compute vs. `VSSetShaderResources` and `PSSetShaderResources`
+ // for rasterization.
+ //
+ // The context type provides simple operations for setting each class
+ // of resource/sampler, which will be overridden in derived types.
+ //
+ // TODO: These operations should really support binding multiple resources/samplers
+ // in one call, so that we can eventually make more efficient use of the API.
+ //
+ // TODO: We could reasonably also just store the bound resources into
+ // lcoal arrays like we are doing for UAVs, and remove the pipeline-specific
+ // virtual functions. However, doing so would seemingly eliminate any
+ // chance of avoiding redundant binding work when binding changes are
+ // made for a root shader object.
+ //
+ virtual void setCBV(UINT index, ID3D11Buffer* buffer) = 0;
+ virtual void setSRV(UINT index, ID3D11ShaderResourceView* srv) = 0;
+ virtual void setSampler(UINT index, ID3D11SamplerState* sampler) = 0;
+
+ // Unordered Access Views (UAVs) are a somewhat special case in that
+ // the D3D11 API requires them to all be set at once, rather than one
+ // at a time. To support this, we will keep a local array of the UAVs
+ // that have been bound (up to the maximum supported by D3D 11.0)
+ //
+ void setUAV(UINT index, ID3D11UnorderedAccessView* uav)
{
- // One key service that the `BindingContext` provides is abstracting over
- // the difference between the D3D11 compute and graphics/rasteriation pipelines.
- // D3D11 has distinct operations for, e.g., `CSSetShaderResources`
- // for compute vs. `VSSetShaderResources` and `PSSetShaderResources`
- // for rasterization.
- //
- // The context type provides simple operations for setting each class
- // of resource/sampler, which will be overridden in derived types.
- //
- // TODO: These operations should really support binding multiple resources/samplers
- // in one call, so that we can eventually make more efficient use of the API.
- //
- // TODO: We could reasonably also just store the bound resources into
- // lcoal arrays like we are doing for UAVs, and remove the pipeline-specific
- // virtual functions. However, doing so would seemingly eliminate any
- // chance of avoiding redundant binding work when binding changes are
- // made for a root shader object.
- //
- virtual void setCBV(UINT index, ID3D11Buffer* buffer) = 0;
- virtual void setSRV(UINT index, ID3D11ShaderResourceView* srv) = 0;
- virtual void setSampler(UINT index, ID3D11SamplerState* sampler) = 0;
-
- // Unordered Access Views (UAVs) are a somewhat special case in that
- // the D3D11 API requires them to all be set at once, rather than one
- // at a time. To support this, we will keep a local array of the UAVs
- // that have been bound (up to the maximum supported by D3D 11.0)
+ uavs[index] = uav;
+
+ // We will also track the total number of UAV slots that will
+ // need to be bound (including any gaps that might occur due
+ // to either explicit bindings or RTV bindings that conflict
+ // with the `u` registers for fragment shaders).
//
- void setUAV(UINT index, ID3D11UnorderedAccessView* uav)
+ if (uavCount <= index)
{
- uavs[index] = uav;
-
- // We will also track the total number of UAV slots that will
- // need to be bound (including any gaps that might occur due
- // to either explicit bindings or RTV bindings that conflict
- // with the `u` registers for fragment shaders).
- //
- if (uavCount <= index)
- {
- uavCount = index + 1;
- }
+ uavCount = index + 1;
}
+ }
- /// The values bound for any UAVs
- ID3D11UnorderedAccessView* uavs[D3D11_PS_CS_UAV_REGISTER_COUNT];
+ /// The values bound for any UAVs
+ ID3D11UnorderedAccessView* uavs[D3D11_PS_CS_UAV_REGISTER_COUNT];
- /// The number of entries in `uavs` that need to be considered when binding to the pipeline
- UINT uavCount = 0;
+ /// The number of entries in `uavs` that need to be considered when binding to the pipeline
+ UINT uavCount = 0;
- /// The D3D11 device that we are using for binding
- DeviceImpl* device = nullptr;
+ /// The D3D11 device that we are using for binding
+ DeviceImpl* device = nullptr;
- /// The D3D11 device context that we are using for binding
- ID3D11DeviceContext* context = nullptr;
+ /// The D3D11 device context that we are using for binding
+ ID3D11DeviceContext* context = nullptr;
- /// Initialize a binding context for binding to the given `device` and `context`
- BindingContext(
- DeviceImpl* device,
- ID3D11DeviceContext* context)
- : device(device)
- , context(context)
- {
- memset(uavs, 0, sizeof(uavs));
- }
- };
-
- /// A `BindingContext` for binding to the compute pipeline
- struct ComputeBindingContext : BindingContext
+ /// Initialize a binding context for binding to the given `device` and `context`
+ BindingContext(DeviceImpl* device, ID3D11DeviceContext* context)
+ : device(device), context(context)
{
- /// Initialize a binding context for binding to the given `device` and `context`
- ComputeBindingContext(
- DeviceImpl* device,
- ID3D11DeviceContext* context)
- : BindingContext(device, context)
- {}
-
- void setCBV(UINT index, ID3D11Buffer* buffer) SLANG_OVERRIDE
- {
- context->CSSetConstantBuffers(index, 1, &buffer);
- }
+ memset(uavs, 0, sizeof(uavs));
+ }
+};
- void setSRV(UINT index, ID3D11ShaderResourceView* srv) SLANG_OVERRIDE
- {
- context->CSSetShaderResources(index, 1, &srv);
- }
+/// A `BindingContext` for binding to the compute pipeline
+struct ComputeBindingContext : BindingContext
+{
+ /// Initialize a binding context for binding to the given `device` and `context`
+ ComputeBindingContext(DeviceImpl* device, ID3D11DeviceContext* context)
+ : BindingContext(device, context)
+ {
+ }
- void setSampler(UINT index, ID3D11SamplerState* sampler) SLANG_OVERRIDE
- {
- context->CSSetSamplers(index, 1, &sampler);
- }
- };
+ void setCBV(UINT index, ID3D11Buffer* buffer) SLANG_OVERRIDE
+ {
+ context->CSSetConstantBuffers(index, 1, &buffer);
+ }
- /// A `BindingContext` for binding to the graphics/rasterization pipeline
- struct GraphicsBindingContext : BindingContext
+ void setSRV(UINT index, ID3D11ShaderResourceView* srv) SLANG_OVERRIDE
{
- /// Initialize a binding context for binding to the given `device` and `context`
- GraphicsBindingContext(
- DeviceImpl* device,
- ID3D11DeviceContext* context)
- : BindingContext(device, context)
- {}
-
- // TODO: The operations here are only dealing with vertex and fragment
- // shaders for now. We should eventually extend them to handle HS/DS/GS
- // bindings. (We might want to skip those stages depending on whether
- // the associated program uses them at all).
- //
- // TODO: If we support cases where different stages might use distinct
- // entry-point parameters, we might need to support some modes where
- // a "stage mask" is passed in that applies to the bindings.
- //
- void setCBV(UINT index, ID3D11Buffer* buffer) SLANG_OVERRIDE
- {
- context->VSSetConstantBuffers(index, 1, &buffer);
- context->PSSetConstantBuffers(index, 1, &buffer);
- }
+ context->CSSetShaderResources(index, 1, &srv);
+ }
- void setSRV(UINT index, ID3D11ShaderResourceView* srv) SLANG_OVERRIDE
- {
- context->VSSetShaderResources(index, 1, &srv);
- context->PSSetShaderResources(index, 1, &srv);
- }
+ void setSampler(UINT index, ID3D11SamplerState* sampler) SLANG_OVERRIDE
+ {
+ context->CSSetSamplers(index, 1, &sampler);
+ }
+};
- void setSampler(UINT index, ID3D11SamplerState* sampler) SLANG_OVERRIDE
- {
- context->VSSetSamplers(index, 1, &sampler);
- context->PSSetSamplers(index, 1, &sampler);
- }
- };
+/// A `BindingContext` for binding to the graphics/rasterization pipeline
+struct GraphicsBindingContext : BindingContext
+{
+ /// Initialize a binding context for binding to the given `device` and `context`
+ GraphicsBindingContext(DeviceImpl* device, ID3D11DeviceContext* context)
+ : BindingContext(device, context)
+ {
+ }
- // In order to bind shader parameters to the correct locations, we need to
- // be able to describe those locations. Most shader parameters will
- // only consume a single type of D3D11-visible regsiter (e.g., a `t`
- // register for a txture, or an `s` register for a sampler), and scalar
- // integers suffice for these cases.
+ // TODO: The operations here are only dealing with vertex and fragment
+ // shaders for now. We should eventually extend them to handle HS/DS/GS
+ // bindings. (We might want to skip those stages depending on whether
+ // the associated program uses them at all).
+ //
+ // TODO: If we support cases where different stages might use distinct
+ // entry-point parameters, we might need to support some modes where
+ // a "stage mask" is passed in that applies to the bindings.
//
- // In more complex cases we might be binding an entire "sub-object" like
- // a parameter block, an entry point, etc. For the general case, we need
- // to be able to represent a composite offset that includes offsets for
- // each of the register classes known to D3D11.
+ void setCBV(UINT index, ID3D11Buffer* buffer) SLANG_OVERRIDE
+ {
+ context->VSSetConstantBuffers(index, 1, &buffer);
+ context->PSSetConstantBuffers(index, 1, &buffer);
+ }
- /// A "simple" binding offset that records an offset in CBV/SRV/UAV/Sampler slots
- struct SimpleBindingOffset
+ void setSRV(UINT index, ID3D11ShaderResourceView* srv) SLANG_OVERRIDE
{
- uint32_t cbv = 0;
- uint32_t srv = 0;
- uint32_t uav = 0;
- uint32_t sampler = 0;
+ context->VSSetShaderResources(index, 1, &srv);
+ context->PSSetShaderResources(index, 1, &srv);
+ }
- /// Create a default (zero) offset
- SimpleBindingOffset()
- {}
+ void setSampler(UINT index, ID3D11SamplerState* sampler) SLANG_OVERRIDE
+ {
+ context->VSSetSamplers(index, 1, &sampler);
+ context->PSSetSamplers(index, 1, &sampler);
+ }
+};
+
+// In order to bind shader parameters to the correct locations, we need to
+// be able to describe those locations. Most shader parameters will
+// only consume a single type of D3D11-visible regsiter (e.g., a `t`
+// register for a txture, or an `s` register for a sampler), and scalar
+// integers suffice for these cases.
+//
+// In more complex cases we might be binding an entire "sub-object" like
+// a parameter block, an entry point, etc. For the general case, we need
+// to be able to represent a composite offset that includes offsets for
+// each of the register classes known to D3D11.
+
+/// A "simple" binding offset that records an offset in CBV/SRV/UAV/Sampler slots
+struct SimpleBindingOffset
+{
+ uint32_t cbv = 0;
+ uint32_t srv = 0;
+ uint32_t uav = 0;
+ uint32_t sampler = 0;
- /// Create an offset based on offset information in the given Slang `varLayout`
- SimpleBindingOffset(slang::VariableLayoutReflection* varLayout)
- {
- if (varLayout)
- {
- cbv = (uint32_t)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER);
- srv = (uint32_t)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_SHADER_RESOURCE);
- uav = (uint32_t)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_UNORDERED_ACCESS);
- sampler = (uint32_t)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_SAMPLER_STATE);
- }
- }
+ /// Create a default (zero) offset
+ SimpleBindingOffset() {}
- /// Create an offset based on size/stride information in the given Slang `typeLayout`
- SimpleBindingOffset(slang::TypeLayoutReflection* typeLayout)
+ /// Create an offset based on offset information in the given Slang `varLayout`
+ SimpleBindingOffset(slang::VariableLayoutReflection* varLayout)
+ {
+ if (varLayout)
{
- if (typeLayout)
- {
- cbv = (uint32_t)typeLayout->getSize(SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER);
- srv = (uint32_t)typeLayout->getSize(SLANG_PARAMETER_CATEGORY_SHADER_RESOURCE);
- uav = (uint32_t)typeLayout->getSize(SLANG_PARAMETER_CATEGORY_UNORDERED_ACCESS);
- sampler = (uint32_t)typeLayout->getSize(SLANG_PARAMETER_CATEGORY_SAMPLER_STATE);
- }
+ cbv = (uint32_t)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER);
+ srv = (uint32_t)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_SHADER_RESOURCE);
+ uav = (uint32_t)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_UNORDERED_ACCESS);
+ sampler = (uint32_t)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_SAMPLER_STATE);
}
+ }
- /// Add any values in the given `offset`
- void operator+=(SimpleBindingOffset const& offset)
+ /// Create an offset based on size/stride information in the given Slang `typeLayout`
+ SimpleBindingOffset(slang::TypeLayoutReflection* typeLayout)
+ {
+ if (typeLayout)
{
- cbv += offset.cbv;
- srv += offset.srv;
- uav += offset.uav;
- sampler += offset.sampler;
+ cbv = (uint32_t)typeLayout->getSize(SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER);
+ srv = (uint32_t)typeLayout->getSize(SLANG_PARAMETER_CATEGORY_SHADER_RESOURCE);
+ uav = (uint32_t)typeLayout->getSize(SLANG_PARAMETER_CATEGORY_UNORDERED_ACCESS);
+ sampler = (uint32_t)typeLayout->getSize(SLANG_PARAMETER_CATEGORY_SAMPLER_STATE);
}
- };
+ }
- // While a "simple" binding offset representation will work in many cases,
- // once we need to deal with layout for programs with interface-type parameters
- // that have been statically specialized, we also need to track the offset
- // for where to bind any "pending" data that arises from the process of static
- // specialization.
- //
- // In order to conveniently track both the "primary" and "pending" offset information,
- // we will define a more complete `BindingOffset` type that combines simple
- // binding offsets for the primary and pending parts.
+ /// Add any values in the given `offset`
+ void operator+=(SimpleBindingOffset const& offset)
+ {
+ cbv += offset.cbv;
+ srv += offset.srv;
+ uav += offset.uav;
+ sampler += offset.sampler;
+ }
+};
+
+// While a "simple" binding offset representation will work in many cases,
+// once we need to deal with layout for programs with interface-type parameters
+// that have been statically specialized, we also need to track the offset
+// for where to bind any "pending" data that arises from the process of static
+// specialization.
+//
+// In order to conveniently track both the "primary" and "pending" offset information,
+// we will define a more complete `BindingOffset` type that combines simple
+// binding offsets for the primary and pending parts.
+
+/// A representation of the offset at which to bind a shader parameter or sub-object
+struct BindingOffset : SimpleBindingOffset
+{
+ // Offsets for "primary" data are stored directly in the `BindingOffset`
+ // via the inheritance from `SimpleBindingOffset`.
+
+ /// Offset for any "pending" data
+ SimpleBindingOffset pending;
- /// A representation of the offset at which to bind a shader parameter or sub-object
- struct BindingOffset : SimpleBindingOffset
+ /// Create a default (zero) offset
+ BindingOffset() {}
+
+ /// Create an offset from a simple offset
+ explicit BindingOffset(SimpleBindingOffset const& offset)
+ : SimpleBindingOffset(offset)
{
- // Offsets for "primary" data are stored directly in the `BindingOffset`
- // via the inheritance from `SimpleBindingOffset`.
-
- /// Offset for any "pending" data
- SimpleBindingOffset pending;
-
- /// Create a default (zero) offset
- BindingOffset()
- {}
-
- /// Create an offset from a simple offset
- explicit BindingOffset(SimpleBindingOffset const& offset)
- : SimpleBindingOffset(offset)
- {}
-
- /// Create an offset based on offset information in the given Slang `varLayout`
- BindingOffset(slang::VariableLayoutReflection* varLayout)
- : SimpleBindingOffset(varLayout)
- , pending(varLayout->getPendingDataLayout())
- {}
-
- /// Create an offset based on size/stride information in the given Slang `typeLayout`
- BindingOffset(slang::TypeLayoutReflection* typeLayout)
- : SimpleBindingOffset(typeLayout)
- , pending(typeLayout->getPendingDataTypeLayout())
- {}
-
- /// Add any values in the given `offset`
- void operator+=(SimpleBindingOffset const& offset)
- {
- SimpleBindingOffset::operator+=(offset);
- }
+ }
- /// Add any values in the given `offset`
- void operator+=(BindingOffset const& offset)
- {
- SimpleBindingOffset::operator+=(offset);
- pending += offset.pending;
- }
- };
-
- bool isSupportedNVAPIOp(IUnknown* dev, uint32_t op);
-
- D3D11_BIND_FLAG calcResourceFlag(ResourceState state);
- int _calcResourceBindFlags(ResourceStateSet allowedStates);
- int _calcResourceAccessFlags(MemoryType memType);
-
- D3D11_FILTER_TYPE translateFilterMode(TextureFilteringMode mode);
- D3D11_FILTER_REDUCTION_TYPE translateFilterReduction(TextureReductionOp op);
- D3D11_TEXTURE_ADDRESS_MODE translateAddressingMode(TextureAddressingMode mode);
- D3D11_COMPARISON_FUNC translateComparisonFunc(ComparisonFunc func);
-
- D3D11_STENCIL_OP translateStencilOp(StencilOp op);
- D3D11_FILL_MODE translateFillMode(FillMode mode);
- D3D11_CULL_MODE translateCullMode(CullMode mode);
- bool isBlendDisabled(AspectBlendDesc const& desc);
- bool isBlendDisabled(TargetBlendDesc const& desc);
- D3D11_BLEND_OP translateBlendOp(BlendOp op);
- D3D11_BLEND translateBlendFactor(BlendFactor factor);
- D3D11_COLOR_WRITE_ENABLE translateRenderTargetWriteMask(RenderTargetWriteMaskT mask);
-
- void initSrvDesc(
- IResource::Type resourceType,
- const ITextureResource::Desc& textureDesc,
- DXGI_FORMAT pixelFormat,
- D3D11_SHADER_RESOURCE_VIEW_DESC& descOut);
+ /// Create an offset based on offset information in the given Slang `varLayout`
+ BindingOffset(slang::VariableLayoutReflection* varLayout)
+ : SimpleBindingOffset(varLayout), pending(varLayout->getPendingDataLayout())
+ {
+ }
+
+ /// Create an offset based on size/stride information in the given Slang `typeLayout`
+ BindingOffset(slang::TypeLayoutReflection* typeLayout)
+ : SimpleBindingOffset(typeLayout), pending(typeLayout->getPendingDataTypeLayout())
+ {
+ }
+
+ /// Add any values in the given `offset`
+ void operator+=(SimpleBindingOffset const& offset) { SimpleBindingOffset::operator+=(offset); }
+
+ /// Add any values in the given `offset`
+ void operator+=(BindingOffset const& offset)
+ {
+ SimpleBindingOffset::operator+=(offset);
+ pending += offset.pending;
+ }
+};
+
+bool isSupportedNVAPIOp(IUnknown* dev, uint32_t op);
+
+D3D11_BIND_FLAG calcResourceFlag(ResourceState state);
+int _calcResourceBindFlags(ResourceStateSet allowedStates);
+int _calcResourceAccessFlags(MemoryType memType);
+
+D3D11_FILTER_TYPE translateFilterMode(TextureFilteringMode mode);
+D3D11_FILTER_REDUCTION_TYPE translateFilterReduction(TextureReductionOp op);
+D3D11_TEXTURE_ADDRESS_MODE translateAddressingMode(TextureAddressingMode mode);
+D3D11_COMPARISON_FUNC translateComparisonFunc(ComparisonFunc func);
+
+D3D11_STENCIL_OP translateStencilOp(StencilOp op);
+D3D11_FILL_MODE translateFillMode(FillMode mode);
+D3D11_CULL_MODE translateCullMode(CullMode mode);
+bool isBlendDisabled(AspectBlendDesc const& desc);
+bool isBlendDisabled(TargetBlendDesc const& desc);
+D3D11_BLEND_OP translateBlendOp(BlendOp op);
+D3D11_BLEND translateBlendFactor(BlendFactor factor);
+D3D11_COLOR_WRITE_ENABLE translateRenderTargetWriteMask(RenderTargetWriteMaskT mask);
+
+void initSrvDesc(
+ IResource::Type resourceType,
+ const ITextureResource::Desc& textureDesc,
+ DXGI_FORMAT pixelFormat,
+ D3D11_SHADER_RESOURCE_VIEW_DESC& descOut);
} // namespace d3d11
Result SLANG_MCALL getD3D11Adapters(List<AdapterInfo>& outAdapters);
diff --git a/tools/gfx/d3d11/d3d11-pipeline-state.h b/tools/gfx/d3d11/d3d11-pipeline-state.h
index 7ca812d1d..dec4ef285 100644
--- a/tools/gfx/d3d11/d3d11-pipeline-state.h
+++ b/tools/gfx/d3d11/d3d11-pipeline-state.h
@@ -19,15 +19,15 @@ public:
class GraphicsPipelineStateImpl : public PipelineStateImpl
{
public:
- UINT m_rtvCount;
+ UINT m_rtvCount;
- RefPtr<InputLayoutImpl> m_inputLayout;
+ RefPtr<InputLayoutImpl> m_inputLayout;
ComPtr<ID3D11DepthStencilState> m_depthStencilState;
- ComPtr<ID3D11RasterizerState> m_rasterizerState;
- ComPtr<ID3D11BlendState> m_blendState;
+ ComPtr<ID3D11RasterizerState> m_rasterizerState;
+ ComPtr<ID3D11BlendState> m_blendState;
- float m_blendColor[4];
- UINT m_sampleMask;
+ float m_blendColor[4];
+ UINT m_sampleMask;
void init(const GraphicsPipelineStateDesc& inDesc);
};
diff --git a/tools/gfx/d3d11/d3d11-query.cpp b/tools/gfx/d3d11/d3d11-query.cpp
index c917ccbca..1a1c27466 100644
--- a/tools/gfx/d3d11/d3d11-query.cpp
+++ b/tools/gfx/d3d11/d3d11-query.cpp
@@ -17,11 +17,8 @@ Result QueryPoolImpl::init(const IQueryPool::Desc& desc, DeviceImpl* device)
m_queryDesc.MiscFlags = 0;
switch (desc.type)
{
- case QueryType::Timestamp:
- m_queryDesc.Query = D3D11_QUERY_TIMESTAMP;
- break;
- default:
- return SLANG_E_INVALID_ARG;
+ case QueryType::Timestamp: m_queryDesc.Query = D3D11_QUERY_TIMESTAMP; break;
+ default: return SLANG_E_INVALID_ARG;
}
m_queries.setCount(desc.count);
return SLANG_OK;
@@ -34,12 +31,15 @@ ID3D11Query* QueryPoolImpl::getQuery(SlangInt index)
return m_queries[index].get();
}
-SLANG_NO_THROW Result SLANG_MCALL QueryPoolImpl::getResult(
- GfxIndex queryIndex, GfxCount count, uint64_t* data)
+SLANG_NO_THROW Result SLANG_MCALL
+QueryPoolImpl::getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data)
{
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT disjointData;
while (S_OK != m_device->m_immediateContext->GetData(
- m_device->m_disjointQuery, &disjointData, sizeof(D3D11_QUERY_DATA_TIMESTAMP_DISJOINT), 0))
+ m_device->m_disjointQuery,
+ &disjointData,
+ sizeof(D3D11_QUERY_DATA_TIMESTAMP_DISJOINT),
+ 0))
{
Process::sleepCurrentThread(1);
}
@@ -48,7 +48,10 @@ SLANG_NO_THROW Result SLANG_MCALL QueryPoolImpl::getResult(
for (SlangInt i = 0; i < count; i++)
{
SLANG_RETURN_ON_FAIL(m_device->m_immediateContext->GetData(
- m_queries[queryIndex + i], data + i, sizeof(uint64_t), 0));
+ m_queries[queryIndex + i],
+ data + i,
+ sizeof(uint64_t),
+ 0));
}
return SLANG_OK;
}
diff --git a/tools/gfx/d3d11/d3d11-query.h b/tools/gfx/d3d11/d3d11-query.h
index 393294c0a..63866d848 100644
--- a/tools/gfx/d3d11/d3d11-query.h
+++ b/tools/gfx/d3d11/d3d11-query.h
@@ -1,7 +1,6 @@
// d3d11-query.h
#pragma once
#include "d3d11-base.h"
-
#include "d3d11-device.h"
namespace gfx
@@ -12,18 +11,18 @@ using namespace Slang;
namespace d3d11
{
- class QueryPoolImpl : public QueryPoolBase
- {
- public:
- List<ComPtr<ID3D11Query>> m_queries;
- RefPtr<DeviceImpl> m_device;
- D3D11_QUERY_DESC m_queryDesc;
+class QueryPoolImpl : public QueryPoolBase
+{
+public:
+ List<ComPtr<ID3D11Query>> m_queries;
+ RefPtr<DeviceImpl> m_device;
+ D3D11_QUERY_DESC m_queryDesc;
- Result init(const IQueryPool::Desc& desc, DeviceImpl* device);
- ID3D11Query* getQuery(SlangInt index);
- virtual SLANG_NO_THROW Result SLANG_MCALL getResult(
- GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
- };
+ Result init(const IQueryPool::Desc& desc, DeviceImpl* device);
+ ID3D11Query* getQuery(SlangInt index);
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
+};
} // namespace d3d11
} // namespace gfx
diff --git a/tools/gfx/d3d11/d3d11-resource-views.h b/tools/gfx/d3d11/d3d11-resource-views.h
index f76acd98b..1ce385f20 100644
--- a/tools/gfx/d3d11/d3d11-resource-views.h
+++ b/tools/gfx/d3d11/d3d11-resource-views.h
@@ -27,26 +27,26 @@ public:
class ShaderResourceViewImpl : public ResourceViewImpl
{
public:
- ComPtr<ID3D11ShaderResourceView> m_srv;
+ ComPtr<ID3D11ShaderResourceView> m_srv;
};
class UnorderedAccessViewImpl : public ResourceViewImpl
{
public:
- ComPtr<ID3D11UnorderedAccessView> m_uav;
+ ComPtr<ID3D11UnorderedAccessView> m_uav;
};
class DepthStencilViewImpl : public ResourceViewImpl
{
public:
- ComPtr<ID3D11DepthStencilView> m_dsv;
+ ComPtr<ID3D11DepthStencilView> m_dsv;
DepthStencilClearValue m_clearValue;
};
class RenderTargetViewImpl : public ResourceViewImpl
{
public:
- ComPtr<ID3D11RenderTargetView> m_rtv;
+ ComPtr<ID3D11RenderTargetView> m_rtv;
float m_clearValue[4];
};
diff --git a/tools/gfx/d3d11/d3d11-scopeNVAPI.h b/tools/gfx/d3d11/d3d11-scopeNVAPI.h
index 0de611ee0..1e49f2db8 100644
--- a/tools/gfx/d3d11/d3d11-scopeNVAPI.h
+++ b/tools/gfx/d3d11/d3d11-scopeNVAPI.h
@@ -14,7 +14,10 @@ namespace d3d11
class ScopeNVAPI
{
public:
- ScopeNVAPI() : m_renderer(nullptr) {}
+ ScopeNVAPI()
+ : m_renderer(nullptr)
+ {
+ }
SlangResult init(DeviceImpl* renderer, Index regIndex);
~ScopeNVAPI();
diff --git a/tools/gfx/d3d11/d3d11-shader-object-layout.cpp b/tools/gfx/d3d11/d3d11-shader-object-layout.cpp
index 70204e4c0..b2b851760 100644
--- a/tools/gfx/d3d11/d3d11-shader-object-layout.cpp
+++ b/tools/gfx/d3d11/d3d11-shader-object-layout.cpp
@@ -29,7 +29,8 @@ ShaderObjectLayoutImpl::SubObjectRangeStride::SubObjectRangeStride(
}
}
-Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutReflection* typeLayout)
+Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(
+ slang::TypeLayoutReflection* typeLayout)
{
typeLayout = _unwrapParameterGroups(typeLayout, m_containerType);
@@ -89,8 +90,7 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
m_samplerRanges.add(r);
break;
- case slang::BindingType::CombinedTextureSampler:
- break;
+ case slang::BindingType::CombinedTextureSampler: break;
case slang::BindingType::MutableTexture:
case slang::BindingType::MutableTypedBuffer:
bindingRangeInfo.baseIndex = m_uavCount;
@@ -98,11 +98,9 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
m_uavRanges.add(r);
break;
- case slang::BindingType::VaryingInput:
- break;
+ case slang::BindingType::VaryingInput: break;
- case slang::BindingType::VaryingOutput:
- break;
+ case slang::BindingType::VaryingOutput: break;
default:
bindingRangeInfo.baseIndex = m_srvCount;
@@ -138,7 +136,9 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
SLANG_ASSERT(descriptorSetIndex == 0);
SlangInt descriptorRangeIndex = typeLayout->getBindingRangeFirstDescriptorRangeIndex(r);
- auto registerOffset = typeLayout->getDescriptorSetDescriptorRangeIndexOffset(descriptorSetIndex, descriptorRangeIndex);
+ auto registerOffset = typeLayout->getDescriptorSetDescriptorRangeIndexOffset(
+ descriptorSetIndex,
+ descriptorRangeIndex);
bindingRangeInfo.registerOffset = (uint32_t)registerOffset;
}
@@ -173,18 +173,18 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
switch (slangBindingType)
{
default:
- {
- // In the case of `ConstantBuffer<X>` or `ParameterBlock<X>`
- // we can construct a layout from the element type directly.
- //
- auto elementTypeLayout = slangLeafTypeLayout->getElementTypeLayout();
- createForElementType(
- m_renderer,
- m_session,
- elementTypeLayout,
- subObjectLayout.writeRef());
- }
- break;
+ {
+ // In the case of `ConstantBuffer<X>` or `ParameterBlock<X>`
+ // we can construct a layout from the element type directly.
+ //
+ auto elementTypeLayout = slangLeafTypeLayout->getElementTypeLayout();
+ createForElementType(
+ m_renderer,
+ m_session,
+ elementTypeLayout,
+ subObjectLayout.writeRef());
+ }
+ break;
case slang::BindingType::ExistentialValue:
// In the case of an interface-type sub-object range, we can only
@@ -207,8 +207,9 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
// increase the size of the ordinary data buffer we need to
// allocate for the parent object.
//
- uint32_t ordinaryDataEnd = subObjectRange.offset.pendingOrdinaryData
- + (uint32_t)bindingRange.count * subObjectRange.stride.pendingOrdinaryData;
+ uint32_t ordinaryDataEnd =
+ subObjectRange.offset.pendingOrdinaryData +
+ (uint32_t)bindingRange.count * subObjectRange.stride.pendingOrdinaryData;
if (ordinaryDataEnd > m_totalOrdinaryDataSize)
{
@@ -225,8 +226,7 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
SlangResult ShaderObjectLayoutImpl::Builder::build(ShaderObjectLayoutImpl** outLayout)
{
- auto layout =
- RefPtr<ShaderObjectLayoutImpl>(new ShaderObjectLayoutImpl());
+ auto layout = RefPtr<ShaderObjectLayoutImpl>(new ShaderObjectLayoutImpl());
SLANG_RETURN_ON_FAIL(layout->_init(this));
returnRefPtrMove(outLayout, layout);
@@ -276,14 +276,17 @@ Result RootShaderObjectLayoutImpl::Builder::build(RootShaderObjectLayoutImpl** o
return SLANG_OK;
}
-void RootShaderObjectLayoutImpl::Builder::addGlobalParams(slang::VariableLayoutReflection* globalsLayout)
+void RootShaderObjectLayoutImpl::Builder::addGlobalParams(
+ slang::VariableLayoutReflection* globalsLayout)
{
setElementTypeLayout(globalsLayout->getTypeLayout());
m_pendingDataOffset = BindingOffset(globalsLayout).pending;
}
void RootShaderObjectLayoutImpl::Builder::addEntryPoint(
- SlangStage stage, ShaderObjectLayoutImpl* entryPointLayout, slang::EntryPointLayout* slangEntryPoint)
+ SlangStage stage,
+ ShaderObjectLayoutImpl* entryPointLayout,
+ slang::EntryPointLayout* slangEntryPoint)
{
EntryPointInfo info;
info.layout = entryPointLayout;
@@ -306,7 +309,10 @@ Result RootShaderObjectLayoutImpl::create(
auto slangEntryPoint = programLayout->getEntryPointByIndex(e);
RefPtr<ShaderObjectLayoutImpl> entryPointLayout;
SLANG_RETURN_ON_FAIL(ShaderObjectLayoutImpl::createForElementType(
- renderer, program->getSession(), slangEntryPoint->getTypeLayout(), entryPointLayout.writeRef()));
+ renderer,
+ program->getSession(),
+ slangEntryPoint->getTypeLayout(),
+ entryPointLayout.writeRef()));
builder.addEntryPoint(slangEntryPoint->getStage(), entryPointLayout, slangEntryPoint);
}
diff --git a/tools/gfx/d3d11/d3d11-shader-object-layout.h b/tools/gfx/d3d11/d3d11-shader-object-layout.h
index e18c91c2e..16cd6c714 100644
--- a/tools/gfx/d3d11/d3d11-shader-object-layout.h
+++ b/tools/gfx/d3d11/d3d11-shader-object-layout.h
@@ -29,31 +29,31 @@ public:
// API, and a shader object layout will store information about those
// ranges in a form that is usable for the D3D11 API:
- /// Information about a logical binding range as reported by Slang reflection
+ /// Information about a logical binding range as reported by Slang reflection
struct BindingRangeInfo
{
- /// The type of bindings in this range
+ /// The type of bindings in this range
slang::BindingType bindingType;
- /// The number of bindings in this range
+ /// The number of bindings in this range
Index count;
- /// The starting index for this range in the appropriate "flat" array in a shader object.
- /// E.g., for a shader resource view range, this would be an index into the `m_srvs` array.
+ /// The starting index for this range in the appropriate "flat" array in a shader object.
+ /// E.g., for a shader resource view range, this would be an index into the `m_srvs` array.
Index baseIndex;
- /// The offset of this binding range from the start of the sub-object
- /// in terms of whatever D3D11 register class it consumes. E.g., for
- /// a `Texture2D` binding range this will represent an offset in
- /// `t` registers.
- ///
+ /// The offset of this binding range from the start of the sub-object
+ /// in terms of whatever D3D11 register class it consumes. E.g., for
+ /// a `Texture2D` binding range this will represent an offset in
+ /// `t` registers.
+ ///
uint32_t registerOffset;
- /// An index into the sub-object array if this binding range is treated
- /// as a sub-object.
+ /// An index into the sub-object array if this binding range is treated
+ /// as a sub-object.
Index subObjectIndex;
- /// Is this binding range specializable, e.g. an existential value or ParameterBlock<IFoo>.
+ /// Is this binding range specializable, e.g. an existential value or ParameterBlock<IFoo>.
bool isSpecializable;
};
@@ -64,43 +64,41 @@ public:
// For that reason we also store pre-computed information about each
// sub-object range.
- /// Offset information for a sub-object range
+ /// Offset information for a sub-object range
struct SubObjectRangeOffset : BindingOffset
{
- SubObjectRangeOffset()
- {}
+ SubObjectRangeOffset() {}
SubObjectRangeOffset(slang::VariableLayoutReflection* varLayout);
- /// The offset for "pending" ordinary data related to this range
+ /// The offset for "pending" ordinary data related to this range
uint32_t pendingOrdinaryData = 0;
};
- /// Stride information for a sub-object range
+ /// Stride information for a sub-object range
struct SubObjectRangeStride : BindingOffset
{
- SubObjectRangeStride()
- {}
+ SubObjectRangeStride() {}
SubObjectRangeStride(slang::TypeLayoutReflection* typeLayout);
- /// The strid for "pending" ordinary data related to this range
+ /// The strid for "pending" ordinary data related to this range
uint32_t pendingOrdinaryData = 0;
};
- /// Information about a logical binding range as reported by Slang reflection
+ /// Information about a logical binding range as reported by Slang reflection
struct SubObjectRangeInfo
{
- /// The index of the binding range that corresponds to this sub-object range
+ /// The index of the binding range that corresponds to this sub-object range
Index bindingRangeIndex;
- /// The layout expected for objects bound to this range (if known)
+ /// The layout expected for objects bound to this range (if known)
RefPtr<ShaderObjectLayoutImpl> layout;
- /// The offset to use when binding the first object in this range
+ /// The offset to use when binding the first object in this range
SubObjectRangeOffset offset;
- /// Stride between consecutive objects in this range
+ /// Stride between consecutive objects in this range
SubObjectRangeStride stride;
};
@@ -109,7 +107,8 @@ public:
public:
Builder(RendererBase* renderer, slang::ISession* session)
: m_renderer(renderer), m_session(session)
- {}
+ {
+ }
RendererBase* m_renderer;
slang::ISession* m_session;
@@ -118,13 +117,13 @@ public:
List<BindingRangeInfo> m_bindingRanges;
List<SubObjectRangeInfo> m_subObjectRanges;
- /// The indices of the binding ranges that represent SRVs
+ /// The indices of the binding ranges that represent SRVs
List<Index> m_srvRanges;
- /// The indices of the binding ranges that represent UAVs
+ /// The indices of the binding ranges that represent UAVs
List<Index> m_uavRanges;
- /// The indices of the binding ranges that represent samplers
+ /// The indices of the binding ranges that represent samplers
List<Index> m_samplerRanges;
Index m_srvCount = 0;
@@ -133,10 +132,10 @@ public:
Index m_subObjectCount = 0;
uint32_t m_totalOrdinaryDataSize = 0;
-
- /// The container type of this shader object. When `m_containerType` is
- /// `StructuredBuffer` or `UnsizedArray`, this shader object represents a collection
- /// instead of a single object.
+
+ /// The container type of this shader object. When `m_containerType` is
+ /// `StructuredBuffer` or `UnsizedArray`, this shader object represents a collection
+ /// instead of a single object.
ShaderObjectContainerType m_containerType = ShaderObjectContainerType::None;
Result setElementTypeLayout(slang::TypeLayoutReflection* typeLayout);
@@ -166,18 +165,15 @@ public:
RendererBase* getRenderer() { return m_renderer; }
- slang::TypeReflection* getType()
- {
- return m_elementTypeLayout->getType();
- }
+ slang::TypeReflection* getType() { return m_elementTypeLayout->getType(); }
- /// Get the indices that represent all the SRV ranges in this type
+ /// Get the indices that represent all the SRV ranges in this type
List<Index> const& getSRVRanges() const { return m_srvRanges; }
- /// Get the indices that reprsent all the UAV ranges in this type
+ /// Get the indices that reprsent all the UAV ranges in this type
List<Index> const& getUAVRanges() const { return m_uavRanges; }
- /// Get the indices that represnet all the sampler ranges in this type
+ /// Get the indices that represnet all the sampler ranges in this type
List<Index> const& getSamplerRanges() const { return m_samplerRanges; }
uint32_t getTotalOrdinaryDataSize() const { return m_totalOrdinaryDataSize; }
@@ -206,10 +202,11 @@ class RootShaderObjectLayoutImpl : public ShaderObjectLayoutImpl
public:
struct EntryPointInfo
{
- RefPtr<ShaderObjectLayoutImpl> layout;
+ RefPtr<ShaderObjectLayoutImpl> layout;
- /// The offset for this entry point's parameters, relative to the starting offset for the program
- BindingOffset offset;
+ /// The offset for this entry point's parameters, relative to the starting offset for the
+ /// program
+ BindingOffset offset;
};
struct Builder : Super::Builder
@@ -221,16 +218,20 @@ public:
: Super::Builder(renderer, program->getSession())
, m_program(program)
, m_programLayout(programLayout)
- {}
+ {
+ }
Result build(RootShaderObjectLayoutImpl** outLayout);
void addGlobalParams(slang::VariableLayoutReflection* globalsLayout);
- void addEntryPoint(SlangStage stage, ShaderObjectLayoutImpl* entryPointLayout, slang::EntryPointLayout* slangEntryPoint);
-
- slang::IComponentType* m_program;
- slang::ProgramLayout* m_programLayout;
- List<EntryPointInfo> m_entryPoints;
- SimpleBindingOffset m_pendingDataOffset;
+ void addEntryPoint(
+ SlangStage stage,
+ ShaderObjectLayoutImpl* entryPointLayout,
+ slang::EntryPointLayout* slangEntryPoint);
+
+ slang::IComponentType* m_program;
+ slang::ProgramLayout* m_programLayout;
+ List<EntryPointInfo> m_entryPoints;
+ SimpleBindingOffset m_pendingDataOffset;
};
EntryPointInfo& getEntryPoint(Index index) { return m_entryPoints[index]; }
@@ -246,13 +247,13 @@ public:
slang::IComponentType* getSlangProgram() const { return m_program; }
slang::ProgramLayout* getSlangProgramLayout() const { return m_programLayout; }
- /// Get the offset at which "pending" shader parameters for this program start
+ /// Get the offset at which "pending" shader parameters for this program start
SimpleBindingOffset const& getPendingDataOffset() const { return m_pendingDataOffset; }
protected:
Result _init(Builder const* builder);
- ComPtr<slang::IComponentType> m_program;
+ ComPtr<slang::IComponentType> m_program;
slang::ProgramLayout* m_programLayout = nullptr;
List<EntryPointInfo> m_entryPoints;
diff --git a/tools/gfx/d3d11/d3d11-shader-object.cpp b/tools/gfx/d3d11/d3d11-shader-object.cpp
index a83b115fa..697d463fb 100644
--- a/tools/gfx/d3d11/d3d11-shader-object.cpp
+++ b/tools/gfx/d3d11/d3d11-shader-object.cpp
@@ -24,7 +24,7 @@ Result ShaderObjectImpl::create(
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setData(ShaderOffset const& inOffset, void const* data, size_t inSize)
+ShaderObjectImpl::setData(ShaderOffset const& inOffset, void const* data, size_t inSize)
{
Index offset = inOffset.uniformOffset;
Index size = inSize;
@@ -54,7 +54,7 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView* resourceView)
+ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView* resourceView)
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
@@ -67,17 +67,20 @@ SLANG_NO_THROW Result SLANG_MCALL
if (D3DUtil::isUAVBinding(bindingRange.bindingType))
{
SLANG_ASSERT(resourceViewImpl->m_type == ResourceViewImpl::Type::UAV);
- m_uavs[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<UnorderedAccessViewImpl*>(resourceView);
+ m_uavs[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<UnorderedAccessViewImpl*>(resourceView);
}
else
{
SLANG_ASSERT(resourceViewImpl->m_type == ResourceViewImpl::Type::SRV);
- m_srvs[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<ShaderResourceViewImpl*>(resourceView);
+ m_srvs[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<ShaderResourceViewImpl*>(resourceView);
}
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* sampler)
+SLANG_NO_THROW Result SLANG_MCALL
+ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* sampler)
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
@@ -86,7 +89,8 @@ SLANG_NO_THROW Result SLANG_MCALL ShaderObjectImpl::setSampler(ShaderOffset cons
return SLANG_E_INVALID_ARG;
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
- m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<SamplerStateImpl*>(sampler);
+ m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<SamplerStateImpl*>(sampler);
return SLANG_OK;
}
@@ -152,7 +156,7 @@ Result ShaderObjectImpl::init(IDevice* device, ShaderObjectLayoutImpl* layout)
Result ShaderObjectImpl::_writeOrdinaryData(
void* dest,
- size_t destSize,
+ size_t destSize,
ShaderObjectLayoutImpl* specializedLayout)
{
// We start by simply writing in the ordinary data contained directly in this object.
@@ -180,7 +184,8 @@ Result ShaderObjectImpl::_writeOrdinaryData(
for (auto const& subObjectRangeInfo : specializedLayout->getSubObjectRanges())
{
Index subObjectRangeIndex = subObjectRangeCounter++;
- auto const& bindingRangeInfo = specializedLayout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
+ auto const& bindingRangeInfo =
+ specializedLayout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
// We only need to handle sub-object ranges for interface/existential-type fields,
// because fields of constant-buffer or parameter-block type are responsible for
@@ -234,11 +239,15 @@ Result ShaderObjectImpl::_writeOrdinaryData(
RefPtr<ShaderObjectLayoutImpl> subObjectLayout;
SLANG_RETURN_ON_FAIL(subObject->_getSpecializedLayout(subObjectLayout.writeRef()));
- auto subObjectOffset = subObjectRangePendingDataOffset + i * subObjectRangePendingDataStride;
+ auto subObjectOffset =
+ subObjectRangePendingDataOffset + i * subObjectRangePendingDataStride;
auto subObjectDest = (char*)dest + subObjectOffset;
- subObject->_writeOrdinaryData(subObjectDest, destSize - subObjectOffset, subObjectLayout);
+ subObject->_writeOrdinaryData(
+ subObjectDest,
+ destSize - subObjectOffset,
+ subObjectLayout);
}
}
@@ -280,7 +289,8 @@ Result ShaderObjectImpl::_ensureOrdinaryDataBufferCreatedIfNeeded(
//
auto ordinaryData = device->map(m_ordinaryDataBuffer, gfx::MapFlavor::WriteDiscard);
- auto result = _writeOrdinaryData(ordinaryData, specializedOrdinaryDataSize, specializedLayout);
+ auto result =
+ _writeOrdinaryData(ordinaryData, specializedOrdinaryDataSize, specializedLayout);
device->unmap(m_ordinaryDataBuffer, 0, specializedOrdinaryDataSize);
m_isConstantBufferDirty = false;
return result;
@@ -295,7 +305,8 @@ Result ShaderObjectImpl::_bindOrdinaryDataBufferIfNeeded(
{
// We start by ensuring that the buffer is created, if it is needed.
//
- SLANG_RETURN_ON_FAIL(_ensureOrdinaryDataBufferCreatedIfNeeded(context->device, specializedLayout));
+ SLANG_RETURN_ON_FAIL(
+ _ensureOrdinaryDataBufferCreatedIfNeeded(context->device, specializedLayout));
// If we did indeed need/create a buffer, then we must bind it
// into root binding state.
@@ -319,7 +330,8 @@ Result ShaderObjectImpl::bindAsConstantBuffer(
// resources and sub-objects.
//
BindingOffset offset = inOffset;
- SLANG_RETURN_ON_FAIL(_bindOrdinaryDataBufferIfNeeded(context, /*inout*/ offset, specializedLayout));
+ SLANG_RETURN_ON_FAIL(
+ _bindOrdinaryDataBufferIfNeeded(context, /*inout*/ offset, specializedLayout));
// Once the ordinary data buffer is bound, we can move on to binding
// the rest of the state, which can use logic shared with the case
@@ -403,7 +415,8 @@ Result ShaderObjectImpl::bindAsValue(
for (auto const& subObjectRange : specializedLayout->getSubObjectRanges())
{
auto subObjectLayout = subObjectRange.layout;
- auto const& bindingRange = specializedLayout->getBindingRange(subObjectRange.bindingRangeIndex);
+ auto const& bindingRange =
+ specializedLayout->getBindingRange(subObjectRange.bindingRangeIndex);
Index count = bindingRange.count;
Index subObjectIndex = bindingRange.subObjectIndex;
@@ -425,21 +438,21 @@ Result ShaderObjectImpl::bindAsValue(
//
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ParameterBlock:
- {
- BindingOffset objOffset = rangeOffset;
- for (Index i = 0; i < count; ++i)
{
- auto subObject = m_objects[subObjectIndex + i];
+ BindingOffset objOffset = rangeOffset;
+ for (Index i = 0; i < count; ++i)
+ {
+ auto subObject = m_objects[subObjectIndex + i];
- // Unsurprisingly, we bind each object in the range as
- // a constant buffer.
- //
- subObject->bindAsConstantBuffer(context, objOffset, subObjectLayout);
+ // Unsurprisingly, we bind each object in the range as
+ // a constant buffer.
+ //
+ subObject->bindAsConstantBuffer(context, objOffset, subObjectLayout);
- objOffset += rangeStride;
+ objOffset += rangeStride;
+ }
}
- }
- break;
+ break;
case slang::BindingType::ExistentialValue:
// We can only bind information for existential-typed sub-object
@@ -465,8 +478,7 @@ Result ShaderObjectImpl::bindAsValue(
}
break;
- default:
- break;
+ default: break;
}
}
@@ -552,7 +564,10 @@ Result RootShaderObjectImpl::bindAsRoot(
// really be querying an appropriate absolute offset from `specializedLayout`.
//
BindingOffset ordinaryDataBufferOffset = offset;
- SLANG_RETURN_ON_FAIL(_bindOrdinaryDataBufferIfNeeded(context, /*inout*/ ordinaryDataBufferOffset, specializedLayout));
+ SLANG_RETURN_ON_FAIL(_bindOrdinaryDataBufferIfNeeded(
+ context,
+ /*inout*/ ordinaryDataBufferOffset,
+ specializedLayout));
SLANG_RETURN_ON_FAIL(bindAsValue(context, offset, specializedLayout));
// Once the state stored in the root shader object itself has been bound,
@@ -574,7 +589,8 @@ Result RootShaderObjectImpl::bindAsRoot(
// the absolute offsets as are used for the global scope do not apply
// (because entry points don't need to deal with explicit bindings).
//
- SLANG_RETURN_ON_FAIL(entryPoint->bindAsConstantBuffer(context, entryPointOffset, entryPointInfo.layout));
+ SLANG_RETURN_ON_FAIL(
+ entryPoint->bindAsConstantBuffer(context, entryPointOffset, entryPointInfo.layout));
}
return SLANG_OK;
@@ -652,7 +668,11 @@ Result RootShaderObjectImpl::_createSpecializedLayout(ShaderObjectLayoutImpl** o
auto slangSpecializedLayout = specializedComponentType->getLayout();
RefPtr<RootShaderObjectLayoutImpl> specializedLayout;
- RootShaderObjectLayoutImpl::create(getRenderer(), specializedComponentType, slangSpecializedLayout, specializedLayout.writeRef());
+ RootShaderObjectLayoutImpl::create(
+ getRenderer(),
+ specializedComponentType,
+ slangSpecializedLayout,
+ specializedLayout.writeRef());
// Note: Computing the layout for the specialized program will have also computed
// the layouts for the entry points, and we really need to attach that information
diff --git a/tools/gfx/d3d11/d3d11-shader-object.h b/tools/gfx/d3d11/d3d11-shader-object.h
index b4e43c3ee..62fb4cf62 100644
--- a/tools/gfx/d3d11/d3d11-shader-object.h
+++ b/tools/gfx/d3d11/d3d11-shader-object.h
@@ -1,14 +1,12 @@
// d3d11-shader-object.h
#pragma once
#include "d3d11-base.h"
-
#include "d3d11-buffer.h"
+#include "d3d11-helper-functions.h"
#include "d3d11-resource-views.h"
#include "d3d11-sampler.h"
#include "d3d11-shader-object-layout.h"
-#include "d3d11-helper-functions.h"
-
namespace gfx
{
@@ -18,10 +16,7 @@ namespace d3d11
{
class ShaderObjectImpl
- : public ShaderObjectBaseImpl<
- ShaderObjectImpl,
- ShaderObjectLayoutImpl,
- SimpleShaderObjectData>
+ : public ShaderObjectBaseImpl<ShaderObjectImpl, ShaderObjectLayoutImpl, SimpleShaderObjectData>
{
public:
static Result create(
@@ -51,67 +46,68 @@ public:
}
SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& inOffset, void const* data, size_t inSize) SLANG_OVERRIDE;
+ setData(ShaderOffset const& inOffset, void const* data, size_t inSize) SLANG_OVERRIDE;
SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* resourceView) SLANG_OVERRIDE;
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) SLANG_OVERRIDE;
SLANG_NO_THROW Result SLANG_MCALL setSampler(ShaderOffset const& offset, ISamplerState* sampler)
SLANG_OVERRIDE;
SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) SLANG_OVERRIDE
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) SLANG_OVERRIDE
{
return SLANG_E_NOT_IMPLEMENTED;
}
public:
-
-
protected:
friend class ProgramVars;
Result init(IDevice* device, ShaderObjectLayoutImpl* layout);
- /// Write the uniform/ordinary data of this object into the given `dest` buffer at the given `offset`
+ /// Write the uniform/ordinary data of this object into the given `dest` buffer at the given
+ /// `offset`
Result _writeOrdinaryData(
void* dest,
- size_t destSize,
+ size_t destSize,
ShaderObjectLayoutImpl* specializedLayout);
- /// Ensure that the `m_ordinaryDataBuffer` has been created, if it is needed
- ///
- /// The `specializedLayout` type must represent a specialized layout for this
- /// type that includes any "pending" data.
- ///
+ /// Ensure that the `m_ordinaryDataBuffer` has been created, if it is needed
+ ///
+ /// The `specializedLayout` type must represent a specialized layout for this
+ /// type that includes any "pending" data.
+ ///
Result _ensureOrdinaryDataBufferCreatedIfNeeded(
DeviceImpl* device,
ShaderObjectLayoutImpl* specializedLayout);
- /// Bind the buffer for ordinary/uniform data, if needed
- ///
- /// The `ioOffset` parameter will be updated to reflect the constant buffer
- /// register consumed by the ordinary data buffer, if one was bound.
- ///
+ /// Bind the buffer for ordinary/uniform data, if needed
+ ///
+ /// The `ioOffset` parameter will be updated to reflect the constant buffer
+ /// register consumed by the ordinary data buffer, if one was bound.
+ ///
Result _bindOrdinaryDataBufferIfNeeded(
BindingContext* context,
BindingOffset& ioOffset,
ShaderObjectLayoutImpl* specializedLayout);
public:
- /// Bind this object as if it was declared as a `ConstantBuffer<T>` in Slang
+ /// Bind this object as if it was declared as a `ConstantBuffer<T>` in Slang
Result bindAsConstantBuffer(
BindingContext* context,
BindingOffset const& inOffset,
ShaderObjectLayoutImpl* specializedLayout);
- /// Bind this object as a value that appears in the body of another object.
- ///
- /// This case is directly used when binding an object for an interface-type
- /// sub-object range when static specialization is used. It is also used
- /// indirectly when binding sub-objects to constant buffer or parameter
- /// block ranges.
- ///
+ /// Bind this object as a value that appears in the body of another object.
+ ///
+ /// This case is directly used when binding an object for an interface-type
+ /// sub-object range when static specialization is used. It is also used
+ /// indirectly when binding sub-objects to constant buffer or parameter
+ /// block ranges.
+ ///
Result bindAsValue(
BindingContext* context,
BindingOffset const& offset,
@@ -121,28 +117,28 @@ public:
// and organized as part of each shader object layout,
// the object itself can store its data in a small number
// of simple arrays.
- /// The shader resource views (SRVs) that are part of the state of this object
+ /// The shader resource views (SRVs) that are part of the state of this object
List<RefPtr<ShaderResourceViewImpl>> m_srvs;
- /// The unordered access views (UAVs) that are part of the state of this object
+ /// The unordered access views (UAVs) that are part of the state of this object
List<RefPtr<UnorderedAccessViewImpl>> m_uavs;
- /// The samplers that are part of the state of this object
+ /// The samplers that are part of the state of this object
List<RefPtr<SamplerStateImpl>> m_samplers;
- /// A constant buffer used to stored ordinary data for this object
- /// and existential-type sub-objects.
- ///
- /// Created on demand with `_createOrdinaryDataBufferIfNeeded()`
+ /// A constant buffer used to stored ordinary data for this object
+ /// and existential-type sub-objects.
+ ///
+ /// Created on demand with `_createOrdinaryDataBufferIfNeeded()`
RefPtr<BufferResourceImpl> m_ordinaryDataBuffer;
bool m_isConstantBufferDirty = true;
- /// Get the layout of this shader object with specialization arguments considered
- ///
- /// This operation should only be called after the shader object has been
- /// fully filled in and finalized.
- ///
+ /// Get the layout of this shader object with specialization arguments considered
+ ///
+ /// This operation should only be called after the shader object has been
+ /// fully filled in and finalized.
+ ///
Result _getSpecializedLayout(ShaderObjectLayoutImpl** outLayout);
/// Create the layout for this shader object with specialization arguments considered
@@ -155,10 +151,9 @@ public:
};
class MutableShaderObjectImpl
- : public MutableShaderObject<
- MutableShaderObjectImpl,
- ShaderObjectLayoutImpl>
-{};
+ : public MutableShaderObject<MutableShaderObjectImpl, ShaderObjectLayoutImpl>
+{
+};
class RootShaderObjectImpl : public ShaderObjectImpl
{
@@ -168,12 +163,22 @@ public:
virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() override { return 1; }
virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() override { return 1; }
- static Result create(IDevice* device, RootShaderObjectLayoutImpl* layout, RootShaderObjectImpl** outShaderObject);
+ static Result create(
+ IDevice* device,
+ RootShaderObjectLayoutImpl* layout,
+ RootShaderObjectImpl** outShaderObject);
- RootShaderObjectLayoutImpl* getLayout() { return static_cast<RootShaderObjectLayoutImpl*>(m_layout.Ptr()); }
+ RootShaderObjectLayoutImpl* getLayout()
+ {
+ return static_cast<RootShaderObjectLayoutImpl*>(m_layout.Ptr());
+ }
- GfxCount SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE { return (GfxCount)m_entryPoints.getCount(); }
- SlangResult SLANG_MCALL getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) SLANG_OVERRIDE
+ GfxCount SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE
+ {
+ return (GfxCount)m_entryPoints.getCount();
+ }
+ SlangResult SLANG_MCALL getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
+ SLANG_OVERRIDE
{
returnComPtr(outEntryPoint, m_entryPoints[index]);
return SLANG_OK;
@@ -181,10 +186,8 @@ public:
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override;
- /// Bind this object as a root shader object
- Result bindAsRoot(
- BindingContext* context,
- RootShaderObjectLayoutImpl* specializedLayout);
+ /// Bind this object as a root shader object
+ Result bindAsRoot(BindingContext* context, RootShaderObjectLayoutImpl* specializedLayout);
protected:
diff --git a/tools/gfx/d3d11/d3d11-shader-program.cpp b/tools/gfx/d3d11/d3d11-shader-program.cpp
index f957f6353..16f73c984 100644
--- a/tools/gfx/d3d11/d3d11-shader-program.cpp
+++ b/tools/gfx/d3d11/d3d11-shader-program.cpp
@@ -12,6 +12,5 @@ namespace d3d11
{
-
} // namespace d3d11
} // namespace gfx
diff --git a/tools/gfx/d3d11/d3d11-swap-chain.cpp b/tools/gfx/d3d11/d3d11-swap-chain.cpp
index 177fb89dd..8eb8d66d6 100644
--- a/tools/gfx/d3d11/d3d11-swap-chain.cpp
+++ b/tools/gfx/d3d11/d3d11-swap-chain.cpp
@@ -12,7 +12,10 @@ using namespace Slang;
namespace d3d11
{
-Result SwapchainImpl::init(DeviceImpl* renderer, const ISwapchain::Desc& swapchainDesc, WindowHandle window)
+Result SwapchainImpl::init(
+ DeviceImpl* renderer,
+ const ISwapchain::Desc& swapchainDesc,
+ WindowHandle window)
{
m_renderer = renderer;
m_device = renderer->m_device;
diff --git a/tools/gfx/d3d11/d3d11-texture.h b/tools/gfx/d3d11/d3d11-texture.h
index fb88d2b76..81e3b2a82 100644
--- a/tools/gfx/d3d11/d3d11-texture.h
+++ b/tools/gfx/d3d11/d3d11-texture.h
@@ -21,7 +21,6 @@ public:
{
}
ComPtr<ID3D11Resource> m_resource;
-
};
} // namespace d3d11
diff --git a/tools/gfx/d3d11/d3d11-vertex-layout.h b/tools/gfx/d3d11/d3d11-vertex-layout.h
index 9c3f1cd46..1908e8cce 100644
--- a/tools/gfx/d3d11/d3d11-vertex-layout.h
+++ b/tools/gfx/d3d11/d3d11-vertex-layout.h
@@ -11,10 +11,10 @@ using namespace Slang;
namespace d3d11
{
-class InputLayoutImpl: public InputLayoutBase
+class InputLayoutImpl : public InputLayoutBase
{
public:
- ComPtr<ID3D11InputLayout> m_layout;
+ ComPtr<ID3D11InputLayout> m_layout;
List<UINT> m_vertexStreamStrides;
};
diff --git a/tools/gfx/d3d12/d3d12-base.h b/tools/gfx/d3d12/d3d12-base.h
index 0e648f9c4..e67a7226c 100644
--- a/tools/gfx/d3d12/d3d12-base.h
+++ b/tools/gfx/d3d12/d3d12-base.h
@@ -12,8 +12,8 @@
#include "core/slang-blob.h"
#include "core/slang-chunked-list.h"
#include "d3d12-descriptor-heap.h"
-#include "d3d12-resource.h"
#include "d3d12-posix-synchapi.h"
+#include "d3d12-resource.h"
#pragma push_macro("WIN32_LEAN_AND_MEAN")
#pragma push_macro("NOMINMAX")
@@ -35,47 +35,48 @@
#ifndef __ID3D12GraphicsCommandList1_FWD_DEFINED__
// If can't find a definition of CommandList1, just use an empty definition
struct ID3D12GraphicsCommandList1
-{};
+{
+};
#endif
namespace gfx
{
namespace d3d12
{
- class DeviceImpl;
- class BufferResourceImpl;
- class TextureResourceImpl;
- class CommandBufferImpl;
- class PipelineCommandEncoder;
- class ResourceCommandEncoderImpl;
- class ComputeCommandEncoderImpl;
- class RenderCommandEncoderImpl;
- class CommandQueueImpl;
- class FenceImpl;
- class FramebufferLayoutImpl;
- class FramebufferImpl;
- class QueryPoolImpl;
- class PlainBufferProxyQueryPoolImpl;
- class PipelineStateImpl;
- class RenderPassLayoutImpl;
- class ResourceViewInternalImpl;
- class ResourceViewImpl;
- class AccelerationStructureImpl;
- class SamplerStateImpl;
- class ShaderObjectImpl;
- class RootShaderObjectImpl;
- class MutableRootShaderObjectImpl;
- class ShaderObjectLayoutImpl;
- class RootShaderObjectLayoutImpl;
- class ShaderProgramImpl;
- class ShaderTableImpl;
- class SwapChainImpl;
- class TransientResourceHeapImpl;
- class InputLayoutImpl;
+class DeviceImpl;
+class BufferResourceImpl;
+class TextureResourceImpl;
+class CommandBufferImpl;
+class PipelineCommandEncoder;
+class ResourceCommandEncoderImpl;
+class ComputeCommandEncoderImpl;
+class RenderCommandEncoderImpl;
+class CommandQueueImpl;
+class FenceImpl;
+class FramebufferLayoutImpl;
+class FramebufferImpl;
+class QueryPoolImpl;
+class PlainBufferProxyQueryPoolImpl;
+class PipelineStateImpl;
+class RenderPassLayoutImpl;
+class ResourceViewInternalImpl;
+class ResourceViewImpl;
+class AccelerationStructureImpl;
+class SamplerStateImpl;
+class ShaderObjectImpl;
+class RootShaderObjectImpl;
+class MutableRootShaderObjectImpl;
+class ShaderObjectLayoutImpl;
+class RootShaderObjectLayoutImpl;
+class ShaderProgramImpl;
+class ShaderTableImpl;
+class SwapChainImpl;
+class TransientResourceHeapImpl;
+class InputLayoutImpl;
#if SLANG_GFX_HAS_DXR_SUPPORT
- class RayTracingCommandEncoderImpl;
- class RayTracingPipelineStateImpl;
+class RayTracingCommandEncoderImpl;
+class RayTracingPipelineStateImpl;
#endif
-}
-}
+} // namespace d3d12
+} // namespace gfx
diff --git a/tools/gfx/d3d12/d3d12-buffer.cpp b/tools/gfx/d3d12/d3d12-buffer.cpp
index 7d3376607..ee078bb3d 100644
--- a/tools/gfx/d3d12/d3d12-buffer.cpp
+++ b/tools/gfx/d3d12/d3d12-buffer.cpp
@@ -9,9 +9,9 @@ namespace d3d12
using namespace Slang;
BufferResourceImpl::BufferResourceImpl(const Desc& desc)
- : Parent(desc)
- , m_defaultState(D3DUtil::getResourceState(desc.defaultState))
-{}
+ : Parent(desc), m_defaultState(D3DUtil::getResourceState(desc.defaultState))
+{
+}
BufferResourceImpl::~BufferResourceImpl()
{
@@ -50,7 +50,11 @@ Result BufferResourceImpl::getSharedHandle(InteropHandle* outHandle)
auto pResource = m_resource.getResource();
pResource->GetDevice(IID_PPV_ARGS(pDevice.writeRef()));
SLANG_RETURN_ON_FAIL(pDevice->CreateSharedHandle(
- pResource, NULL, GENERIC_ALL, nullptr, (HANDLE*)&outHandle->handleValue));
+ pResource,
+ NULL,
+ GENERIC_ALL,
+ nullptr,
+ (HANDLE*)&outHandle->handleValue));
outHandle->api = InteropHandleAPI::D3D12;
sharedHandle = *outHandle;
return SLANG_OK;
diff --git a/tools/gfx/d3d12/d3d12-buffer.h b/tools/gfx/d3d12/d3d12-buffer.h
index 272969b07..b58426af6 100644
--- a/tools/gfx/d3d12/d3d12-buffer.h
+++ b/tools/gfx/d3d12/d3d12-buffer.h
@@ -20,19 +20,19 @@ public:
~BufferResourceImpl();
D3D12Resource m_resource; ///< The resource in gpu memory, allocated on the correct heap
- ///< relative to the cpu access flag
+ ///< relative to the cpu access flag
D3D12_RESOURCE_STATES m_defaultState;
virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeResourceHandle(InteropHandle* outHandle) override;
+ getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- map(MemoryRange* rangeToRead, void** outPointer) override;
+ map(MemoryRange* rangeToRead, void** outPointer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL unmap(MemoryRange* writtenRange) override;
@@ -41,4 +41,3 @@ public:
} // namespace d3d12
} // namespace gfx
-
diff --git a/tools/gfx/d3d12/d3d12-command-buffer.cpp b/tools/gfx/d3d12/d3d12-command-buffer.cpp
index fb979d3b9..641234a63 100644
--- a/tools/gfx/d3d12/d3d12-command-buffer.cpp
+++ b/tools/gfx/d3d12/d3d12-command-buffer.cpp
@@ -60,7 +60,7 @@ void CommandBufferImpl::init(
reinit();
m_cmdList->QueryInterface<ID3D12GraphicsCommandList6>(m_cmdList6.writeRef());
-if (m_cmdList6)
+ if (m_cmdList6)
{
m_cmdList4 = m_cmdList6;
m_cmdList1 = m_cmdList6;
@@ -84,7 +84,9 @@ void CommandBufferImpl::encodeResourceCommands(IResourceCommandEncoder** outEnco
}
void CommandBufferImpl::encodeRenderCommands(
- IRenderPassLayout* renderPass, IFramebuffer* framebuffer, IRenderCommandEncoder** outEncoder)
+ IRenderPassLayout* renderPass,
+ IFramebuffer* framebuffer,
+ IRenderCommandEncoder** outEncoder)
{
m_renderCommandEncoder.init(
m_renderer,
@@ -107,11 +109,14 @@ void CommandBufferImpl::encodeRayTracingCommands(IRayTracingCommandEncoder** out
m_rayTracingCommandEncoder.init(this);
*outEncoder = &m_rayTracingCommandEncoder;
#else
- * outEncoder = nullptr;
+ *outEncoder = nullptr;
#endif
}
-void CommandBufferImpl::close() { m_cmdList->Close(); }
+void CommandBufferImpl::close()
+{
+ m_cmdList->Close();
+}
} // namespace d3d12
} // namespace gfx
diff --git a/tools/gfx/d3d12/d3d12-command-buffer.h b/tools/gfx/d3d12/d3d12-command-buffer.h
index 1cc6e8850..192be9e2b 100644
--- a/tools/gfx/d3d12/d3d12-command-buffer.h
+++ b/tools/gfx/d3d12/d3d12-command-buffer.h
@@ -2,13 +2,14 @@
#pragma once
#include "d3d12-base.h"
-#include "d3d12-shader-object.h"
#include "d3d12-command-encoder.h"
+#include "d3d12-shader-object.h"
#ifndef __ID3D12GraphicsCommandList1_FWD_DEFINED__
// If can't find a definition of CommandList1, just use an empty definition
struct ID3D12GraphicsCommandList1
-{};
+{
+};
#endif
namespace gfx
@@ -18,9 +19,7 @@ namespace d3d12
using namespace Slang;
-class CommandBufferImpl
- : public ICommandBufferD3D12
- , public ComObject
+class CommandBufferImpl : public ICommandBufferD3D12, public ComObject
{
public:
// There are a pair of cyclic references between a `TransientResourceHeap` and
@@ -28,7 +27,7 @@ public:
// the public reference count of a command buffer dropping to 0.
SLANG_COM_OBJECT_IUNKNOWN_ALL
- ICommandBufferD3D12* getInterface(const Guid& guid);
+ ICommandBufferD3D12* getInterface(const Guid& guid);
virtual void comFree() override { m_transientHeap.breakStrongReference(); }
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* handle) override;
@@ -49,8 +48,14 @@ public:
void bindDescriptorHeaps();
- virtual SLANG_NO_THROW void SLANG_MCALL invalidateDescriptorHeapBinding() override { m_descriptorHeapsBound = false; }
- virtual SLANG_NO_THROW void SLANG_MCALL ensureInternalDescriptorHeapsBound() override { bindDescriptorHeaps(); }
+ virtual SLANG_NO_THROW void SLANG_MCALL invalidateDescriptorHeapBinding() override
+ {
+ m_descriptorHeapsBound = false;
+ }
+ virtual SLANG_NO_THROW void SLANG_MCALL ensureInternalDescriptorHeapsBound() override
+ {
+ bindDescriptorHeaps();
+ }
void reinit();
@@ -62,7 +67,7 @@ public:
ResourceCommandEncoderImpl m_resourceCommandEncoder;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
+ encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
RenderCommandEncoderImpl m_renderCommandEncoder;
virtual SLANG_NO_THROW void SLANG_MCALL encodeRenderCommands(
@@ -72,13 +77,13 @@ public:
ComputeCommandEncoderImpl m_computeCommandEncoder;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
+ encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
#if SLANG_GFX_HAS_DXR_SUPPORT
RayTracingCommandEncoderImpl m_rayTracingCommandEncoder;
#endif
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
+ encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL close() override;
};
diff --git a/tools/gfx/d3d12/d3d12-command-encoder.cpp b/tools/gfx/d3d12/d3d12-command-encoder.cpp
index 892c792fb..f0b4b0dfc 100644
--- a/tools/gfx/d3d12/d3d12-command-encoder.cpp
+++ b/tools/gfx/d3d12/d3d12-command-encoder.cpp
@@ -3,17 +3,16 @@
#include "d3d12-command-buffer.h"
#include "d3d12-device.h"
+#include "d3d12-helper-functions.h"
#include "d3d12-pipeline-state.h"
#include "d3d12-query.h"
#include "d3d12-shader-object.h"
#include "d3d12-shader-program.h"
#include "d3d12-shader-table.h"
-#include "d3d12-transient-heap.h"
#include "d3d12-texture.h"
+#include "d3d12-transient-heap.h"
#include "d3d12-vertex-layout.h"
-#include "d3d12-helper-functions.h"
-
namespace gfx
{
namespace d3d12
@@ -25,15 +24,10 @@ int PipelineCommandEncoder::getBindPointIndex(PipelineType type)
{
switch (type)
{
- case PipelineType::Graphics:
- return 0;
- case PipelineType::Compute:
- return 1;
- case PipelineType::RayTracing:
- return 2;
- default:
- assert(!"unknown pipeline type.");
- return -1;
+ case PipelineType::Graphics: return 0;
+ case PipelineType::Compute: return 1;
+ case PipelineType::RayTracing: return 2;
+ default: assert(!"unknown pipeline type."); return -1;
}
}
@@ -48,7 +42,8 @@ void PipelineCommandEncoder::init(CommandBufferImpl* commandBuffer)
}
Result PipelineCommandEncoder::bindPipelineImpl(
- IPipelineState* pipelineState, IShaderObject** outRootObject)
+ IPipelineState* pipelineState,
+ IShaderObject** outRootObject)
{
m_currentPipeline = static_cast<PipelineStateBase*>(pipelineState);
auto rootObject = &m_commandBuffer->m_rootShaderObject;
@@ -63,7 +58,8 @@ Result PipelineCommandEncoder::bindPipelineImpl(
}
Result PipelineCommandEncoder::bindPipelineWithRootObjectImpl(
- IPipelineState* pipelineState, IShaderObject* rootObject)
+ IPipelineState* pipelineState,
+ IShaderObject* rootObject)
{
m_currentPipeline = static_cast<PipelineStateBase*>(pipelineState);
m_commandBuffer->m_mutableRootShaderObject =
@@ -73,11 +69,12 @@ Result PipelineCommandEncoder::bindPipelineWithRootObjectImpl(
}
Result PipelineCommandEncoder::_bindRenderState(
- Submitter* submitter, RefPtr<PipelineStateBase>& newPipeline)
+ Submitter* submitter,
+ RefPtr<PipelineStateBase>& newPipeline)
{
RootShaderObjectImpl* rootObjectImpl = m_commandBuffer->m_mutableRootShaderObject
- ? m_commandBuffer->m_mutableRootShaderObject.Ptr()
- : &m_commandBuffer->m_rootShaderObject;
+ ? m_commandBuffer->m_mutableRootShaderObject.Ptr()
+ : &m_commandBuffer->m_rootShaderObject;
SLANG_RETURN_ON_FAIL(
m_renderer->maybeSpecializePipeline(m_currentPipeline, rootObjectImpl, newPipeline));
PipelineStateBase* newPipelineImpl = static_cast<PipelineStateBase*>(newPipeline.Ptr());
@@ -127,9 +124,7 @@ Result PipelineCommandEncoder::_bindRenderState(
d3dheap = m_transientHeap->getCurrentSamplerHeap().getHeap();
m_commandBuffer->bindDescriptorHeaps();
break;
- default:
- assert(!"shouldn't be here");
- return SLANG_FAIL;
+ default: assert(!"shouldn't be here"); return SLANG_FAIL;
}
// Try again.
@@ -140,7 +135,10 @@ Result PipelineCommandEncoder::_bindRenderState(
}
void ResourceCommandEncoderImpl::bufferBarrier(
- GfxCount count, IBufferResource* const* buffers, ResourceState src, ResourceState dst)
+ GfxCount count,
+ IBufferResource* const* buffers,
+ ResourceState src,
+ ResourceState dst)
{
ShortList<D3D12_RESOURCE_BARRIER, 16> barriers;
for (GfxIndex i = 0; i < count; i++)
@@ -150,8 +148,8 @@ void ResourceCommandEncoderImpl::bufferBarrier(
D3D12_RESOURCE_BARRIER barrier = {};
// If the src == dst, it must be a UAV barrier.
barrier.Type = (src == dst && dst == ResourceState::UnorderedAccess)
- ? D3D12_RESOURCE_BARRIER_TYPE_UAV
- : D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ ? D3D12_RESOURCE_BARRIER_TYPE_UAV
+ : D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
if (barrier.Type == D3D12_RESOURCE_BARRIER_TYPE_UAV)
@@ -172,7 +170,8 @@ void ResourceCommandEncoderImpl::bufferBarrier(
if (barriers.getCount())
{
m_commandBuffer->m_cmdList4->ResourceBarrier(
- (UINT)barriers.getCount(), barriers.getArrayView().getBuffer());
+ (UINT)barriers.getCount(),
+ barriers.getArrayView().getBuffer());
}
}
@@ -199,7 +198,8 @@ void ResourceCommandEncoderImpl::copyTexture(
srcSubresource.layerCount == 0 && srcSubresource.mipLevelCount == 0)
{
m_commandBuffer->m_cmdList->CopyResource(
- dstTexture->m_resource.getResource(), srcTexture->m_resource.getResource());
+ dstTexture->m_resource.getResource(),
+ srcTexture->m_resource.getResource());
return;
}
@@ -246,7 +246,12 @@ void ResourceCommandEncoderImpl::copyTexture(
srcBox.back = srcBox.front + extent.depth;
m_commandBuffer->m_cmdList->CopyTextureRegion(
- &dstRegion, dstOffset.x, dstOffset.y, dstOffset.z, &srcRegion, &srcBox);
+ &dstRegion,
+ dstOffset.x,
+ dstOffset.y,
+ dstOffset.z,
+ &srcRegion,
+ &srcBox);
}
}
}
@@ -314,7 +319,7 @@ void ResourceCommandEncoderImpl::uploadTextureData(
footprint.Footprint.Depth = Math::Max(1, (textureSize.depth >> mipLevel)) - offset.z;
}
auto rowSize = (footprint.Footprint.Width + formatInfo.blockWidth - 1) /
- formatInfo.blockWidth * formatInfo.blockSizeInBytes;
+ formatInfo.blockWidth * formatInfo.blockSizeInBytes;
auto rowCount =
(footprint.Footprint.Height + formatInfo.blockHeight - 1) / formatInfo.blockHeight;
footprint.Footprint.RowPitch =
@@ -325,11 +330,15 @@ void ResourceCommandEncoderImpl::uploadTextureData(
IBufferResource* stagingBuffer;
Offset stagingBufferOffset = 0;
m_commandBuffer->m_transientHeap->allocateStagingBuffer(
- bufferSize, stagingBuffer, stagingBufferOffset, MemoryType::Upload, true);
+ bufferSize,
+ stagingBuffer,
+ stagingBufferOffset,
+ MemoryType::Upload,
+ true);
assert(stagingBufferOffset == 0);
BufferResourceImpl* bufferImpl = static_cast<BufferResourceImpl*>(stagingBuffer);
uint8_t* bufferData = nullptr;
- D3D12_RANGE mapRange = { 0, 0 };
+ D3D12_RANGE mapRange = {0, 0};
bufferImpl->m_resource.getResource()->Map(0, &mapRange, (void**)&bufferData);
for (uint32_t z = 0; z < footprint.Footprint.Depth; z++)
{
@@ -345,13 +354,15 @@ void ResourceCommandEncoderImpl::uploadTextureData(
}
bufferImpl->m_resource.getResource()->Unmap(0, nullptr);
srcRegion.pResource = bufferImpl->m_resource.getResource();
- m_commandBuffer->m_cmdList->CopyTextureRegion(
- &dstRegion, offset.x, offset.y, offset.z, &srcRegion, nullptr);
+ m_commandBuffer->m_cmdList
+ ->CopyTextureRegion(&dstRegion, offset.x, offset.y, offset.z, &srcRegion, nullptr);
}
}
void ResourceCommandEncoderImpl::clearResourceView(
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags)
+ IResourceView* view,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags)
{
auto viewImpl = static_cast<ResourceViewImpl*>(view);
m_commandBuffer->bindDescriptorHeaps();
@@ -359,86 +370,93 @@ void ResourceCommandEncoderImpl::clearResourceView(
{
case IResourceView::Type::RenderTarget:
m_commandBuffer->m_cmdList->ClearRenderTargetView(
- viewImpl->m_descriptor.cpuHandle, clearValue->color.floatValues, 0, nullptr);
- break;
- case IResourceView::Type::DepthStencil:
- {
- D3D12_CLEAR_FLAGS clearFlags = (D3D12_CLEAR_FLAGS)0;
- if (flags & ClearResourceViewFlags::ClearDepth)
- {
- clearFlags |= D3D12_CLEAR_FLAG_DEPTH;
- }
- if (flags & ClearResourceViewFlags::ClearStencil)
- {
- clearFlags |= D3D12_CLEAR_FLAG_STENCIL;
- }
- m_commandBuffer->m_cmdList->ClearDepthStencilView(
viewImpl->m_descriptor.cpuHandle,
- clearFlags,
- clearValue->depthStencil.depth,
- (UINT8)clearValue->depthStencil.stencil,
+ clearValue->color.floatValues,
0,
nullptr);
break;
- }
- case IResourceView::Type::UnorderedAccess:
- {
- ID3D12Resource* d3dResource = nullptr;
- D3D12Descriptor descriptor = viewImpl->m_descriptor;
- switch (viewImpl->m_resource->getType())
- {
- case IResource::Type::Buffer:
- d3dResource = static_cast<BufferResourceImpl*>(viewImpl->m_resource.Ptr())
- ->m_resource.getResource();
- // D3D12 requires a UAV descriptor with zero buffer stride for calling ClearUnorderedAccessViewUint/Float.
- viewImpl->getBufferDescriptorForBinding(m_commandBuffer->m_renderer, viewImpl, 0, descriptor);
- break;
- default:
- d3dResource = static_cast<TextureResourceImpl*>(viewImpl->m_resource.Ptr())
- ->m_resource.getResource();
- break;
- }
- auto gpuHandleIndex =
- m_commandBuffer->m_transientHeap->getCurrentViewHeap().allocate(1);
- if (gpuHandleIndex == -1)
- {
- m_commandBuffer->m_transientHeap->allocateNewViewDescriptorHeap(
- m_commandBuffer->m_renderer);
- gpuHandleIndex = m_commandBuffer->m_transientHeap->getCurrentViewHeap().allocate(1);
- m_commandBuffer->bindDescriptorHeaps();
- }
- this->m_commandBuffer->m_renderer->m_device->CopyDescriptorsSimple(
- 1,
- m_commandBuffer->m_transientHeap->getCurrentViewHeap().getCpuHandle(gpuHandleIndex),
- descriptor.cpuHandle,
- D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
-
- if (flags & ClearResourceViewFlags::FloatClearValues)
+ case IResourceView::Type::DepthStencil:
{
- m_commandBuffer->m_cmdList->ClearUnorderedAccessViewFloat(
- m_commandBuffer->m_transientHeap->getCurrentViewHeap().getGpuHandle(
- gpuHandleIndex),
- descriptor.cpuHandle,
- d3dResource,
- clearValue->color.floatValues,
+ D3D12_CLEAR_FLAGS clearFlags = (D3D12_CLEAR_FLAGS)0;
+ if (flags & ClearResourceViewFlags::ClearDepth)
+ {
+ clearFlags |= D3D12_CLEAR_FLAG_DEPTH;
+ }
+ if (flags & ClearResourceViewFlags::ClearStencil)
+ {
+ clearFlags |= D3D12_CLEAR_FLAG_STENCIL;
+ }
+ m_commandBuffer->m_cmdList->ClearDepthStencilView(
+ viewImpl->m_descriptor.cpuHandle,
+ clearFlags,
+ clearValue->depthStencil.depth,
+ (UINT8)clearValue->depthStencil.stencil,
0,
nullptr);
+ break;
}
- else
+ case IResourceView::Type::UnorderedAccess:
{
- m_commandBuffer->m_cmdList->ClearUnorderedAccessViewUint(
- m_commandBuffer->m_transientHeap->getCurrentViewHeap().getGpuHandle(
- gpuHandleIndex),
+ ID3D12Resource* d3dResource = nullptr;
+ D3D12Descriptor descriptor = viewImpl->m_descriptor;
+ switch (viewImpl->m_resource->getType())
+ {
+ case IResource::Type::Buffer:
+ d3dResource = static_cast<BufferResourceImpl*>(viewImpl->m_resource.Ptr())
+ ->m_resource.getResource();
+ // D3D12 requires a UAV descriptor with zero buffer stride for calling
+ // ClearUnorderedAccessViewUint/Float.
+ viewImpl->getBufferDescriptorForBinding(
+ m_commandBuffer->m_renderer,
+ viewImpl,
+ 0,
+ descriptor);
+ break;
+ default:
+ d3dResource = static_cast<TextureResourceImpl*>(viewImpl->m_resource.Ptr())
+ ->m_resource.getResource();
+ break;
+ }
+ auto gpuHandleIndex =
+ m_commandBuffer->m_transientHeap->getCurrentViewHeap().allocate(1);
+ if (gpuHandleIndex == -1)
+ {
+ m_commandBuffer->m_transientHeap->allocateNewViewDescriptorHeap(
+ m_commandBuffer->m_renderer);
+ gpuHandleIndex = m_commandBuffer->m_transientHeap->getCurrentViewHeap().allocate(1);
+ m_commandBuffer->bindDescriptorHeaps();
+ }
+ this->m_commandBuffer->m_renderer->m_device->CopyDescriptorsSimple(
+ 1,
+ m_commandBuffer->m_transientHeap->getCurrentViewHeap().getCpuHandle(gpuHandleIndex),
descriptor.cpuHandle,
- d3dResource,
- clearValue->color.uintValues,
- 0,
- nullptr);
+ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+
+ if (flags & ClearResourceViewFlags::FloatClearValues)
+ {
+ m_commandBuffer->m_cmdList->ClearUnorderedAccessViewFloat(
+ m_commandBuffer->m_transientHeap->getCurrentViewHeap().getGpuHandle(
+ gpuHandleIndex),
+ descriptor.cpuHandle,
+ d3dResource,
+ clearValue->color.floatValues,
+ 0,
+ nullptr);
+ }
+ else
+ {
+ m_commandBuffer->m_cmdList->ClearUnorderedAccessViewUint(
+ m_commandBuffer->m_transientHeap->getCurrentViewHeap().getGpuHandle(
+ gpuHandleIndex),
+ descriptor.cpuHandle,
+ d3dResource,
+ clearValue->color.uintValues,
+ 0,
+ nullptr);
+ }
+ break;
}
- break;
- }
- default:
- break;
+ default: break;
}
}
@@ -485,7 +503,11 @@ void ResourceCommandEncoderImpl::resolveResource(
}
void ResourceCommandEncoderImpl::resolveQuery(
- IQueryPool* queryPool, GfxIndex index, GfxCount count, IBufferResource* buffer, Offset offset)
+ IQueryPool* queryPool,
+ GfxIndex index,
+ GfxCount count,
+ IBufferResource* buffer,
+ Offset offset)
{
auto queryBase = static_cast<QueryPoolBase*>(queryPool);
switch (queryBase->m_desc.type)
@@ -493,45 +515,45 @@ void ResourceCommandEncoderImpl::resolveQuery(
case QueryType::AccelerationStructureCompactedSize:
case QueryType::AccelerationStructureCurrentSize:
case QueryType::AccelerationStructureSerializedSize:
- {
- auto queryPoolImpl = static_cast<PlainBufferProxyQueryPoolImpl*>(queryPool);
- auto bufferImpl = static_cast<BufferResourceImpl*>(buffer);
- auto srcQueryBuffer = queryPoolImpl->m_bufferResource->m_resource.getResource();
+ {
+ auto queryPoolImpl = static_cast<PlainBufferProxyQueryPoolImpl*>(queryPool);
+ auto bufferImpl = static_cast<BufferResourceImpl*>(buffer);
+ auto srcQueryBuffer = queryPoolImpl->m_bufferResource->m_resource.getResource();
- D3D12_RESOURCE_BARRIER barrier = {};
- barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
- barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
- barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
- barrier.Transition.pResource = srcQueryBuffer;
- m_commandBuffer->m_cmdList->ResourceBarrier(1, &barrier);
-
- m_commandBuffer->m_cmdList->CopyBufferRegion(
- bufferImpl->m_resource.getResource(),
- (uint64_t)offset,
- srcQueryBuffer,
- index * sizeof(uint64_t),
- count * sizeof(uint64_t));
+ D3D12_RESOURCE_BARRIER barrier = {};
+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
+ barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
+ barrier.Transition.pResource = srcQueryBuffer;
+ m_commandBuffer->m_cmdList->ResourceBarrier(1, &barrier);
+
+ m_commandBuffer->m_cmdList->CopyBufferRegion(
+ bufferImpl->m_resource.getResource(),
+ (uint64_t)offset,
+ srcQueryBuffer,
+ index * sizeof(uint64_t),
+ count * sizeof(uint64_t));
- barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
- barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE;
- barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
- barrier.Transition.pResource = srcQueryBuffer;
- m_commandBuffer->m_cmdList->ResourceBarrier(1, &barrier);
- }
- break;
+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE;
+ barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
+ barrier.Transition.pResource = srcQueryBuffer;
+ m_commandBuffer->m_cmdList->ResourceBarrier(1, &barrier);
+ }
+ break;
default:
- {
- auto queryPoolImpl = static_cast<QueryPoolImpl*>(queryPool);
- auto bufferImpl = static_cast<BufferResourceImpl*>(buffer);
- m_commandBuffer->m_cmdList->ResolveQueryData(
- queryPoolImpl->m_queryHeap.get(),
- queryPoolImpl->m_queryType,
- index,
- count,
- bufferImpl->m_resource.getResource(),
- offset);
- }
- break;
+ {
+ auto queryPoolImpl = static_cast<QueryPoolImpl*>(queryPool);
+ auto bufferImpl = static_cast<BufferResourceImpl*>(buffer);
+ m_commandBuffer->m_cmdList->ResolveQueryData(
+ queryPoolImpl->m_queryHeap.get(),
+ queryPoolImpl->m_queryType,
+ index,
+ count,
+ bufferImpl->m_resource.getResource(),
+ offset);
+ }
+ break;
}
}
@@ -680,7 +702,8 @@ void ResourceCommandEncoderImpl::textureSubresourceBarrier(
}
}
m_commandBuffer->m_cmdList->ResourceBarrier(
- (UINT)barriers.getCount(), barriers.getArrayView().getBuffer());
+ (UINT)barriers.getCount(),
+ barriers.getArrayView().getBuffer());
}
void ResourceCommandEncoderImpl::beginDebugEvent(const char* name, float rgbColor[3])
@@ -691,7 +714,7 @@ void ResourceCommandEncoderImpl::beginDebugEvent(const char* name, float rgbColo
beginEvent(
m_commandBuffer->m_cmdList,
0xff000000 | (uint8_t(rgbColor[0] * 255.0f) << 16) |
- (uint8_t(rgbColor[1] * 255.0f) << 8) | uint8_t(rgbColor[2] * 255.0f),
+ (uint8_t(rgbColor[1] * 255.0f) << 8) | uint8_t(rgbColor[2] * 255.0f),
name);
}
}
@@ -706,7 +729,11 @@ void ResourceCommandEncoderImpl::endDebugEvent()
}
void ResourceCommandEncoderImpl::copyBuffer(
- IBufferResource* dst, Offset dstOffset, IBufferResource* src, Offset srcOffset, Size size)
+ IBufferResource* dst,
+ Offset dstOffset,
+ IBufferResource* src,
+ Offset srcOffset,
+ Size size)
{
auto dstBuffer = static_cast<BufferResourceImpl*>(dst);
auto srcBuffer = static_cast<BufferResourceImpl*>(src);
@@ -720,7 +747,10 @@ void ResourceCommandEncoderImpl::copyBuffer(
}
void ResourceCommandEncoderImpl::uploadBufferData(
- IBufferResource* dst, Offset offset, Size size, void* data)
+ IBufferResource* dst,
+ Offset offset,
+ Size size,
+ void* data)
{
uploadBufferDataImpl(
m_commandBuffer->m_renderer->m_device,
@@ -733,7 +763,10 @@ void ResourceCommandEncoderImpl::uploadBufferData(
}
void ResourceCommandEncoderImpl::textureBarrier(
- GfxCount count, ITextureResource* const* textures, ResourceState src, ResourceState dst)
+ GfxCount count,
+ ITextureResource* const* textures,
+ ResourceState src,
+ ResourceState dst)
{
ShortList<D3D12_RESOURCE_BARRIER> barriers;
@@ -769,7 +802,8 @@ void ResourceCommandEncoderImpl::textureBarrier(
if (barriers.getCount())
{
m_commandBuffer->m_cmdList->ResourceBarrier(
- (UINT)barriers.getCount(), barriers.getArrayView().getBuffer());
+ (UINT)barriers.getCount(),
+ barriers.getArrayView().getBuffer());
}
}
@@ -832,7 +866,9 @@ void RenderCommandEncoderImpl::init(
initialState = D3DUtil::getResourceState(access.initialState);
}
textureResource->m_resource.transition(
- initialState, D3D12_RESOURCE_STATE_RENDER_TARGET, submitter);
+ initialState,
+ D3D12_RESOURCE_STATE_RENDER_TARGET,
+ submitter);
}
}
}
@@ -866,7 +902,9 @@ void RenderCommandEncoderImpl::init(
D3DUtil::getResourceState(renderPass->m_depthStencilAccess.initialState);
}
textureResource->m_resource.transition(
- initialState, D3D12_RESOURCE_STATE_DEPTH_WRITE, submitter);
+ initialState,
+ D3D12_RESOURCE_STATE_DEPTH_WRITE,
+ submitter);
}
// Clear.
uint32_t clearFlags = 0;
@@ -898,7 +936,8 @@ Result RenderCommandEncoderImpl::bindPipeline(IPipelineState* state, IShaderObje
}
Result RenderCommandEncoderImpl::bindPipelineWithRootObject(
- IPipelineState* state, IShaderObject* rootObject)
+ IPipelineState* state,
+ IShaderObject* rootObject)
{
return bindPipelineWithRootObjectImpl(state, rootObject);
}
@@ -972,7 +1011,9 @@ void RenderCommandEncoderImpl::setVertexBuffers(
}
void RenderCommandEncoderImpl::setIndexBuffer(
- IBufferResource* buffer, Format indexFormat, Offset offset)
+ IBufferResource* buffer,
+ Format indexFormat,
+ Offset offset)
{
m_boundIndexBuffer = (BufferResourceImpl*)buffer;
m_boundIndexFormat = D3DUtil::getMapFormat(indexFormat);
@@ -1045,10 +1086,17 @@ Result RenderCommandEncoderImpl::draw(GfxCount vertexCount, GfxIndex startVertex
}
Result RenderCommandEncoderImpl::drawIndexed(
- GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex)
+ GfxCount indexCount,
+ GfxIndex startIndex,
+ GfxIndex baseVertex)
{
SLANG_RETURN_ON_FAIL(prepareDraw());
- m_d3dCmdList->DrawIndexedInstanced((uint32_t)indexCount, 1, (uint32_t)startIndex, (uint32_t)baseVertex, 0);
+ m_d3dCmdList->DrawIndexedInstanced(
+ (uint32_t)indexCount,
+ 1,
+ (uint32_t)startIndex,
+ (uint32_t)baseVertex,
+ 0);
return SLANG_OK;
}
@@ -1146,12 +1194,16 @@ Result RenderCommandEncoderImpl::drawIndexedIndirect(
}
Result RenderCommandEncoderImpl::setSamplePositions(
- GfxCount samplesPerPixel, GfxCount pixelCount, const SamplePosition* samplePositions)
+ GfxCount samplesPerPixel,
+ GfxCount pixelCount,
+ const SamplePosition* samplePositions)
{
if (m_commandBuffer->m_cmdList1)
{
m_commandBuffer->m_cmdList1->SetSamplePositions(
- (uint32_t)samplesPerPixel, (uint32_t)pixelCount, (D3D12_SAMPLE_POSITION*)samplePositions);
+ (uint32_t)samplesPerPixel,
+ (uint32_t)pixelCount,
+ (D3D12_SAMPLE_POSITION*)samplePositions);
return SLANG_OK;
}
return SLANG_E_NOT_AVAILABLE;
@@ -1196,10 +1248,15 @@ Result RenderCommandEncoderImpl::drawMeshTasks(int x, int y, int z)
return SLANG_OK;
}
-void ComputeCommandEncoderImpl::endEncoding() { PipelineCommandEncoder::endEncodingImpl(); }
+void ComputeCommandEncoderImpl::endEncoding()
+{
+ PipelineCommandEncoder::endEncodingImpl();
+}
void ComputeCommandEncoderImpl::init(
- DeviceImpl* renderer, TransientResourceHeapImpl* transientHeap, CommandBufferImpl* cmdBuffer)
+ DeviceImpl* renderer,
+ TransientResourceHeapImpl* transientHeap,
+ CommandBufferImpl* cmdBuffer)
{
PipelineCommandEncoder::init(cmdBuffer);
m_preCmdList = nullptr;
@@ -1213,7 +1270,8 @@ Result ComputeCommandEncoderImpl::bindPipeline(IPipelineState* state, IShaderObj
}
Result ComputeCommandEncoderImpl::bindPipelineWithRootObject(
- IPipelineState* state, IShaderObject* rootObject)
+ IPipelineState* state,
+ IShaderObject* rootObject)
{
return bindPipelineWithRootObjectImpl(state, rootObject);
}
@@ -1241,7 +1299,12 @@ Result ComputeCommandEncoderImpl::dispatchComputeIndirect(IBufferResource* argBu
auto argBufferImpl = static_cast<BufferResourceImpl*>(argBuffer);
m_d3dCmdList->ExecuteIndirect(
- m_renderer->dispatchIndirectCmdSignature, 1, argBufferImpl->m_resource, (uint64_t)offset, nullptr, 0);
+ m_renderer->dispatchIndirectCmdSignature,
+ 1,
+ argBufferImpl->m_resource,
+ (uint64_t)offset,
+ nullptr,
+ 0);
return SLANG_OK;
}
@@ -1278,11 +1341,15 @@ void RayTracingCommandEncoderImpl::buildAccelerationStructure(
List<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC> postBuildInfoDescs;
translatePostBuildInfoDescs(propertyQueryCount, queryDescs, postBuildInfoDescs);
m_commandBuffer->m_cmdList4->BuildRaytracingAccelerationStructure(
- &buildDesc, (UINT)propertyQueryCount, postBuildInfoDescs.getBuffer());
+ &buildDesc,
+ (UINT)propertyQueryCount,
+ postBuildInfoDescs.getBuffer());
}
void RayTracingCommandEncoderImpl::copyAccelerationStructure(
- IAccelerationStructure* dest, IAccelerationStructure* src, AccelerationStructureCopyMode mode)
+ IAccelerationStructure* dest,
+ IAccelerationStructure* src,
+ AccelerationStructureCopyMode mode)
{
auto destASImpl = static_cast<AccelerationStructureImpl*>(dest);
auto srcASImpl = static_cast<AccelerationStructureImpl*>(src);
@@ -1303,7 +1370,9 @@ void RayTracingCommandEncoderImpl::copyAccelerationStructure(
return;
}
m_commandBuffer->m_cmdList4->CopyRaytracingAccelerationStructure(
- destASImpl->getDeviceAddress(), srcASImpl->getDeviceAddress(), copyMode);
+ destASImpl->getDeviceAddress(),
+ srcASImpl->getDeviceAddress(),
+ copyMode);
}
void RayTracingCommandEncoderImpl::queryAccelerationStructureProperties(
@@ -1319,11 +1388,14 @@ void RayTracingCommandEncoderImpl::queryAccelerationStructureProperties(
asAddresses[i] = accelerationStructures[i]->getDeviceAddress();
translatePostBuildInfoDescs(queryCount, queryDescs, postBuildInfoDescs);
m_commandBuffer->m_cmdList4->EmitRaytracingAccelerationStructurePostbuildInfo(
- postBuildInfoDescs.getBuffer(), (UINT)accelerationStructureCount, asAddresses.getBuffer());
+ postBuildInfoDescs.getBuffer(),
+ (UINT)accelerationStructureCount,
+ asAddresses.getBuffer());
}
void RayTracingCommandEncoderImpl::serializeAccelerationStructure(
- DeviceAddress dest, IAccelerationStructure* src)
+ DeviceAddress dest,
+ IAccelerationStructure* src)
{
auto srcASImpl = static_cast<AccelerationStructureImpl*>(src);
m_commandBuffer->m_cmdList4->CopyRaytracingAccelerationStructure(
@@ -1333,7 +1405,8 @@ void RayTracingCommandEncoderImpl::serializeAccelerationStructure(
}
void RayTracingCommandEncoderImpl::deserializeAccelerationStructure(
- IAccelerationStructure* dest, DeviceAddress source)
+ IAccelerationStructure* dest,
+ DeviceAddress source)
{
auto destASImpl = static_cast<AccelerationStructureImpl*>(dest);
m_commandBuffer->m_cmdList4->CopyRaytracingAccelerationStructure(
@@ -1343,7 +1416,8 @@ void RayTracingCommandEncoderImpl::deserializeAccelerationStructure(
}
Result RayTracingCommandEncoderImpl::bindPipeline(
- IPipelineState* state, IShaderObject** outRootObject)
+ IPipelineState* state,
+ IShaderObject** outRootObject)
{
return bindPipelineImpl(state, outRootObject);
}
@@ -1362,9 +1436,9 @@ Result RayTracingCommandEncoderImpl::dispatchRays(
{
ID3D12GraphicsCommandList4* m_cmdList4;
RayTracingSubmitter(ID3D12GraphicsCommandList4* cmdList4)
- : ComputeSubmitter(cmdList4)
- , m_cmdList4(cmdList4)
- {}
+ : ComputeSubmitter(cmdList4), m_cmdList4(cmdList4)
+ {
+ }
virtual void setPipelineState(PipelineStateBase* pipeline) override
{
auto pipelineImpl = static_cast<RayTracingPipelineStateImpl*>(pipeline);
@@ -1380,15 +1454,17 @@ Result RayTracingCommandEncoderImpl::dispatchRays(
auto shaderTableImpl = static_cast<ShaderTableImpl*>(shaderTable);
- auto shaderTableBuffer =
- shaderTableImpl->getOrCreateBuffer(pipelineImpl, m_transientHeap, static_cast<ResourceCommandEncoderImpl*>(this));
+ auto shaderTableBuffer = shaderTableImpl->getOrCreateBuffer(
+ pipelineImpl,
+ m_transientHeap,
+ static_cast<ResourceCommandEncoderImpl*>(this));
auto shaderTableAddr = shaderTableBuffer->getDeviceAddress();
D3D12_DISPATCH_RAYS_DESC dispatchDesc = {};
- dispatchDesc.RayGenerationShaderRecord.StartAddress =
- shaderTableAddr + shaderTableImpl->m_rayGenTableOffset +
- rayGenShaderIndex * kRayGenRecordSize;
+ dispatchDesc.RayGenerationShaderRecord.StartAddress = shaderTableAddr +
+ shaderTableImpl->m_rayGenTableOffset +
+ rayGenShaderIndex * kRayGenRecordSize;
dispatchDesc.RayGenerationShaderRecord.SizeInBytes = D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES;
if (shaderTableImpl->m_missShaderCount > 0)
diff --git a/tools/gfx/d3d12/d3d12-command-encoder.h b/tools/gfx/d3d12/d3d12-command-encoder.h
index 034749946..513c7c994 100644
--- a/tools/gfx/d3d12/d3d12-command-encoder.h
+++ b/tools/gfx/d3d12/d3d12-command-encoder.h
@@ -48,9 +48,7 @@ public:
Result _bindRenderState(Submitter* submitter, RefPtr<PipelineStateBase>& newPipeline);
};
-class ResourceCommandEncoderImpl
- : public IResourceCommandEncoder
- , public PipelineCommandEncoder
+class ResourceCommandEncoderImpl : public IResourceCommandEncoder, public PipelineCommandEncoder
{
public:
virtual void* getInterface(SlangUUID const& uuid)
@@ -60,7 +58,7 @@ public:
return nullptr;
}
virtual SLANG_NO_THROW SlangResult SLANG_MCALL
- queryInterface(SlangUUID const& uuid, void** outObject) override
+ queryInterface(SlangUUID const& uuid, void** outObject) override
{
if (auto ptr = getInterface(uuid))
{
@@ -79,7 +77,7 @@ public:
Offset srcOffset,
Size size) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- uploadBufferData(IBufferResource* dst, Offset offset, Size size, void* data) override;
+ uploadBufferData(IBufferResource* dst, Offset offset, Size size, void* data) override;
virtual SLANG_NO_THROW void SLANG_MCALL textureBarrier(
GfxCount count,
ITextureResource* const* textures,
@@ -92,7 +90,7 @@ public:
ResourceState dst) override;
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override {}
virtual SLANG_NO_THROW void SLANG_MCALL
- writeTimestamp(IQueryPool* pool, GfxIndex index) override;
+ writeTimestamp(IQueryPool* pool, GfxIndex index) override;
virtual SLANG_NO_THROW void SLANG_MCALL copyTexture(
ITextureResource* dst,
ResourceState dstState,
@@ -113,7 +111,9 @@ public:
GfxCount subResourceDataCount) override;
virtual SLANG_NO_THROW void SLANG_MCALL clearResourceView(
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags) override;
+ IResourceView* view,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags) override;
virtual SLANG_NO_THROW void SLANG_MCALL resolveResource(
ITextureResource* source,
@@ -148,19 +148,18 @@ public:
ResourceState dst) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- beginDebugEvent(const char* name, float rgbColor[3]) override;
+ beginDebugEvent(const char* name, float rgbColor[3]) override;
virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent() override;
};
-class ComputeCommandEncoderImpl
- : public IComputeCommandEncoder
- , public ResourceCommandEncoderImpl
+class ComputeCommandEncoderImpl : public IComputeCommandEncoder, public ResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoderImpl)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IComputeCommandEncoder ||
+ uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
return this;
return nullptr;
}
@@ -173,15 +172,15 @@ public:
CommandBufferImpl* cmdBuffer);
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL dispatchCompute(int x, int y, int z) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override;
+ dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override;
};
struct BoundVertexBuffer
@@ -190,15 +189,14 @@ struct BoundVertexBuffer
int m_offset;
};
-class RenderCommandEncoderImpl
- : public IRenderCommandEncoder
- , public ResourceCommandEncoderImpl
+class RenderCommandEncoderImpl : public IRenderCommandEncoder, public ResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoderImpl)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IRenderCommandEncoder ||
+ uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
return this;
return nullptr;
}
@@ -228,19 +226,19 @@ public:
FramebufferImpl* framebuffer);
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setViewports(GfxCount count, const Viewport* viewports) override;
+ setViewports(GfxCount count, const Viewport* viewports) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setScissorRects(GfxCount count, const ScissorRect* rects) override;
+ setScissorRects(GfxCount count, const ScissorRect* rects) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setPrimitiveTopology(PrimitiveTopology topology) override;
+ setPrimitiveTopology(PrimitiveTopology topology) override;
virtual SLANG_NO_THROW void SLANG_MCALL setVertexBuffers(
GfxIndex startSlot,
@@ -249,13 +247,13 @@ public:
const Offset* offsets) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) override;
+ setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) override;
Result prepareDraw();
virtual SLANG_NO_THROW Result SLANG_MCALL
- draw(GfxCount vertexCount, GfxIndex startVertex = 0) override;
+ draw(GfxCount vertexCount, GfxIndex startVertex = 0) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override;
+ drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override;
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW void SLANG_MCALL setStencilReference(uint32_t referenceValue) override;
@@ -292,20 +290,19 @@ public:
GfxIndex baseVertexLocation,
GfxIndex startInstanceLocation) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL
- drawMeshTasks(int x, int y, int z) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL drawMeshTasks(int x, int y, int z) override;
};
#if SLANG_GFX_HAS_DXR_SUPPORT
-class RayTracingCommandEncoderImpl
- : public IRayTracingCommandEncoder
- , public ResourceCommandEncoderImpl
+class RayTracingCommandEncoderImpl : public IRayTracingCommandEncoder,
+ public ResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoderImpl)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IRayTracingCommandEncoder || uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IRayTracingCommandEncoder ||
+ uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
return this;
return nullptr;
}
@@ -325,13 +322,13 @@ public:
GfxCount queryCount,
AccelerationStructureQueryDesc* queryDescs) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure* source) override;
- virtual SLANG_NO_THROW void SLANG_MCALL deserializeAccelerationStructure(
- IAccelerationStructure* dest, DeviceAddress source) override;
+ serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure* source) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ deserializeAccelerationStructure(IAccelerationStructure* dest, DeviceAddress source) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override
{
return bindPipelineWithRootObjectImpl(state, rootObject);
}
diff --git a/tools/gfx/d3d12/d3d12-command-queue.cpp b/tools/gfx/d3d12/d3d12-command-queue.cpp
index d0c567b13..a856c0633 100644
--- a/tools/gfx/d3d12/d3d12-command-queue.cpp
+++ b/tools/gfx/d3d12/d3d12-command-queue.cpp
@@ -24,7 +24,10 @@ Result CommandQueueImpl::init(DeviceImpl* device, uint32_t queueIndex)
SLANG_RETURN_ON_FAIL(
m_device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(m_fence.writeRef())));
globalWaitHandle = CreateEventEx(
- nullptr, nullptr, CREATE_EVENT_INITIAL_SET | CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
+ nullptr,
+ nullptr,
+ CREATE_EVENT_INITIAL_SET | CREATE_EVENT_MANUAL_RESET,
+ EVENT_ALL_ACCESS);
return SLANG_OK;
}
@@ -36,7 +39,10 @@ CommandQueueImpl::~CommandQueueImpl()
}
void CommandQueueImpl::executeCommandBuffers(
- GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal)
+ GfxCount count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal)
{
ShortList<ID3D12CommandList*> commandLists;
for (GfxCount i = 0; i < count; i++)
@@ -80,7 +86,9 @@ void CommandQueueImpl::waitOnHost()
}
Result CommandQueueImpl::waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* waitValues)
{
for (GfxCount i = 0; i < fenceCount; ++i)
{
@@ -90,7 +98,10 @@ Result CommandQueueImpl::waitForFenceValuesOnDevice(
return SLANG_OK;
}
-const CommandQueueImpl::Desc& CommandQueueImpl::getDesc() { return m_desc; }
+const CommandQueueImpl::Desc& CommandQueueImpl::getDesc()
+{
+ return m_desc;
+}
ICommandQueue* CommandQueueImpl::getInterface(const Guid& guid)
{
diff --git a/tools/gfx/d3d12/d3d12-command-queue.h b/tools/gfx/d3d12/d3d12-command-queue.h
index f11df5894..dadb85d17 100644
--- a/tools/gfx/d3d12/d3d12-command-queue.h
+++ b/tools/gfx/d3d12/d3d12-command-queue.h
@@ -10,13 +10,11 @@ namespace d3d12
using namespace Slang;
-class CommandQueueImpl
- : public ICommandQueue
- , public ComObject
+class CommandQueueImpl : public ICommandQueue, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
- ICommandQueue* getInterface(const Guid& guid);
+ ICommandQueue* getInterface(const Guid& guid);
void breakStrongReferenceToDevice() { m_renderer.breakStrongReference(); }
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* handle) override;
@@ -43,8 +41,8 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL waitOnHost() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ waitForFenceValuesOnDevice(GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
};
} // namespace d3d12
diff --git a/tools/gfx/d3d12/d3d12-descriptor-heap.cpp b/tools/gfx/d3d12/d3d12-descriptor-heap.cpp
index b9c0d28ba..d975727f9 100644
--- a/tools/gfx/d3d12/d3d12-descriptor-heap.cpp
+++ b/tools/gfx/d3d12/d3d12-descriptor-heap.cpp
@@ -1,17 +1,20 @@
#include "d3d12-descriptor-heap.h"
-namespace gfx {
+namespace gfx
+{
using namespace Slang;
-D3D12DescriptorHeap::D3D12DescriptorHeap():
- m_totalSize(0),
- m_currentIndex(0),
- m_descriptorSize(0)
+D3D12DescriptorHeap::D3D12DescriptorHeap()
+ : m_totalSize(0), m_currentIndex(0), m_descriptorSize(0)
{
}
-Result D3D12DescriptorHeap::init(ID3D12Device* device, int size, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags)
+Result D3D12DescriptorHeap::init(
+ ID3D12Device* device,
+ int size,
+ D3D12_DESCRIPTOR_HEAP_TYPE type,
+ D3D12_DESCRIPTOR_HEAP_FLAGS flags)
{
m_device = device;
@@ -19,7 +22,8 @@ Result D3D12DescriptorHeap::init(ID3D12Device* device, int size, D3D12_DESCRIPTO
srvHeapDesc.NumDescriptors = size;
srvHeapDesc.Flags = flags;
srvHeapDesc.Type = type;
- SLANG_RETURN_ON_FAIL(device->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(m_heap.writeRef())));
+ SLANG_RETURN_ON_FAIL(
+ device->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(m_heap.writeRef())));
m_descriptorSize = device->GetDescriptorHandleIncrementSize(type);
m_totalSize = size;
@@ -28,7 +32,12 @@ Result D3D12DescriptorHeap::init(ID3D12Device* device, int size, D3D12_DESCRIPTO
return SLANG_OK;
}
-Result D3D12DescriptorHeap::init(ID3D12Device* device, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, int numHandles, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags)
+Result D3D12DescriptorHeap::init(
+ ID3D12Device* device,
+ const D3D12_CPU_DESCRIPTOR_HANDLE* handles,
+ int numHandles,
+ D3D12_DESCRIPTOR_HEAP_TYPE type,
+ D3D12_DESCRIPTOR_HEAP_FLAGS flags)
{
SLANG_RETURN_ON_FAIL(init(device, numHandles, type, flags));
D3D12_CPU_DESCRIPTOR_HANDLE dst = m_heap->GetCPUDescriptorHandleForHeapStart();
@@ -47,4 +56,3 @@ Result D3D12DescriptorHeap::init(ID3D12Device* device, const D3D12_CPU_DESCRIPTO
}
} // namespace gfx
-
diff --git a/tools/gfx/d3d12/d3d12-descriptor-heap.h b/tools/gfx/d3d12/d3d12-descriptor-heap.h
index 6f82a3f42..44d03b5b0 100644
--- a/tools/gfx/d3d12/d3d12-descriptor-heap.h
+++ b/tools/gfx/d3d12/d3d12-descriptor-heap.h
@@ -1,68 +1,86 @@
#pragma once
-#include <dxgi.h>
-#include <d3d12.h>
-
-#include "slang-com-ptr.h"
-#include "core/slang-virtual-object-pool.h"
-#include "core/slang-short-list.h"
#include "core/slang-basic.h"
+#include "core/slang-short-list.h"
+#include "core/slang-virtual-object-pool.h"
+#include "slang-com-ptr.h"
-namespace gfx {
+#include <d3d12.h>
+#include <dxgi.h>
-/*! \brief A simple class to manage an underlying Dx12 Descriptor Heap. Allocations are made linearly in order. It is not possible to free
-individual allocations, but all allocations can be deallocated with 'deallocateAll'. */
+namespace gfx
+{
+
+/*! \brief A simple class to manage an underlying Dx12 Descriptor Heap. Allocations are made
+linearly in order. It is not possible to free individual allocations, but all allocations can be
+deallocated with 'deallocateAll'. */
class D3D12DescriptorHeap
{
public:
typedef D3D12DescriptorHeap ThisType;
- /// Initialize
- Slang::Result init(ID3D12Device* device, int size, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags);
- /// Initialize with an array of handles copying over the representation
- Slang::Result init(ID3D12Device* device, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, int numHandles, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags);
+ /// Initialize
+ Slang::Result init(
+ ID3D12Device* device,
+ int size,
+ D3D12_DESCRIPTOR_HEAP_TYPE type,
+ D3D12_DESCRIPTOR_HEAP_FLAGS flags);
+ /// Initialize with an array of handles copying over the representation
+ Slang::Result init(
+ ID3D12Device* device,
+ const D3D12_CPU_DESCRIPTOR_HANDLE* handles,
+ int numHandles,
+ D3D12_DESCRIPTOR_HEAP_TYPE type,
+ D3D12_DESCRIPTOR_HEAP_FLAGS flags);
- /// Returns the number of slots that have been used
+ /// Returns the number of slots that have been used
SLANG_FORCE_INLINE int getUsedSize() const { return m_currentIndex; }
- /// Get the total amount of descriptors possible on the heap
+ /// Get the total amount of descriptors possible on the heap
SLANG_FORCE_INLINE int getTotalSize() const { return m_totalSize; }
- /// Allocate a descriptor. Returns the index, or -1 if none left.
+ /// Allocate a descriptor. Returns the index, or -1 if none left.
SLANG_FORCE_INLINE int allocate();
- /// Allocate a number of descriptors. Returns the start index (or -1 if not possible)
+ /// Allocate a number of descriptors. Returns the start index (or -1 if not possible)
SLANG_FORCE_INLINE int allocate(int numDescriptors);
- ///
+ ///
SLANG_FORCE_INLINE int placeAt(int index);
- /// Deallocates all allocations, and starts allocation from the start of the underlying heap again
+ /// Deallocates all allocations, and starts allocation from the start of the underlying heap
+ /// again
SLANG_FORCE_INLINE void deallocateAll() { m_currentIndex = 0; }
- /// Get the size of each
+ /// Get the size of each
SLANG_FORCE_INLINE int getDescriptorSize() const { return m_descriptorSize; }
- /// Get the GPU heap start
- SLANG_FORCE_INLINE D3D12_GPU_DESCRIPTOR_HANDLE getGpuStart() const { return m_heap->GetGPUDescriptorHandleForHeapStart(); }
- /// Get the CPU heap start
- SLANG_FORCE_INLINE D3D12_CPU_DESCRIPTOR_HANDLE getCpuStart() const { return m_heap->GetCPUDescriptorHandleForHeapStart(); }
+ /// Get the GPU heap start
+ SLANG_FORCE_INLINE D3D12_GPU_DESCRIPTOR_HANDLE getGpuStart() const
+ {
+ return m_heap->GetGPUDescriptorHandleForHeapStart();
+ }
+ /// Get the CPU heap start
+ SLANG_FORCE_INLINE D3D12_CPU_DESCRIPTOR_HANDLE getCpuStart() const
+ {
+ return m_heap->GetCPUDescriptorHandleForHeapStart();
+ }
- /// Get the GPU handle at the specified index
+ /// Get the GPU handle at the specified index
SLANG_FORCE_INLINE D3D12_GPU_DESCRIPTOR_HANDLE getGpuHandle(int index) const;
- /// Get the CPU handle at the specified index
+ /// Get the CPU handle at the specified index
SLANG_FORCE_INLINE D3D12_CPU_DESCRIPTOR_HANDLE getCpuHandle(int index) const;
- /// Get the underlying heap
+ /// Get the underlying heap
SLANG_FORCE_INLINE ID3D12DescriptorHeap* getHeap() const { return m_heap; }
- /// Ctor
+ /// Ctor
D3D12DescriptorHeap();
protected:
Slang::ComPtr<ID3D12Device> m_device;
- Slang::ComPtr<ID3D12DescriptorHeap> m_heap; ///< The underlying heap being allocated from
- int m_totalSize; ///< Total amount of allocations available on the heap
- int m_currentIndex; ///< The current descriptor
+ Slang::ComPtr<ID3D12DescriptorHeap> m_heap; ///< The underlying heap being allocated from
+ int m_totalSize; ///< Total amount of allocations available on the heap
+ int m_currentIndex; ///< The current descriptor
int m_descriptorSize; ///< The size of each descriptor
D3D12_DESCRIPTOR_HEAP_FLAGS m_heapFlags; ///< The flags of the heap
};
@@ -83,17 +101,21 @@ struct D3D12Descriptor
///
class D3D12GeneralDescriptorHeap : public Slang::RefObject
{
- ID3D12Device* m_device;
- int m_chunkSize;
- D3D12_DESCRIPTOR_HEAP_TYPE m_type;
+ ID3D12Device* m_device;
+ int m_chunkSize;
+ D3D12_DESCRIPTOR_HEAP_TYPE m_type;
- D3D12DescriptorHeap m_heap;
+ D3D12DescriptorHeap m_heap;
Slang::VirtualObjectPool m_allocator;
public:
int getSize() { return m_chunkSize; }
- Slang::Result init(ID3D12Device* device, int chunkSize, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flag)
+ Slang::Result init(
+ ID3D12Device* device,
+ int chunkSize,
+ D3D12_DESCRIPTOR_HEAP_TYPE type,
+ D3D12_DESCRIPTOR_HEAP_FLAGS flag)
{
m_device = device;
m_chunkSize = chunkSize;
@@ -114,17 +136,14 @@ public:
return m_heap.getGpuHandle(index);
}
- int allocate(int count)
- {
- return m_allocator.alloc(count);
- }
+ int allocate(int count) { return m_allocator.alloc(count); }
Slang::Result allocate(D3D12Descriptor* outDescriptor)
{
// TODO: this allocator would take some work to make thread-safe
int index = m_allocator.alloc(1);
- if(index < 0)
+ if (index < 0)
{
assert(!"descriptor allocation failed");
return SLANG_FAIL;
@@ -137,10 +156,7 @@ public:
return SLANG_OK;
}
- void free(int index, int count)
- {
- m_allocator.free(index, count);
- }
+ void free(int index, int count) { m_allocator.free(index, count); }
void free(D3D12Descriptor descriptor)
{
@@ -167,7 +183,8 @@ public:
m_subHeaps.add(subHeap);
if (m_subHeapStartingIndex.getCount())
{
- m_subHeapStartingIndex.add(m_subHeapStartingIndex.getLast() + m_subHeaps.getLast()->getSize());
+ m_subHeapStartingIndex.add(
+ m_subHeapStartingIndex.getLast() + m_subHeaps.getLast()->getSize());
}
else
{
@@ -268,7 +285,6 @@ public:
break;
}
}
-
}
}
};
@@ -344,7 +360,10 @@ struct DescriptorHeapReference
{
enum class Type
{
- Linear, General, ExpandingGeneral, ExpandingLinear
+ Linear,
+ General,
+ ExpandingGeneral,
+ ExpandingLinear
};
union Ptr
{
@@ -380,44 +399,31 @@ struct DescriptorHeapReference
{
switch (type)
{
- case Type::Linear:
- return ptr.linearHeap->getCpuHandle(index);
- case Type::General:
- return ptr.generalHeap->getCpuHandle(index);
- case Type::ExpandingGeneral:
- return ptr.generalExpandingHeap->getCpuHandle(index);
- case Type::ExpandingLinear:
- return ptr.linearExpandingHeap->getCpuHandle(index);
- default:
- return D3D12_CPU_DESCRIPTOR_HANDLE();
+ case Type::Linear: return ptr.linearHeap->getCpuHandle(index);
+ case Type::General: return ptr.generalHeap->getCpuHandle(index);
+ case Type::ExpandingGeneral: return ptr.generalExpandingHeap->getCpuHandle(index);
+ case Type::ExpandingLinear: return ptr.linearExpandingHeap->getCpuHandle(index);
+ default: return D3D12_CPU_DESCRIPTOR_HANDLE();
}
}
D3D12_GPU_DESCRIPTOR_HANDLE getGpuHandle(int index) const
{
switch (type)
{
- case Type::Linear:
- return ptr.linearHeap->getGpuHandle(index);
- case Type::General:
- return ptr.generalHeap->getGpuHandle(index);
- case Type::ExpandingGeneral:
- return ptr.generalExpandingHeap->getGpuHandle(index);
- default:
- return D3D12_GPU_DESCRIPTOR_HANDLE();
+ case Type::Linear: return ptr.linearHeap->getGpuHandle(index);
+ case Type::General: return ptr.generalHeap->getGpuHandle(index);
+ case Type::ExpandingGeneral: return ptr.generalExpandingHeap->getGpuHandle(index);
+ default: return D3D12_GPU_DESCRIPTOR_HANDLE();
}
}
int allocate(int numDescriptors)
{
switch (type)
{
- case Type::Linear:
- return ptr.linearHeap->allocate(numDescriptors);
- case Type::General:
- return ptr.generalHeap->allocate(numDescriptors);
- case Type::ExpandingGeneral:
- return ptr.generalExpandingHeap->allocate(numDescriptors);
- default:
- return ptr.linearExpandingHeap->allocate(numDescriptors);
+ case Type::Linear: return ptr.linearHeap->allocate(numDescriptors);
+ case Type::General: return ptr.generalHeap->allocate(numDescriptors);
+ case Type::ExpandingGeneral: return ptr.generalExpandingHeap->allocate(numDescriptors);
+ default: return ptr.linearExpandingHeap->allocate(numDescriptors);
}
}
void free(int index, int count)
@@ -425,33 +431,28 @@ struct DescriptorHeapReference
switch (type)
{
default:
- case Type::Linear:
- SLANG_ASSERT(!"Linear heap does not support free().");
- break;
- case Type::General:
- return ptr.generalHeap->free(index, count);
- case Type::ExpandingGeneral:
- return ptr.generalExpandingHeap->free(index, count);
+ case Type::Linear: SLANG_ASSERT(!"Linear heap does not support free()."); break;
+ case Type::General: return ptr.generalHeap->free(index, count);
+ case Type::ExpandingGeneral: return ptr.generalExpandingHeap->free(index, count);
}
}
void freeIfSupported(int index, int count)
{
switch (type)
{
- case Type::Linear:
- return;
- case Type::General:
- return ptr.generalHeap->free(index, count);
- case Type::ExpandingGeneral:
- return ptr.generalExpandingHeap->free(index, count);
- default:
- break;
+ case Type::Linear: return;
+ case Type::General: return ptr.generalHeap->free(index, count);
+ case Type::ExpandingGeneral: return ptr.generalExpandingHeap->free(index, count);
+ default: break;
}
}
};
// ---------------------------------------------------------------------------
-int D3D12DescriptorHeap::allocate() { return allocate(1); }
+int D3D12DescriptorHeap::allocate()
+{
+ return allocate(1);
+}
// ---------------------------------------------------------------------------
int D3D12DescriptorHeap::allocate(int numDescriptors)
{
@@ -511,4 +512,3 @@ SLANG_FORCE_INLINE D3D12_GPU_DESCRIPTOR_HANDLE D3D12DescriptorHeap::getGpuHandle
}
} // namespace gfx
-
diff --git a/tools/gfx/d3d12/d3d12-device.cpp b/tools/gfx/d3d12/d3d12-device.cpp
index 09a789ff0..f2b24ab5f 100644
--- a/tools/gfx/d3d12/d3d12-device.cpp
+++ b/tools/gfx/d3d12/d3d12-device.cpp
@@ -5,6 +5,7 @@
#include "d3d12-buffer.h"
#include "d3d12-fence.h"
#include "d3d12-framebuffer.h"
+#include "d3d12-helper-functions.h"
#include "d3d12-pipeline-state.h"
#include "d3d12-query.h"
#include "d3d12-render-pass.h"
@@ -16,22 +17,20 @@
#include "d3d12-swap-chain.h"
#include "d3d12-vertex-layout.h"
-#include "d3d12-helper-functions.h"
-
#ifdef _DEBUG
-# define ENABLE_DEBUG_LAYER 1
+#define ENABLE_DEBUG_LAYER 1
#else
-# define ENABLE_DEBUG_LAYER 0
+#define ENABLE_DEBUG_LAYER 0
#endif
#ifdef GFX_NVAPI
-# include "../nvapi/nvapi-include.h"
+#include "../nvapi/nvapi-include.h"
#endif
#ifdef GFX_NV_AFTERMATH
-# include "GFSDK_Aftermath.h"
-# include "GFSDK_Aftermath_Defines.h"
-# include "GFSDK_Aftermath_GpuCrashDump.h"
+#include "GFSDK_Aftermath.h"
+#include "GFSDK_Aftermath_Defines.h"
+#include "GFSDK_Aftermath_GpuCrashDump.h"
#endif
namespace gfx
@@ -45,9 +44,9 @@ static const uint32_t D3D_FEATURE_LEVEL_12_2 = 0xc200;
#if GFX_NV_AFTERMATH
-/* static */const bool DeviceImpl::g_isAftermathEnabled = true;
+/* static */ const bool DeviceImpl::g_isAftermathEnabled = true;
#else
-/* static */const bool DeviceImpl::g_isAftermathEnabled = false;
+/* static */ const bool DeviceImpl::g_isAftermathEnabled = false;
#endif
struct ShaderModelInfo
@@ -58,10 +57,16 @@ struct ShaderModelInfo
};
// List of shader models. Do not change oldest to newest order.
static ShaderModelInfo kKnownShaderModels[] = {
-#define SHADER_MODEL_INFO_DXBC(major, minor) {D3D_SHADER_MODEL_##major##_##minor, SLANG_DXBC, "sm_" #major "_" #minor }
+#define SHADER_MODEL_INFO_DXBC(major, minor) \
+ { \
+ D3D_SHADER_MODEL_##major##_##minor, SLANG_DXBC, "sm_" #major "_" #minor \
+ }
SHADER_MODEL_INFO_DXBC(5, 1),
#undef SHADER_MODEL_INFO_DXBC
-#define SHADER_MODEL_INFO_DXIL(major, minor) {(D3D_SHADER_MODEL)0x##major##minor, SLANG_DXIL, "sm_" #major "_" #minor }
+#define SHADER_MODEL_INFO_DXIL(major, minor) \
+ { \
+ (D3D_SHADER_MODEL)0x##major##minor, SLANG_DXIL, "sm_" #major "_" #minor \
+ }
SHADER_MODEL_INFO_DXIL(6, 0),
SHADER_MODEL_INFO_DXIL(6, 1),
SHADER_MODEL_INFO_DXIL(6, 2),
@@ -119,8 +124,7 @@ Result DeviceImpl::createBuffer(
if (initialState != D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE)
initialState = D3D12_RESOURCE_STATE_COMMON;
break;
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
}
// Create the resource.
@@ -166,8 +170,8 @@ Result DeviceImpl::createBuffer(
if (memoryType == MemoryType::DeviceLocal)
{
auto encodeInfo = encodeResourceCommands();
- encodeInfo.d3dCommandList->CopyBufferRegion(
- resourceOut, 0, uploadResourceRef, 0, bufferSize);
+ encodeInfo.d3dCommandList
+ ->CopyBufferRegion(resourceOut, 0, uploadResourceRef, 0, bufferSize);
submitResourceCommandsAndWait(encodeInfo);
}
}
@@ -269,7 +273,7 @@ Result DeviceImpl::captureTextureToSurface(
ID3D12Resource* dxResource = stagingResource;
UINT8* data;
- D3D12_RANGE readRange = { 0, bufferSize };
+ D3D12_RANGE readRange = {0, bufferSize};
SLANG_RETURN_ON_FAIL(dxResource->Map(0, &readRange, reinterpret_cast<void**>(&data)));
@@ -320,7 +324,7 @@ Result DeviceImpl::_createDevice(
{
IDXGIAdapter* dxgiAdapter = dxgiAdapters[i];
if (SLANG_SUCCEEDED(
- m_D3D12CreateDevice(dxgiAdapter, featureLevel, IID_PPV_ARGS(device.writeRef()))))
+ m_D3D12CreateDevice(dxgiAdapter, featureLevel, IID_PPV_ARGS(device.writeRef()))))
{
adapter = dxgiAdapter;
break;
@@ -357,7 +361,9 @@ Result DeviceImpl::_createDevice(
D3D12_FEATURE_DATA_SHADER_MODEL featureShaderModel;
featureShaderModel.HighestShaderModel = D3D_SHADER_MODEL_6_3;
SLANG_SUCCEEDED(device->CheckFeatureSupport(
- D3D12_FEATURE_SHADER_MODEL, &featureShaderModel, sizeof(featureShaderModel)));
+ D3D12_FEATURE_SHADER_MODEL,
+ &featureShaderModel,
+ sizeof(featureShaderModel)));
if (featureShaderModel.HighestShaderModel >= D3D_SHADER_MODEL_6_3)
{
@@ -373,7 +379,7 @@ Result DeviceImpl::_createDevice(
};
// We filter INFO messages because they are way too many
- D3D12_MESSAGE_SEVERITY severities[] = { D3D12_MESSAGE_SEVERITY_INFO };
+ D3D12_MESSAGE_SEVERITY severities[] = {D3D12_MESSAGE_SEVERITY_INFO};
D3D12_INFO_QUEUE_FILTER infoQueueFilter = {};
infoQueueFilter.DenyList.NumSeverities = SLANG_COUNT_OF(severities);
@@ -392,23 +398,28 @@ Result DeviceImpl::_createDevice(
if ((deviceCheckFlags & DeviceCheckFlag::UseDebug) && g_isAftermathEnabled)
{
// Initialize Nsight Aftermath for this device.
- // This combination of flags is not necessarily appropraite for real world usage
- const uint32_t aftermathFlags =
- GFSDK_Aftermath_FeatureFlags_EnableMarkers | // Enable event marker tracking.
- GFSDK_Aftermath_FeatureFlags_CallStackCapturing | // Enable automatic call stack event markers.
- GFSDK_Aftermath_FeatureFlags_EnableResourceTracking | // Enable tracking of resources.
- GFSDK_Aftermath_FeatureFlags_GenerateShaderDebugInfo | // Generate debug information for shaders.
- GFSDK_Aftermath_FeatureFlags_EnableShaderErrorReporting; // Enable additional runtime shader error reporting.
-
+ // This combination of flags is not necessarily appropraite for real world usage
+ const uint32_t aftermathFlags =
+ GFSDK_Aftermath_FeatureFlags_EnableMarkers | // Enable event marker tracking.
+ GFSDK_Aftermath_FeatureFlags_CallStackCapturing | // Enable automatic call stack
+ // event markers.
+ GFSDK_Aftermath_FeatureFlags_EnableResourceTracking | // Enable tracking of
+ // resources.
+ GFSDK_Aftermath_FeatureFlags_GenerateShaderDebugInfo | // Generate debug information
+ // for shaders.
+ GFSDK_Aftermath_FeatureFlags_EnableShaderErrorReporting; // Enable additional
+ // runtime shader error
+ // reporting.
+
auto initResult = GFSDK_Aftermath_DX12_Initialize(
GFSDK_Aftermath_Version_API,
aftermathFlags,
device);
-
- if ( initResult != GFSDK_Aftermath_Result_Success)
+
+ if (initResult != GFSDK_Aftermath_Result_Success)
{
SLANG_ASSERT_FAILURE("Unable to initialize aftermath");
- // Unable to initialize
+ // Unable to initialize
return SLANG_FAIL;
}
}
@@ -456,7 +467,9 @@ Result DeviceImpl::initialize(const Desc& desc)
if (SLANG_FAILED(SharedLibrary::load(libName, d3dModule)))
{
getDebugCallback()->handleMessage(
- DebugMessageType::Error, DebugMessageSource::Layer, "error: failed load 'd3d12.dll'\n");
+ DebugMessageType::Error,
+ DebugMessageSource::Layer,
+ "error: failed load 'd3d12.dll'\n");
return SLANG_FAIL;
}
@@ -465,7 +478,7 @@ Result DeviceImpl::initialize(const Desc& desc)
{
StructType stype;
memcpy(&stype, desc.extendedDescs[i], sizeof(stype));
- switch (stype )
+ switch (stype)
{
case StructType::D3D12DeviceExtendedDesc:
memcpy(&m_extendedDesc, desc.extendedDescs[i], sizeof(m_extendedDesc));
@@ -486,7 +499,7 @@ Result DeviceImpl::initialize(const Desc& desc)
m_info.bindingStyle = BindingStyle::DirectX;
m_info.projectionStyle = ProjectionStyle::DirectX;
m_info.apiName = "Direct3D 12";
- static const float kIdentity[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
+ static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
::memcpy(m_info.identityProjectionMatrix, kIdentity, sizeof(kIdentity));
}
@@ -498,8 +511,9 @@ Result DeviceImpl::initialize(const Desc& desc)
return SLANG_FAIL;
}
- m_D3D12SerializeVersionedRootSignature =
- (PFN_D3D12_SERIALIZE_VERSIONED_ROOT_SIGNATURE)loadProc(d3dModule, "D3D12SerializeVersionedRootSignature");
+ m_D3D12SerializeVersionedRootSignature = (PFN_D3D12_SERIALIZE_VERSIONED_ROOT_SIGNATURE)loadProc(
+ d3dModule,
+ "D3D12SerializeVersionedRootSignature");
if (!m_D3D12SerializeVersionedRootSignature)
{
return SLANG_FAIL;
@@ -526,7 +540,7 @@ Result DeviceImpl::initialize(const Desc& desc)
{
if (SLANG_SUCCEEDED(m_D3D12GetDebugInterface(IID_PPV_ARGS(m_dxDebug.writeRef()))))
{
-# if 0
+#if 0
// Can enable for extra validation. NOTE! That d3d12 warns if you do....
// D3D12 MESSAGE : Device Debug Layer Startup Options : GPU - Based Validation is enabled(disabled by default).
// This results in new validation not possible during API calls on the CPU, by creating patched shaders that have validation
@@ -539,7 +553,7 @@ Result DeviceImpl::initialize(const Desc& desc)
{
debug1->SetEnableGPUBasedValidation(true);
}
-# endif
+#endif
}
}
}
@@ -559,7 +573,8 @@ Result DeviceImpl::initialize(const Desc& desc)
if (ENABLE_DEBUG_LAYER || isGfxDebugLayerEnabled())
{
combiner.add(
- DeviceCheckFlag::UseDebug, ChangeType::OnOff); ///< First try debug then non debug
+ DeviceCheckFlag::UseDebug,
+ ChangeType::OnOff); ///< First try debug then non debug
}
else
{
@@ -570,8 +585,7 @@ Result DeviceImpl::initialize(const Desc& desc)
ChangeType::OnOff); ///< First try hardware, then reference
- const D3D_FEATURE_LEVEL featureLevels[] =
- {
+ const D3D_FEATURE_LEVEL featureLevels[] = {
(D3D_FEATURE_LEVEL)D3D_FEATURE_LEVEL_12_2,
D3D_FEATURE_LEVEL_12_1,
D3D_FEATURE_LEVEL_12_0,
@@ -581,24 +595,23 @@ Result DeviceImpl::initialize(const Desc& desc)
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
- D3D_FEATURE_LEVEL_9_1
- };
+ D3D_FEATURE_LEVEL_9_1};
for (auto featureLevel : featureLevels)
{
const int numCombinations = combiner.getNumCombinations();
for (int i = 0; i < numCombinations; ++i)
{
if (SLANG_SUCCEEDED(_createDevice(
- combiner.getCombination(i),
- desc.adapterLUID,
- featureLevel,
- m_deviceInfo)))
+ combiner.getCombination(i),
+ desc.adapterLUID,
+ featureLevel,
+ m_deviceInfo)))
{
goto succ;
}
}
}
- succ:
+ succ:
if (!m_deviceInfo.m_adapter)
{
// Couldn't find an adapter
@@ -669,9 +682,10 @@ Result DeviceImpl::initialize(const Desc& desc)
SLANG_COMPILE_TIME_ASSERT(D3D_SHADER_MODEL_6_0 == 0x60);
{
- // CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL) can fail if the runtime/driver does not yet know the
- // specified highest shader model. Therefore we assemble a list of shader models to check and
- // walk it from highest to lowest to find the supported shader model.
+ // CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL) can fail if the runtime/driver does
+ // not yet know the specified highest shader model. Therefore we assemble a list of
+ // shader models to check and walk it from highest to lowest to find the supported
+ // shader model.
Slang::ShortList<D3D_SHADER_MODEL> shaderModels;
if (m_extendedDesc.highestShaderModel != 0)
shaderModels.add((D3D_SHADER_MODEL)m_extendedDesc.highestShaderModel);
@@ -680,12 +694,16 @@ Result DeviceImpl::initialize(const Desc& desc)
for (D3D_SHADER_MODEL shaderModel : shaderModels)
{
shaderModelData.HighestShaderModel = shaderModel;
- if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &shaderModelData, sizeof(shaderModelData))))
+ if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(
+ D3D12_FEATURE_SHADER_MODEL,
+ &shaderModelData,
+ sizeof(shaderModelData))))
break;
}
// TODO: Currently warp causes a crash when using half, so disable for now
- if (m_deviceInfo.m_isWarp == false && shaderModelData.HighestShaderModel >= D3D_SHADER_MODEL_6_2)
+ if (m_deviceInfo.m_isWarp == false &&
+ shaderModelData.HighestShaderModel >= D3D_SHADER_MODEL_6_2)
{
// With sm_6_2 we have half
m_features.add("half");
@@ -694,7 +712,9 @@ Result DeviceImpl::initialize(const Desc& desc)
{
D3D12_FEATURE_DATA_D3D12_OPTIONS options;
if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(
- D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))))
+ D3D12_FEATURE_D3D12_OPTIONS,
+ &options,
+ sizeof(options))))
{
// Check double precision support
if (options.DoublePrecisionFloatShaderOps)
@@ -728,7 +748,9 @@ Result DeviceImpl::initialize(const Desc& desc)
{
D3D12_FEATURE_DATA_D3D12_OPTIONS1 options;
if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(
- D3D12_FEATURE_D3D12_OPTIONS1, &options, sizeof(options))))
+ D3D12_FEATURE_D3D12_OPTIONS1,
+ &options,
+ sizeof(options))))
{
// Check wave operations support
if (options.WaveOps)
@@ -738,7 +760,9 @@ Result DeviceImpl::initialize(const Desc& desc)
{
D3D12_FEATURE_DATA_D3D12_OPTIONS2 options;
if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(
- D3D12_FEATURE_D3D12_OPTIONS2, &options, sizeof(options))))
+ D3D12_FEATURE_D3D12_OPTIONS2,
+ &options,
+ sizeof(options))))
{
// Check programmable sample positions support
switch (options.ProgrammableSamplePositionsTier)
@@ -750,15 +774,16 @@ Result DeviceImpl::initialize(const Desc& desc)
case D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_1:
m_features.add("programmable-sample-positions-1");
break;
- default:
- break;
+ default: break;
}
}
}
{
D3D12_FEATURE_DATA_D3D12_OPTIONS3 options;
if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(
- D3D12_FEATURE_D3D12_OPTIONS3, &options, sizeof(options))))
+ D3D12_FEATURE_D3D12_OPTIONS3,
+ &options,
+ sizeof(options))))
{
// Check barycentrics support
if (options.BarycentricsSupported)
@@ -771,7 +796,9 @@ Result DeviceImpl::initialize(const Desc& desc)
{
D3D12_FEATURE_DATA_D3D12_OPTIONS5 options;
if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(
- D3D12_FEATURE_D3D12_OPTIONS5, &options, sizeof(options))))
+ D3D12_FEATURE_D3D12_OPTIONS5,
+ &options,
+ sizeof(options))))
{
if (options.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED)
{
@@ -787,7 +814,9 @@ Result DeviceImpl::initialize(const Desc& desc)
{
D3D12_FEATURE_DATA_D3D12_OPTIONS7 options;
if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(
- D3D12_FEATURE_D3D12_OPTIONS7, &options, sizeof(options))))
+ D3D12_FEATURE_D3D12_OPTIONS7,
+ &options,
+ sizeof(options))))
{
if (options.MeshShaderTier >= D3D12_MESH_SHADER_TIER_1)
{
@@ -825,9 +854,12 @@ Result DeviceImpl::initialize(const Desc& desc)
limits.maxComputeThreadGroupSize[0] = D3D12_CS_THREAD_GROUP_MAX_X;
limits.maxComputeThreadGroupSize[1] = D3D12_CS_THREAD_GROUP_MAX_Y;
limits.maxComputeThreadGroupSize[2] = D3D12_CS_THREAD_GROUP_MAX_Z;
- limits.maxComputeDispatchThreadGroups[0] = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
- limits.maxComputeDispatchThreadGroups[1] = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
- limits.maxComputeDispatchThreadGroups[2] = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
+ limits.maxComputeDispatchThreadGroups[0] =
+ D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
+ limits.maxComputeDispatchThreadGroups[1] =
+ D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
+ limits.maxComputeDispatchThreadGroups[2] =
+ D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
limits.maxViewports = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
limits.maxViewportDimensions[0] = D3D12_VIEWPORT_BOUNDS_MAX;
@@ -859,14 +891,23 @@ Result DeviceImpl::initialize(const Desc& desc)
D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
m_cpuSamplerHeap = new D3D12GeneralExpandingDescriptorHeap();
SLANG_RETURN_ON_FAIL(m_cpuSamplerHeap->init(
- m_device, 2048, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
+ m_device,
+ 2048,
+ D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
+ D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
m_rtvAllocator = new D3D12GeneralExpandingDescriptorHeap();
SLANG_RETURN_ON_FAIL(m_rtvAllocator->init(
- m_device, 16 * 1024, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
+ m_device,
+ 16 * 1024,
+ D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
+ D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
m_dsvAllocator = new D3D12GeneralExpandingDescriptorHeap();
SLANG_RETURN_ON_FAIL(m_dsvAllocator->init(
- m_device, 1024, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
+ m_device,
+ 1024,
+ D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
+ D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
ComPtr<IDXGIDevice> dxgiDevice;
if (m_deviceInfo.m_adapter)
@@ -914,7 +955,7 @@ Result DeviceImpl::initialize(const Desc& desc)
desc.extendedDescs,
compileTarget,
profileName,
- makeArray(slang::PreprocessorMacroDesc{ "__D3D12__", "1" }).getView()));
+ makeArray(slang::PreprocessorMacroDesc{"__D3D12__", "1"}).getView()));
// Allocate a D3D12 "command signature" object that matches the behavior
// of a D3D11-style `DrawInstancedIndirect` operation.
@@ -929,7 +970,9 @@ Result DeviceImpl::initialize(const Desc& desc)
desc.NodeMask = 0;
SLANG_RETURN_ON_FAIL(m_device->CreateCommandSignature(
- &desc, nullptr, IID_PPV_ARGS(drawIndirectCmdSignature.writeRef())));
+ &desc,
+ nullptr,
+ IID_PPV_ARGS(drawIndirectCmdSignature.writeRef())));
}
// Allocate a D3D12 "command signature" object that matches the behavior
@@ -945,7 +988,9 @@ Result DeviceImpl::initialize(const Desc& desc)
desc.NodeMask = 0;
SLANG_RETURN_ON_FAIL(m_device->CreateCommandSignature(
- &desc, nullptr, IID_PPV_ARGS(drawIndexedIndirectCmdSignature.writeRef())));
+ &desc,
+ nullptr,
+ IID_PPV_ARGS(drawIndexedIndirectCmdSignature.writeRef())));
}
// Allocate a D3D12 "command signature" object that matches the behavior
@@ -961,14 +1006,17 @@ Result DeviceImpl::initialize(const Desc& desc)
desc.NodeMask = 0;
SLANG_RETURN_ON_FAIL(m_device->CreateCommandSignature(
- &desc, nullptr, IID_PPV_ARGS(dispatchIndirectCmdSignature.writeRef())));
+ &desc,
+ nullptr,
+ IID_PPV_ARGS(dispatchIndirectCmdSignature.writeRef())));
}
m_isInitialized = true;
return SLANG_OK;
}
Result DeviceImpl::createTransientResourceHeap(
- const ITransientResourceHeap::Desc& desc, ITransientResourceHeap** outHeap)
+ const ITransientResourceHeap::Desc& desc,
+ ITransientResourceHeap** outHeap)
{
RefPtr<TransientResourceHeapImpl> heap;
SLANG_RETURN_ON_FAIL(createTransientResourceHeapImpl(
@@ -990,7 +1038,9 @@ Result DeviceImpl::createCommandQueue(const ICommandQueue::Desc& desc, ICommandQ
}
Result DeviceImpl::createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain)
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain)
{
RefPtr<SwapchainImpl> swapchain = new SwapchainImpl();
SLANG_RETURN_ON_FAIL(swapchain->init(this, desc, window));
@@ -1006,11 +1056,17 @@ SlangResult DeviceImpl::readTextureResource(
Size* outPixelSize)
{
return captureTextureToSurface(
- static_cast<TextureResourceImpl*>(resource), state, outBlob, outRowPitch, outPixelSize);
+ static_cast<TextureResourceImpl*>(resource),
+ state,
+ outBlob,
+ outRowPitch,
+ outPixelSize);
}
Result DeviceImpl::getTextureAllocationInfo(
- const ITextureResource::Desc& desc, Size* outSize, Size* outAlignment)
+ const ITextureResource::Desc& desc,
+ Size* outSize,
+ Size* outAlignment)
{
TextureResource::Desc srcDesc = fixupTextureDesc(desc);
D3D12_RESOURCE_DESC resourceDesc = {};
@@ -1069,7 +1125,7 @@ Result DeviceImpl::createTextureResource(
clearValuePtr = &clearValue;
}
if ((resourceDesc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET |
- D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) == 0)
+ D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) == 0)
{
clearValuePtr = nullptr;
}
@@ -1194,8 +1250,8 @@ Result DeviceImpl::createTextureResource(
const uint8_t* srcRow = srcLayer;
uint8_t* dstRow = dstLayer;
int j = gfxIsCompressedFormat(descIn.format)
- ? 4
- : 1; // BC compressed formats are organized into 4x4 blocks
+ ? 4
+ : 1; // BC compressed formats are organized into 4x4 blocks
for (int k = 0; k < mipSize.height; k += j)
{
::memcpy(dstRow, srcRow, (Size)mipRowSize);
@@ -1240,7 +1296,9 @@ Result DeviceImpl::createTextureResource(
{
D3D12BarrierSubmitter submitter(encodeInfo.d3dCommandList);
texture->m_resource.transition(
- D3D12_RESOURCE_STATE_COPY_DEST, texture->m_defaultState, submitter);
+ D3D12_RESOURCE_STATE_COPY_DEST,
+ texture->m_defaultState,
+ submitter);
}
submitResourceCommandsAndWait(encodeInfo);
}
@@ -1250,7 +1308,9 @@ Result DeviceImpl::createTextureResource(
}
Result DeviceImpl::createTextureFromNativeHandle(
- InteropHandle handle, const ITextureResource::Desc& srcDesc, ITextureResource** outResource)
+ InteropHandle handle,
+ const ITextureResource::Desc& srcDesc,
+ ITextureResource** outResource)
{
RefPtr<TextureResourceImpl> texture(new TextureResourceImpl(srcDesc));
@@ -1268,7 +1328,9 @@ Result DeviceImpl::createTextureFromNativeHandle(
}
Result DeviceImpl::createBufferResource(
- const IBufferResource::Desc& descIn, const void* initData, IBufferResource** outResource)
+ const IBufferResource::Desc& descIn,
+ const void* initData,
+ IBufferResource** outResource)
{
BufferResource::Desc srcDesc = fixupBufferDesc(descIn);
@@ -1294,7 +1356,9 @@ Result DeviceImpl::createBufferResource(
}
Result DeviceImpl::createBufferFromNativeHandle(
- InteropHandle handle, const IBufferResource::Desc& srcDesc, IBufferResource** outResource)
+ InteropHandle handle,
+ const IBufferResource::Desc& srcDesc,
+ IBufferResource** outResource)
{
RefPtr<BufferResourceImpl> buffer(new BufferResourceImpl(srcDesc));
@@ -1359,7 +1423,9 @@ Result DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerS
}
Result DeviceImpl::createTextureView(
- ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView)
+ ITextureResource* texture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView)
{
auto resourceImpl = (TextureResourceImpl*)texture;
@@ -1370,242 +1436,246 @@ Result DeviceImpl::createTextureView(
bool isMultiSample = resourceImpl ? resourceImpl->getDesc()->sampleDesc.numSamples > 1 : false;
switch (desc.type)
{
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
case IResourceView::Type::RenderTarget:
- {
- SLANG_RETURN_ON_FAIL(m_rtvAllocator->allocate(&viewImpl->m_descriptor));
- viewImpl->m_allocator = m_rtvAllocator;
- D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
- rtvDesc.Format = D3DUtil::getMapFormat(desc.format);
- switch (desc.renderTarget.shape)
{
- case IResource::Type::Texture1D:
- rtvDesc.ViewDimension = isArray ? D3D12_RTV_DIMENSION_TEXTURE1DARRAY : D3D12_RTV_DIMENSION_TEXTURE1D;
- if(isArray)
- {
- rtvDesc.Texture1DArray.MipSlice = desc.subresourceRange.mipLevel;
- rtvDesc.Texture1DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
- rtvDesc.Texture1DArray.ArraySize = desc.subresourceRange.layerCount;
- }
- else
- {
- rtvDesc.Texture1D.MipSlice = desc.subresourceRange.mipLevel;
- }
-
- break;
- case IResource::Type::Texture2D:
- if (isMultiSample)
+ SLANG_RETURN_ON_FAIL(m_rtvAllocator->allocate(&viewImpl->m_descriptor));
+ viewImpl->m_allocator = m_rtvAllocator;
+ D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
+ rtvDesc.Format = D3DUtil::getMapFormat(desc.format);
+ switch (desc.renderTarget.shape)
{
- rtvDesc.ViewDimension = isArray ? D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY
- : D3D12_RTV_DIMENSION_TEXTURE2DMS;
- rtvDesc.Texture2DMSArray.ArraySize = desc.subresourceRange.layerCount;
- rtvDesc.Texture2DMSArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
- }
- else
- {
- rtvDesc.ViewDimension = isArray ? D3D12_RTV_DIMENSION_TEXTURE2DARRAY
- : D3D12_RTV_DIMENSION_TEXTURE2D;
- if(isArray)
+ case IResource::Type::Texture1D:
+ rtvDesc.ViewDimension =
+ isArray ? D3D12_RTV_DIMENSION_TEXTURE1DARRAY : D3D12_RTV_DIMENSION_TEXTURE1D;
+ if (isArray)
{
- rtvDesc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
- rtvDesc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount;
- rtvDesc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
- rtvDesc.Texture2DArray.PlaneSlice =
- resourceImpl ? D3DUtil::getPlaneSlice(
- D3DUtil::getMapFormat(resourceImpl->getDesc()->format),
- desc.subresourceRange.aspectMask)
- : 0;
+ rtvDesc.Texture1DArray.MipSlice = desc.subresourceRange.mipLevel;
+ rtvDesc.Texture1DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
+ rtvDesc.Texture1DArray.ArraySize = desc.subresourceRange.layerCount;
}
else
{
- rtvDesc.Texture2D.MipSlice = desc.subresourceRange.mipLevel;
- rtvDesc.Texture2D.PlaneSlice =
- resourceImpl ? D3DUtil::getPlaneSlice(
- D3DUtil::getMapFormat(resourceImpl->getDesc()->format),
- desc.subresourceRange.aspectMask)
- : 0;
+ rtvDesc.Texture1D.MipSlice = desc.subresourceRange.mipLevel;
+ }
+
+ break;
+ case IResource::Type::Texture2D:
+ if (isMultiSample)
+ {
+ rtvDesc.ViewDimension = isArray ? D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY
+ : D3D12_RTV_DIMENSION_TEXTURE2DMS;
+ rtvDesc.Texture2DMSArray.ArraySize = desc.subresourceRange.layerCount;
+ rtvDesc.Texture2DMSArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
}
+ else
+ {
+ rtvDesc.ViewDimension = isArray ? D3D12_RTV_DIMENSION_TEXTURE2DARRAY
+ : D3D12_RTV_DIMENSION_TEXTURE2D;
+ if (isArray)
+ {
+ rtvDesc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
+ rtvDesc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount;
+ rtvDesc.Texture2DArray.FirstArraySlice =
+ desc.subresourceRange.baseArrayLayer;
+ rtvDesc.Texture2DArray.PlaneSlice =
+ resourceImpl
+ ? D3DUtil::getPlaneSlice(
+ D3DUtil::getMapFormat(resourceImpl->getDesc()->format),
+ desc.subresourceRange.aspectMask)
+ : 0;
+ }
+ else
+ {
+ rtvDesc.Texture2D.MipSlice = desc.subresourceRange.mipLevel;
+ rtvDesc.Texture2D.PlaneSlice =
+ resourceImpl
+ ? D3DUtil::getPlaneSlice(
+ D3DUtil::getMapFormat(resourceImpl->getDesc()->format),
+ desc.subresourceRange.aspectMask)
+ : 0;
+ }
+ }
+ break;
+ case IResource::Type::TextureCube:
+ rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
+ rtvDesc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
+ rtvDesc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount;
+ rtvDesc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
+ rtvDesc.Texture2DArray.PlaneSlice =
+ resourceImpl ? D3DUtil::getPlaneSlice(
+ D3DUtil::getMapFormat(resourceImpl->getDesc()->format),
+ desc.subresourceRange.aspectMask)
+ : 0;
+ break;
+ case IResource::Type::Texture3D:
+ rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
+ rtvDesc.Texture3D.MipSlice = desc.subresourceRange.mipLevel;
+ rtvDesc.Texture3D.FirstWSlice = desc.subresourceRange.baseArrayLayer;
+ rtvDesc.Texture3D.WSize =
+ (desc.subresourceRange.layerCount == 0) ? -1 : desc.subresourceRange.layerCount;
+ break;
+ case IResource::Type::Buffer: rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_BUFFER; break;
+ default: return SLANG_FAIL;
}
- break;
- case IResource::Type::TextureCube:
- rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
- rtvDesc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
- rtvDesc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount;
- rtvDesc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
- rtvDesc.Texture2DArray.PlaneSlice =
- resourceImpl
- ? D3DUtil::getPlaneSlice(D3DUtil::getMapFormat(resourceImpl->getDesc()->format), desc.subresourceRange.aspectMask)
- : 0;
- break;
- case IResource::Type::Texture3D:
- rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
- rtvDesc.Texture3D.MipSlice = desc.subresourceRange.mipLevel;
- rtvDesc.Texture3D.FirstWSlice = desc.subresourceRange.baseArrayLayer;
- rtvDesc.Texture3D.WSize = (desc.subresourceRange.layerCount == 0) ? -1 : desc.subresourceRange.layerCount;
- break;
- case IResource::Type::Buffer:
- rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_BUFFER;
- break;
- default:
- return SLANG_FAIL;
+ m_device->CreateRenderTargetView(
+ resourceImpl ? resourceImpl->m_resource.getResource() : nullptr,
+ &rtvDesc,
+ viewImpl->m_descriptor.cpuHandle);
}
- m_device->CreateRenderTargetView(
- resourceImpl ? resourceImpl->m_resource.getResource() : nullptr,
- &rtvDesc,
- viewImpl->m_descriptor.cpuHandle);
- }
- break;
+ break;
case IResourceView::Type::DepthStencil:
- {
- SLANG_RETURN_ON_FAIL(m_dsvAllocator->allocate(&viewImpl->m_descriptor));
- viewImpl->m_allocator = m_dsvAllocator;
- D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
- dsvDesc.Format = D3DUtil::getMapFormat(desc.format);
- switch (desc.renderTarget.shape)
{
- case IResource::Type::Texture1D:
- dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D;
- dsvDesc.Texture1D.MipSlice = desc.subresourceRange.mipLevel;
- break;
- case IResource::Type::Texture2D:
- if (isMultiSample)
- {
- dsvDesc.ViewDimension = isArray ? D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY
- : D3D12_DSV_DIMENSION_TEXTURE2DMS;
- dsvDesc.Texture2DMSArray.ArraySize = desc.subresourceRange.layerCount;
- dsvDesc.Texture2DMSArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
- }
- else
+ SLANG_RETURN_ON_FAIL(m_dsvAllocator->allocate(&viewImpl->m_descriptor));
+ viewImpl->m_allocator = m_dsvAllocator;
+ D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
+ dsvDesc.Format = D3DUtil::getMapFormat(desc.format);
+ switch (desc.renderTarget.shape)
{
- dsvDesc.ViewDimension = isArray ? D3D12_DSV_DIMENSION_TEXTURE2DARRAY
- : D3D12_DSV_DIMENSION_TEXTURE2D;
+ case IResource::Type::Texture1D:
+ dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D;
+ dsvDesc.Texture1D.MipSlice = desc.subresourceRange.mipLevel;
+ break;
+ case IResource::Type::Texture2D:
+ if (isMultiSample)
+ {
+ dsvDesc.ViewDimension = isArray ? D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY
+ : D3D12_DSV_DIMENSION_TEXTURE2DMS;
+ dsvDesc.Texture2DMSArray.ArraySize = desc.subresourceRange.layerCount;
+ dsvDesc.Texture2DMSArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
+ }
+ else
+ {
+ dsvDesc.ViewDimension = isArray ? D3D12_DSV_DIMENSION_TEXTURE2DARRAY
+ : D3D12_DSV_DIMENSION_TEXTURE2D;
+ dsvDesc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
+ dsvDesc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount;
+ dsvDesc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
+ }
+ break;
+ case IResource::Type::TextureCube:
+ dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
dsvDesc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
dsvDesc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount;
dsvDesc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
+ break;
+ default: return SLANG_FAIL;
}
- break;
- case IResource::Type::TextureCube:
- dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
- dsvDesc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
- dsvDesc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount;
- dsvDesc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
- break;
- default:
- return SLANG_FAIL;
+ m_device->CreateDepthStencilView(
+ resourceImpl ? resourceImpl->m_resource.getResource() : nullptr,
+ &dsvDesc,
+ viewImpl->m_descriptor.cpuHandle);
}
- m_device->CreateDepthStencilView(
- resourceImpl ? resourceImpl->m_resource.getResource() : nullptr,
- &dsvDesc,
- viewImpl->m_descriptor.cpuHandle);
- }
- break;
+ break;
case IResourceView::Type::UnorderedAccess:
- {
- // TODO: need to support the separate "counter resource" for the case
- // of append/consume buffers with attached counters.
-
- SLANG_RETURN_ON_FAIL(m_cpuViewHeap->allocate(&viewImpl->m_descriptor));
- viewImpl->m_allocator = m_cpuViewHeap;
- D3D12_UNORDERED_ACCESS_VIEW_DESC d3d12desc = {};
- auto& resourceDesc = *resourceImpl->getDesc();
- d3d12desc.Format = gfxIsTypelessFormat(texture->getDesc()->format)
- ? D3DUtil::getMapFormat(desc.format)
- : D3DUtil::getMapFormat(texture->getDesc()->format);
- switch (resourceImpl->getDesc()->type)
{
- case IResource::Type::Texture1D:
- d3d12desc.ViewDimension = isArray
- ? D3D12_UAV_DIMENSION_TEXTURE1DARRAY
- : D3D12_UAV_DIMENSION_TEXTURE1D;
- if(isArray)
- {
- d3d12desc.Texture1DArray.MipSlice = desc.subresourceRange.mipLevel;
- d3d12desc.Texture1DArray.ArraySize = desc.subresourceRange.layerCount == 0
- ? resourceDesc.arraySize
- : desc.subresourceRange.layerCount;
- d3d12desc.Texture1DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
- }
- else
- {
- d3d12desc.Texture1D.MipSlice = desc.subresourceRange.mipLevel;
- }
- break;
- case IResource::Type::Texture2D:
- d3d12desc.ViewDimension = isArray
- ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY
- : D3D12_UAV_DIMENSION_TEXTURE2D;
- if(isArray)
+ // TODO: need to support the separate "counter resource" for the case
+ // of append/consume buffers with attached counters.
+
+ SLANG_RETURN_ON_FAIL(m_cpuViewHeap->allocate(&viewImpl->m_descriptor));
+ viewImpl->m_allocator = m_cpuViewHeap;
+ D3D12_UNORDERED_ACCESS_VIEW_DESC d3d12desc = {};
+ auto& resourceDesc = *resourceImpl->getDesc();
+ d3d12desc.Format = gfxIsTypelessFormat(texture->getDesc()->format)
+ ? D3DUtil::getMapFormat(desc.format)
+ : D3DUtil::getMapFormat(texture->getDesc()->format);
+ switch (resourceImpl->getDesc()->type)
{
+ case IResource::Type::Texture1D:
+ d3d12desc.ViewDimension =
+ isArray ? D3D12_UAV_DIMENSION_TEXTURE1DARRAY : D3D12_UAV_DIMENSION_TEXTURE1D;
+ if (isArray)
+ {
+ d3d12desc.Texture1DArray.MipSlice = desc.subresourceRange.mipLevel;
+ d3d12desc.Texture1DArray.ArraySize = desc.subresourceRange.layerCount == 0
+ ? resourceDesc.arraySize
+ : desc.subresourceRange.layerCount;
+ d3d12desc.Texture1DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
+ }
+ else
+ {
+ d3d12desc.Texture1D.MipSlice = desc.subresourceRange.mipLevel;
+ }
+ break;
+ case IResource::Type::Texture2D:
+ d3d12desc.ViewDimension =
+ isArray ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D;
+ if (isArray)
+ {
+ d3d12desc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
+ d3d12desc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount == 0
+ ? resourceDesc.arraySize
+ : desc.subresourceRange.layerCount;
+ d3d12desc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
+ d3d12desc.Texture2DArray.PlaneSlice =
+ D3DUtil::getPlaneSlice(d3d12desc.Format, desc.subresourceRange.aspectMask);
+ }
+ else
+ {
+ d3d12desc.Texture2D.MipSlice = desc.subresourceRange.mipLevel;
+ d3d12desc.Texture2D.PlaneSlice =
+ D3DUtil::getPlaneSlice(d3d12desc.Format, desc.subresourceRange.aspectMask);
+ }
+ break;
+ case IResource::Type::TextureCube:
+ d3d12desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
d3d12desc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
d3d12desc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount == 0
- ? resourceDesc.arraySize
- : desc.subresourceRange.layerCount;
+ ? resourceDesc.arraySize
+ : desc.subresourceRange.layerCount;
d3d12desc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
d3d12desc.Texture2DArray.PlaneSlice =
D3DUtil::getPlaneSlice(d3d12desc.Format, desc.subresourceRange.aspectMask);
+ break;
+ case IResource::Type::Texture3D:
+ d3d12desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
+ d3d12desc.Texture3D.MipSlice = desc.subresourceRange.mipLevel;
+ d3d12desc.Texture3D.FirstWSlice = desc.subresourceRange.baseArrayLayer;
+ d3d12desc.Texture3D.WSize =
+ resourceDesc.size.depth >> desc.subresourceRange.mipLevel;
+ break;
+ default: return SLANG_FAIL;
}
- else
- {
- d3d12desc.Texture2D.MipSlice = desc.subresourceRange.mipLevel;
- d3d12desc.Texture2D.PlaneSlice =
- D3DUtil::getPlaneSlice(d3d12desc.Format, desc.subresourceRange.aspectMask);
- }
- break;
- case IResource::Type::TextureCube:
- d3d12desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
- d3d12desc.Texture2DArray.MipSlice = desc.subresourceRange.mipLevel;
- d3d12desc.Texture2DArray.ArraySize = desc.subresourceRange.layerCount == 0
- ? resourceDesc.arraySize
- : desc.subresourceRange.layerCount;
- d3d12desc.Texture2DArray.FirstArraySlice = desc.subresourceRange.baseArrayLayer;
- d3d12desc.Texture2DArray.PlaneSlice =
- D3DUtil::getPlaneSlice(d3d12desc.Format, desc.subresourceRange.aspectMask);
- break;
- case IResource::Type::Texture3D:
- d3d12desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
- d3d12desc.Texture3D.MipSlice = desc.subresourceRange.mipLevel;
- d3d12desc.Texture3D.FirstWSlice = desc.subresourceRange.baseArrayLayer;
- d3d12desc.Texture3D.WSize = resourceDesc.size.depth >> desc.subresourceRange.mipLevel;
- break;
- default:
- return SLANG_FAIL;
+ m_device->CreateUnorderedAccessView(
+ resourceImpl->m_resource,
+ nullptr,
+ &d3d12desc,
+ viewImpl->m_descriptor.cpuHandle);
}
- m_device->CreateUnorderedAccessView(
- resourceImpl->m_resource, nullptr, &d3d12desc, viewImpl->m_descriptor.cpuHandle);
- }
- break;
+ break;
case IResourceView::Type::ShaderResource:
- {
- SLANG_RETURN_ON_FAIL(m_cpuViewHeap->allocate(&viewImpl->m_descriptor));
- viewImpl->m_allocator = m_cpuViewHeap;
-
- // Need to construct the D3D12_SHADER_RESOURCE_VIEW_DESC because otherwise TextureCube
- // is not accessed appropriately (rather than just passing nullptr to
- // CreateShaderResourceView)
- const D3D12_RESOURCE_DESC resourceDesc =
- resourceImpl->m_resource.getResource()->GetDesc();
- const DXGI_FORMAT pixelFormat = desc.format == Format::Unknown
- ? resourceDesc.Format
- : D3DUtil::getMapFormat(desc.format);
-
- D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
- initSrvDesc(
- resourceImpl->getType(),
- *resourceImpl->getDesc(),
- resourceDesc,
- pixelFormat,
- desc.subresourceRange,
- srvDesc);
-
- m_device->CreateShaderResourceView(
- resourceImpl->m_resource, &srvDesc, viewImpl->m_descriptor.cpuHandle);
- }
- break;
+ {
+ SLANG_RETURN_ON_FAIL(m_cpuViewHeap->allocate(&viewImpl->m_descriptor));
+ viewImpl->m_allocator = m_cpuViewHeap;
+
+ // Need to construct the D3D12_SHADER_RESOURCE_VIEW_DESC because otherwise TextureCube
+ // is not accessed appropriately (rather than just passing nullptr to
+ // CreateShaderResourceView)
+ const D3D12_RESOURCE_DESC resourceDesc =
+ resourceImpl->m_resource.getResource()->GetDesc();
+ const DXGI_FORMAT pixelFormat = desc.format == Format::Unknown
+ ? resourceDesc.Format
+ : D3DUtil::getMapFormat(desc.format);
+
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
+ initSrvDesc(
+ resourceImpl->getType(),
+ *resourceImpl->getDesc(),
+ resourceDesc,
+ pixelFormat,
+ desc.subresourceRange,
+ srvDesc);
+
+ m_device->CreateShaderResourceView(
+ resourceImpl->m_resource,
+ &srvDesc,
+ viewImpl->m_descriptor.cpuHandle);
+ }
+ break;
}
returnComPtr(outView, viewImpl);
@@ -1677,7 +1747,7 @@ Result DeviceImpl::createBufferView(
// Buffer view descriptors are created on demand.
viewImpl->m_descriptor = {0};
viewImpl->m_allocator = m_cpuViewHeap.get();
-
+
returnComPtr(outView, viewImpl);
return SLANG_OK;
}
@@ -1699,11 +1769,14 @@ Result DeviceImpl::createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffe
auto clearValue =
static_cast<TextureResourceImpl*>(
static_cast<ResourceViewImpl*>(desc.renderTargetViews[i])->m_resource.Ptr())
- ->getDesc()
- ->optimalClearValue;
+ ->getDesc()
+ ->optimalClearValue;
if (clearValue)
{
- memcpy(&framebuffer->renderTargetClearValues[i], &clearValue->color, sizeof(ColorClearValue));
+ memcpy(
+ &framebuffer->renderTargetClearValues[i],
+ &clearValue->color,
+ sizeof(ColorClearValue));
}
}
else
@@ -1714,10 +1787,11 @@ Result DeviceImpl::createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffe
framebuffer->depthStencilView = static_cast<ResourceViewImpl*>(desc.depthStencilView);
if (desc.depthStencilView)
{
- auto clearValue = static_cast<TextureResourceImpl*>(
- static_cast<ResourceViewImpl*>(desc.depthStencilView)->m_resource.Ptr())
- ->getDesc()
- ->optimalClearValue;
+ auto clearValue =
+ static_cast<TextureResourceImpl*>(
+ static_cast<ResourceViewImpl*>(desc.depthStencilView)->m_resource.Ptr())
+ ->getDesc()
+ ->optimalClearValue;
if (clearValue)
{
@@ -1735,7 +1809,8 @@ Result DeviceImpl::createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffe
}
Result DeviceImpl::createFramebufferLayout(
- IFramebufferLayout::Desc const& desc, IFramebufferLayout** outLayout)
+ IFramebufferLayout::Desc const& desc,
+ IFramebufferLayout** outLayout)
{
RefPtr<FramebufferLayoutImpl> layout = new FramebufferLayoutImpl();
layout->m_renderTargets.setCount(desc.renderTargetCount);
@@ -1758,7 +1833,8 @@ Result DeviceImpl::createFramebufferLayout(
}
Result DeviceImpl::createRenderPassLayout(
- const IRenderPassLayout::Desc& desc, IRenderPassLayout** outRenderPassLayout)
+ const IRenderPassLayout::Desc& desc,
+ IRenderPassLayout** outRenderPassLayout)
{
RefPtr<RenderPassLayoutImpl> result = new RenderPassLayoutImpl();
result->init(desc);
@@ -1824,10 +1900,16 @@ Result DeviceImpl::createInputLayout(IInputLayout::Desc const& desc, IInputLayou
return SLANG_OK;
}
-const gfx::DeviceInfo& DeviceImpl::getDeviceInfo() const { return m_info; }
+const gfx::DeviceInfo& DeviceImpl::getDeviceInfo() const
+{
+ return m_info;
+}
Result DeviceImpl::readBufferResource(
- IBufferResource* bufferIn, Offset offset, Size size, ISlangBlob** outBlob)
+ IBufferResource* bufferIn,
+ Offset offset,
+ Size size,
+ ISlangBlob** outBlob)
{
BufferResourceImpl* buffer = static_cast<BufferResourceImpl*>(bufferIn);
@@ -1876,7 +1958,7 @@ Result DeviceImpl::readBufferResource(
List<uint8_t> blobData;
{
UINT8* data;
- D3D12_RANGE readRange = { 0, size };
+ D3D12_RANGE readRange = {0, size};
SLANG_RETURN_ON_FAIL(
stageBufRef.getResource()->Map(0, &readRange, reinterpret_cast<void**>(&data)));
@@ -1893,7 +1975,9 @@ Result DeviceImpl::readBufferResource(
}
Result DeviceImpl::createProgram(
- const IShaderProgram::Desc& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnosticBlob)
+ const IShaderProgram::Desc& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnosticBlob)
{
RefPtr<ShaderProgramImpl> shaderProgram = new ShaderProgramImpl();
shaderProgram->init(desc);
@@ -1941,13 +2025,16 @@ Result DeviceImpl::createShaderObject(ShaderObjectLayoutBase* layout, IShaderObj
{
RefPtr<ShaderObjectImpl> shaderObject;
SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(
- this, reinterpret_cast<ShaderObjectLayoutImpl*>(layout), shaderObject.writeRef()));
+ this,
+ reinterpret_cast<ShaderObjectLayoutImpl*>(layout),
+ shaderObject.writeRef()));
returnComPtr(outObject, shaderObject);
return SLANG_OK;
}
Result DeviceImpl::createMutableShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject)
{
auto result = createShaderObject(layout, outObject);
SLANG_RETURN_ON_FAIL(result);
@@ -1961,7 +2048,11 @@ Result DeviceImpl::createMutableRootShaderObject(IShaderProgram* program, IShade
result->init(this);
auto programImpl = static_cast<ShaderProgramImpl*>(program);
result->resetImpl(
- this, programImpl->m_rootObjectLayout, m_cpuViewHeap.Ptr(), m_cpuSamplerHeap.Ptr(), true);
+ this,
+ programImpl->m_rootObjectLayout,
+ m_cpuViewHeap.Ptr(),
+ m_cpuSamplerHeap.Ptr(),
+ true);
returnComPtr(outObject, result);
return SLANG_OK;
}
@@ -1976,7 +2067,8 @@ Result DeviceImpl::createShaderTable(const IShaderTable::Desc& desc, IShaderTabl
}
Result DeviceImpl::createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& desc, IPipelineState** outState)
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState)
{
RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl(this);
pipelineStateImpl->init(desc);
@@ -1985,7 +2077,8 @@ Result DeviceImpl::createGraphicsPipelineState(
}
Result DeviceImpl::createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState)
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState)
{
RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl(this);
pipelineStateImpl->init(desc);
@@ -2011,17 +2104,17 @@ void DeviceImpl::submitResourceCommandsAndWait(const DeviceImpl::ResourceCommand
void DeviceImpl::processExperimentalFeaturesDesc(SharedLibrary::Handle d3dModule, void* inDesc)
{
- typedef HRESULT(WINAPI* PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES)(
- UINT NumFeatures,
+ typedef HRESULT(WINAPI * PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES)(
+ UINT NumFeatures,
const IID* pIIDs,
void* pConfigurationStructs,
- UINT* pConfigurationStructSizes
- );
+ UINT* pConfigurationStructSizes);
D3D12ExperimentalFeaturesDesc desc = {};
memcpy(&desc, inDesc, sizeof(desc));
- auto enableExperimentalFeaturesFunc =
- (PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES)loadProc(d3dModule, "D3D12EnableExperimentalFeatures");
+ auto enableExperimentalFeaturesFunc = (PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES)loadProc(
+ d3dModule,
+ "D3D12EnableExperimentalFeatures");
if (!enableExperimentalFeaturesFunc)
{
getDebugCallback()->handleMessage(
@@ -2031,7 +2124,11 @@ void DeviceImpl::processExperimentalFeaturesDesc(SharedLibrary::Handle d3dModule
"not found.");
return;
}
- if (!SLANG_SUCCEEDED(enableExperimentalFeaturesFunc(desc.numFeatures, (IID*)desc.featureIIDs, desc.configurationStructs, desc.configurationStructSizes)))
+ if (!SLANG_SUCCEEDED(enableExperimentalFeaturesFunc(
+ desc.numFeatures,
+ (IID*)desc.featureIIDs,
+ desc.configurationStructs,
+ desc.configurationStructSizes)))
{
getDebugCallback()->handleMessage(
gfx::DebugMessageType::Warning,
@@ -2049,23 +2146,23 @@ Result DeviceImpl::createQueryPool(const IQueryPool::Desc& desc, IQueryPool** ou
case QueryType::AccelerationStructureCompactedSize:
case QueryType::AccelerationStructureSerializedSize:
case QueryType::AccelerationStructureCurrentSize:
- {
- RefPtr<PlainBufferProxyQueryPoolImpl> queryPoolImpl =
- new PlainBufferProxyQueryPoolImpl();
- uint32_t stride = 8;
- if (desc.type == QueryType::AccelerationStructureSerializedSize)
- stride = 16;
- SLANG_RETURN_ON_FAIL(queryPoolImpl->init(desc, this, stride));
- returnComPtr(outState, queryPoolImpl);
- return SLANG_OK;
- }
+ {
+ RefPtr<PlainBufferProxyQueryPoolImpl> queryPoolImpl =
+ new PlainBufferProxyQueryPoolImpl();
+ uint32_t stride = 8;
+ if (desc.type == QueryType::AccelerationStructureSerializedSize)
+ stride = 16;
+ SLANG_RETURN_ON_FAIL(queryPoolImpl->init(desc, this, stride));
+ returnComPtr(outState, queryPoolImpl);
+ return SLANG_OK;
+ }
default:
- {
- RefPtr<QueryPoolImpl> queryPoolImpl = new QueryPoolImpl();
- SLANG_RETURN_ON_FAIL(queryPoolImpl->init(desc, this));
- returnComPtr(outState, queryPoolImpl);
- return SLANG_OK;
- }
+ {
+ RefPtr<QueryPoolImpl> queryPoolImpl = new QueryPoolImpl();
+ SLANG_RETURN_ON_FAIL(queryPoolImpl->init(desc, this));
+ returnComPtr(outState, queryPoolImpl);
+ return SLANG_OK;
+ }
}
}
@@ -2078,7 +2175,11 @@ Result DeviceImpl::createFence(const IFence::Desc& desc, IFence** outFence)
}
Result DeviceImpl::waitForFences(
- GfxCount fenceCount, IFence** fences, uint64_t* fenceValues, bool waitForAll, uint64_t timeout)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* fenceValues,
+ bool waitForAll,
+ uint64_t timeout)
{
ShortList<HANDLE> waitHandles;
for (GfxCount i = 0; i < fenceCount; ++i)
@@ -2118,7 +2219,8 @@ Result DeviceImpl::getAccelerationStructurePrebuildInfo(
}
Result DeviceImpl::createAccelerationStructure(
- const IAccelerationStructure::CreateDesc& desc, IAccelerationStructure** outAS)
+ const IAccelerationStructure::CreateDesc& desc,
+ IAccelerationStructure** outAS)
{
#if SLANG_GFX_HAS_DXR_SUPPORT
RefPtr<AccelerationStructureImpl> result = new AccelerationStructureImpl();
@@ -2139,13 +2241,14 @@ Result DeviceImpl::createAccelerationStructure(
returnComPtr(outAS, result);
return SLANG_OK;
#else
- * outAS = nullptr;
+ *outAS = nullptr;
return SLANG_FAIL;
#endif
}
Result DeviceImpl::createRayTracingPipelineState(
- const RayTracingPipelineStateDesc& inDesc, IPipelineState** outState)
+ const RayTracingPipelineStateDesc& inDesc,
+ IPipelineState** outState)
{
if (!m_device5)
{
@@ -2203,7 +2306,10 @@ void* DeviceImpl::loadProc(SharedLibrary::Handle module, char const* name)
return proc;
}
-DeviceImpl::~DeviceImpl() { m_shaderObjectLayoutCache = decltype(m_shaderObjectLayoutCache)(); }
+DeviceImpl::~DeviceImpl()
+{
+ m_shaderObjectLayoutCache = decltype(m_shaderObjectLayoutCache)();
+}
} // namespace d3d12
diff --git a/tools/gfx/d3d12/d3d12-device.h b/tools/gfx/d3d12/d3d12-device.h
index a38e3c68e..31756d3e9 100644
--- a/tools/gfx/d3d12/d3d12-device.h
+++ b/tools/gfx/d3d12/d3d12-device.h
@@ -2,8 +2,8 @@
#pragma once
#include "d3d12-command-buffer.h"
#include "d3d12-command-queue.h"
-#include "d3d12-transient-heap.h"
#include "d3d12-texture.h"
+#include "d3d12-transient-heap.h"
#include <d3d12.h>
#include <d3d12sdklayers.h>
@@ -17,7 +17,9 @@ using namespace Slang;
// Define function pointer types for PIX library.
typedef HRESULT(WINAPI* PFN_BeginEventOnCommandList)(
- ID3D12GraphicsCommandList* commandList, UINT64 color, PCSTR formatString);
+ ID3D12GraphicsCommandList* commandList,
+ UINT64 color,
+ PCSTR formatString);
typedef HRESULT(WINAPI* PFN_EndEventOnCommandList)(ID3D12GraphicsCommandList* commandList);
struct D3D12DeviceInfo
@@ -74,7 +76,7 @@ public:
// around CPU-visible heaps for storing shader-objects' descriptors in a format
// that is ready for copying into the GPU-visible heaps as needed.
//
- RefPtr<D3D12GeneralExpandingDescriptorHeap> m_cpuViewHeap; ///< Cbv, Srv, Uav
+ RefPtr<D3D12GeneralExpandingDescriptorHeap> m_cpuViewHeap; ///< Cbv, Srv, Uav
RefPtr<D3D12GeneralExpandingDescriptorHeap> m_cpuSamplerHeap; ///< Heap for samplers
// Dll entry points
@@ -97,17 +99,22 @@ public:
public:
virtual SLANG_NO_THROW SlangResult SLANG_MCALL initialize(const Desc& desc) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
+ getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
+ createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTransientResourceHeap(
- const ITransientResourceHeap::Desc& desc, ITransientResourceHeap** outHeap) override;
+ const ITransientResourceHeap::Desc& desc,
+ ITransientResourceHeap** outHeap) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain) override;
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureAllocationInfo(
- const ITextureResource::Desc& desc, Size* outSize, Size* outAlignment) override;
+ const ITextureResource::Desc& desc,
+ Size* outSize,
+ Size* outAlignment) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureRowAlignment(Size* outAlignment) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureResource(
const ITextureResource::Desc& desc,
@@ -127,7 +134,7 @@ public:
IBufferResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
+ createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
ITextureResource* texture,
@@ -140,42 +147,49 @@ public:
IResourceView** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffer** outFrameBuffer) override;
+ createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffer** outFrameBuffer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createFramebufferLayout(
- IFramebufferLayout::Desc const& desc, IFramebufferLayout** outLayout) override;
+ IFramebufferLayout::Desc const& desc,
+ IFramebufferLayout** outLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createRenderPassLayout(
- const IRenderPassLayout::Desc& desc, IRenderPassLayout** outRenderPassLayout) override;
+ const IRenderPassLayout::Desc& desc,
+ IRenderPassLayout** outRenderPassLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
+ createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
virtual Result createShaderObjectLayout(
- slang::ISession* session, slang::TypeLayoutReflection* typeLayout, ShaderObjectLayoutBase** outLayout) override;
- virtual Result createShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
+ slang::ISession* session,
+ slang::TypeLayoutReflection* typeLayout,
+ ShaderObjectLayoutBase** outLayout) override;
+ virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ override;
virtual Result createMutableShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
+ createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outShaderTable) override;
+ createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outShaderTable) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createProgram(
const IShaderProgram::Desc& desc,
IShaderProgram** outProgram,
ISlangBlob** outDiagnostics) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& desc, IPipelineState** outState) override;
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState) override;
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outState) override;
+ createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFence(const IFence::Desc& desc, IFence** outFence) override;
+ createFence(const IFence::Desc& desc, IFence** outFence) override;
virtual SLANG_NO_THROW Result SLANG_MCALL waitForFences(
GfxCount fenceCount,
@@ -192,12 +206,15 @@ public:
Size* outPixelSize) override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL readBufferResource(
- IBufferResource* resource, Offset offset, Size size, ISlangBlob** outBlob) override;
+ IBufferResource* resource,
+ Offset offset,
+ Size size,
+ ISlangBlob** outBlob) override;
virtual SLANG_NO_THROW const gfx::DeviceInfo& SLANG_MCALL getDeviceInfo() const override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeDeviceHandles(InteropHandles* outHandles) override;
+ getNativeDeviceHandles(InteropHandles* outHandles) override;
~DeviceImpl();
@@ -205,9 +222,11 @@ public:
const IAccelerationStructure::BuildInputs& buildInputs,
IAccelerationStructure::PrebuildInfo* outPrebuildInfo) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createAccelerationStructure(
- const IAccelerationStructure::CreateDesc& desc, IAccelerationStructure** outView) override;
+ const IAccelerationStructure::CreateDesc& desc,
+ IAccelerationStructure** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createRayTracingPipelineState(
- const RayTracingPipelineStateDesc& desc, IPipelineState** outState) override;
+ const RayTracingPipelineStateDesc& desc,
+ IPipelineState** outState) override;
public:
static void* loadProc(SharedLibrary::Handle module, char const* name);
@@ -250,6 +269,7 @@ public:
};
ResourceCommandRecordInfo encodeResourceCommands();
void submitResourceCommandsAndWait(const ResourceCommandRecordInfo& info);
+
private:
void processExperimentalFeaturesDesc(SharedLibrary::Handle d3dModule, void* desc);
};
diff --git a/tools/gfx/d3d12/d3d12-fence.cpp b/tools/gfx/d3d12/d3d12-fence.cpp
index 124d9354c..8b7d47440 100644
--- a/tools/gfx/d3d12/d3d12-fence.cpp
+++ b/tools/gfx/d3d12/d3d12-fence.cpp
@@ -60,7 +60,11 @@ Result FenceImpl::getSharedHandle(InteropHandle* outHandle)
ComPtr<ID3D12Device> devicePtr;
m_fence->GetDevice(IID_PPV_ARGS(devicePtr.writeRef()));
SLANG_RETURN_ON_FAIL(devicePtr->CreateSharedHandle(
- m_fence, NULL, GENERIC_ALL, nullptr, (HANDLE*)&outHandle->handleValue));
+ m_fence,
+ NULL,
+ GENERIC_ALL,
+ nullptr,
+ (HANDLE*)&outHandle->handleValue));
outHandle->api = InteropHandleAPI::D3D12;
sharedHandle = *outHandle;
return SLANG_OK;
diff --git a/tools/gfx/d3d12/d3d12-fence.h b/tools/gfx/d3d12/d3d12-fence.h
index 9a109ae65..3e735ef78 100644
--- a/tools/gfx/d3d12/d3d12-fence.h
+++ b/tools/gfx/d3d12/d3d12-fence.h
@@ -30,7 +30,7 @@ public:
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeHandle(InteropHandle* outNativeHandle) override;
+ getNativeHandle(InteropHandle* outNativeHandle) override;
};
} // namespace d3d12
diff --git a/tools/gfx/d3d12/d3d12-helper-functions.cpp b/tools/gfx/d3d12/d3d12-helper-functions.cpp
index 077645b95..3ce9b872e 100644
--- a/tools/gfx/d3d12/d3d12-helper-functions.cpp
+++ b/tools/gfx/d3d12/d3d12-helper-functions.cpp
@@ -2,18 +2,18 @@
#include "d3d12-helper-functions.h"
#ifdef GFX_NVAPI
-# include "../nvapi/nvapi-include.h"
+#include "../nvapi/nvapi-include.h"
#endif
#include "../nvapi/nvapi-util.h"
#include "d3d12-buffer.h"
-#include "d3d12-transient-heap.h"
#include "d3d12-query.h"
+#include "d3d12-transient-heap.h"
#ifdef _DEBUG
-# define ENABLE_DEBUG_LAYER 1
+#define ENABLE_DEBUG_LAYER 1
#else
-# define ENABLE_DEBUG_LAYER 0
+#define ENABLE_DEBUG_LAYER 0
#endif
namespace gfx
@@ -42,16 +42,12 @@ D3D12_RESOURCE_FLAGS calcResourceFlag(ResourceState state)
{
switch (state)
{
- case ResourceState::RenderTarget:
- return D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
+ case ResourceState::RenderTarget: return D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
case ResourceState::DepthRead:
- case ResourceState::DepthWrite:
- return D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
+ case ResourceState::DepthWrite: return D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
case ResourceState::UnorderedAccess:
- case ResourceState::AccelerationStructure:
- return D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
- default:
- return D3D12_RESOURCE_FLAG_NONE;
+ case ResourceState::AccelerationStructure: return D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+ default: return D3D12_RESOURCE_FLAG_NONE;
}
}
@@ -71,19 +67,15 @@ D3D12_RESOURCE_DIMENSION calcResourceDimension(IResource::Type type)
{
switch (type)
{
- case IResource::Type::Buffer:
- return D3D12_RESOURCE_DIMENSION_BUFFER;
- case IResource::Type::Texture1D:
- return D3D12_RESOURCE_DIMENSION_TEXTURE1D;
+ case IResource::Type::Buffer: return D3D12_RESOURCE_DIMENSION_BUFFER;
+ case IResource::Type::Texture1D: return D3D12_RESOURCE_DIMENSION_TEXTURE1D;
case IResource::Type::TextureCube:
case IResource::Type::Texture2D:
- {
- return D3D12_RESOURCE_DIMENSION_TEXTURE2D;
- }
- case IResource::Type::Texture3D:
- return D3D12_RESOURCE_DIMENSION_TEXTURE3D;
- default:
- return D3D12_RESOURCE_DIMENSION_UNKNOWN;
+ {
+ return D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+ }
+ case IResource::Type::Texture3D: return D3D12_RESOURCE_DIMENSION_TEXTURE3D;
+ default: return D3D12_RESOURCE_DIMENSION_UNKNOWN;
}
}
@@ -91,16 +83,12 @@ DXGI_FORMAT getTypelessFormatFromDepthFormat(Format format)
{
switch (format)
{
- case Format::D16_UNORM:
- return DXGI_FORMAT_R16_TYPELESS;
- case Format::D32_FLOAT:
- return DXGI_FORMAT_R32_TYPELESS;
- case Format::D32_FLOAT_S8_UINT:
- return DXGI_FORMAT_R32G8X24_TYPELESS;
- //case Format::D24_UNORM_S8_UINT:
- // return DXGI_FORMAT_R24G8_TYPELESS;
- default:
- return D3DUtil::getMapFormat(format);
+ case Format::D16_UNORM: return DXGI_FORMAT_R16_TYPELESS;
+ case Format::D32_FLOAT: return DXGI_FORMAT_R32_TYPELESS;
+ case Format::D32_FLOAT_S8_UINT: return DXGI_FORMAT_R32G8X24_TYPELESS;
+ // case Format::D24_UNORM_S8_UINT:
+ // return DXGI_FORMAT_R24G8_TYPELESS;
+ default: return D3DUtil::getMapFormat(format);
}
}
@@ -111,10 +99,8 @@ bool isTypelessDepthFormat(DXGI_FORMAT format)
case DXGI_FORMAT_R16_TYPELESS:
case DXGI_FORMAT_R32_TYPELESS:
case DXGI_FORMAT_R32G8X24_TYPELESS:
- case DXGI_FORMAT_R24G8_TYPELESS:
- return true;
- default:
- return false;
+ case DXGI_FORMAT_R24G8_TYPELESS: return true;
+ default: return false;
}
}
@@ -122,12 +108,10 @@ D3D12_FILTER_TYPE translateFilterMode(TextureFilteringMode mode)
{
switch (mode)
{
- default:
- return D3D12_FILTER_TYPE(0);
+ default: return D3D12_FILTER_TYPE(0);
-#define CASE(SRC, DST) \
- case TextureFilteringMode::SRC: \
- return D3D12_FILTER_TYPE_##DST
+#define CASE(SRC, DST) \
+ case TextureFilteringMode::SRC: return D3D12_FILTER_TYPE_##DST
CASE(Point, POINT);
CASE(Linear, LINEAR);
@@ -140,12 +124,10 @@ D3D12_FILTER_REDUCTION_TYPE translateFilterReduction(TextureReductionOp op)
{
switch (op)
{
- default:
- return D3D12_FILTER_REDUCTION_TYPE(0);
+ default: return D3D12_FILTER_REDUCTION_TYPE(0);
-#define CASE(SRC, DST) \
- case TextureReductionOp::SRC: \
- return D3D12_FILTER_REDUCTION_TYPE_##DST
+#define CASE(SRC, DST) \
+ case TextureReductionOp::SRC: return D3D12_FILTER_REDUCTION_TYPE_##DST
CASE(Average, STANDARD);
CASE(Comparison, COMPARISON);
@@ -160,12 +142,10 @@ D3D12_TEXTURE_ADDRESS_MODE translateAddressingMode(TextureAddressingMode mode)
{
switch (mode)
{
- default:
- return D3D12_TEXTURE_ADDRESS_MODE(0);
+ default: return D3D12_TEXTURE_ADDRESS_MODE(0);
-#define CASE(SRC, DST) \
- case TextureAddressingMode::SRC: \
- return D3D12_TEXTURE_ADDRESS_MODE_##DST
+#define CASE(SRC, DST) \
+ case TextureAddressingMode::SRC: return D3D12_TEXTURE_ADDRESS_MODE_##DST
CASE(Wrap, WRAP);
CASE(ClampToEdge, CLAMP);
@@ -185,9 +165,8 @@ D3D12_COMPARISON_FUNC translateComparisonFunc(ComparisonFunc func)
// TODO: need to report failures
return D3D12_COMPARISON_FUNC_ALWAYS;
-#define CASE(FROM, TO) \
- case ComparisonFunc::FROM: \
- return D3D12_COMPARISON_FUNC_##TO
+#define CASE(FROM, TO) \
+ case ComparisonFunc::FROM: return D3D12_COMPARISON_FUNC_##TO
CASE(Never, NEVER);
CASE(Less, LESS);
@@ -224,8 +203,8 @@ void initSrvDesc(
descOut = D3D12_SHADER_RESOURCE_VIEW_DESC();
descOut.Format = (pixelFormat == DXGI_FORMAT_UNKNOWN)
- ? D3DUtil::calcFormat(D3DUtil::USAGE_SRV, desc.Format)
- : pixelFormat;
+ ? D3DUtil::calcFormat(D3DUtil::USAGE_SRV, desc.Format)
+ : pixelFormat;
descOut.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
if (desc.DepthOrArraySize == 1)
{
@@ -234,29 +213,30 @@ void initSrvDesc(
case D3D12_RESOURCE_DIMENSION_TEXTURE1D:
descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
descOut.Texture1D.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels - subresourceRange.mipLevel
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels - subresourceRange.mipLevel
+ : subresourceRange.mipLevelCount;
descOut.Texture1D.MostDetailedMip = subresourceRange.mipLevel;
break;
case D3D12_RESOURCE_DIMENSION_TEXTURE2D:
- descOut.ViewDimension = textureDesc.sampleDesc.numSamples > 1 ? D3D12_SRV_DIMENSION_TEXTURE2DMS : D3D12_SRV_DIMENSION_TEXTURE2D;
+ descOut.ViewDimension = textureDesc.sampleDesc.numSamples > 1
+ ? D3D12_SRV_DIMENSION_TEXTURE2DMS
+ : D3D12_SRV_DIMENSION_TEXTURE2D;
descOut.Texture2D.PlaneSlice =
D3DUtil::getPlaneSlice(descOut.Format, subresourceRange.aspectMask);
descOut.Texture2D.ResourceMinLODClamp = 0.0f;
descOut.Texture2D.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels - subresourceRange.mipLevel
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels - subresourceRange.mipLevel
+ : subresourceRange.mipLevelCount;
descOut.Texture2D.MostDetailedMip = subresourceRange.mipLevel;
break;
case D3D12_RESOURCE_DIMENSION_TEXTURE3D:
descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
descOut.Texture3D.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels - subresourceRange.mipLevel
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels - subresourceRange.mipLevel
+ : subresourceRange.mipLevelCount;
descOut.Texture3D.MostDetailedMip = subresourceRange.mipLevel;
break;
- default:
- assert(!"Unknown dimension");
+ default: assert(!"Unknown dimension");
}
}
else if (resourceType == IResource::Type::TextureCube)
@@ -266,12 +246,12 @@ void initSrvDesc(
descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
descOut.TextureCubeArray.NumCubes = subresourceRange.layerCount == 0
- ? textureDesc.arraySize
- : subresourceRange.layerCount / 6;
+ ? textureDesc.arraySize
+ : subresourceRange.layerCount / 6;
descOut.TextureCubeArray.First2DArrayFace = subresourceRange.baseArrayLayer;
descOut.TextureCubeArray.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels - subresourceRange.mipLevel
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels - subresourceRange.mipLevel
+ : subresourceRange.mipLevelCount;
descOut.TextureCubeArray.MostDetailedMip = subresourceRange.mipLevel;
descOut.TextureCubeArray.ResourceMinLODClamp = 0;
}
@@ -280,8 +260,8 @@ void initSrvDesc(
descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
descOut.TextureCube.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels - subresourceRange.mipLevel
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels - subresourceRange.mipLevel
+ : subresourceRange.mipLevelCount;
descOut.TextureCube.MostDetailedMip = subresourceRange.mipLevel;
descOut.TextureCube.ResourceMinLODClamp = 0;
}
@@ -296,60 +276,62 @@ void initSrvDesc(
descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
descOut.Texture1D.MostDetailedMip = subresourceRange.mipLevel;
descOut.Texture1D.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels
+ : subresourceRange.mipLevelCount;
descOut.Texture1DArray.ArraySize = subresourceRange.layerCount == 0
- ? desc.DepthOrArraySize
- : subresourceRange.layerCount;
+ ? desc.DepthOrArraySize
+ : subresourceRange.layerCount;
descOut.Texture1DArray.FirstArraySlice = subresourceRange.baseArrayLayer;
descOut.Texture1DArray.ResourceMinLODClamp = 0;
descOut.Texture1DArray.MostDetailedMip = subresourceRange.mipLevel;
descOut.Texture1DArray.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels - subresourceRange.mipLevel
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels - subresourceRange.mipLevel
+ : subresourceRange.mipLevelCount;
break;
case D3D12_RESOURCE_DIMENSION_TEXTURE2D:
- descOut.ViewDimension = textureDesc.sampleDesc.numSamples > 1 ? D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY : D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
- if(descOut.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY)
+ descOut.ViewDimension = textureDesc.sampleDesc.numSamples > 1
+ ? D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY
+ : D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
+ if (descOut.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY)
{
descOut.Texture2DArray.ArraySize = subresourceRange.layerCount == 0
- ? desc.DepthOrArraySize
- : subresourceRange.layerCount;
+ ? desc.DepthOrArraySize
+ : subresourceRange.layerCount;
descOut.Texture2DArray.FirstArraySlice = subresourceRange.baseArrayLayer;
descOut.Texture2DArray.PlaneSlice =
D3DUtil::getPlaneSlice(descOut.Format, subresourceRange.aspectMask);
descOut.Texture2DArray.ResourceMinLODClamp = 0;
descOut.Texture2DArray.MostDetailedMip = subresourceRange.mipLevel;
descOut.Texture2DArray.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels - subresourceRange.mipLevel
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels - subresourceRange.mipLevel
+ : subresourceRange.mipLevelCount;
}
else
{
assert(descOut.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY);
descOut.Texture2DMSArray.FirstArraySlice = subresourceRange.baseArrayLayer;
descOut.Texture2DMSArray.ArraySize = subresourceRange.layerCount == 0
- ? desc.DepthOrArraySize
- : subresourceRange.layerCount;
+ ? desc.DepthOrArraySize
+ : subresourceRange.layerCount;
}
-
+
break;
case D3D12_RESOURCE_DIMENSION_TEXTURE3D:
descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
descOut.Texture3D.MostDetailedMip = subresourceRange.mipLevel;
descOut.Texture3D.MipLevels = subresourceRange.mipLevelCount == 0
- ? desc.MipLevels
- : subresourceRange.mipLevelCount;
+ ? desc.MipLevels
+ : subresourceRange.mipLevelCount;
break;
- default:
- assert(!"Unknown dimension");
+ default: assert(!"Unknown dimension");
}
}
}
Result initTextureResourceDesc(
- D3D12_RESOURCE_DESC& resourceDesc, const ITextureResource::Desc& srcDesc)
+ D3D12_RESOURCE_DESC& resourceDesc,
+ const ITextureResource::Desc& srcDesc)
{
const DXGI_FORMAT pixelFormat = D3DUtil::getMapFormat(srcDesc.format);
if (pixelFormat == DXGI_FORMAT_UNKNOWN)
@@ -385,7 +367,7 @@ Result initTextureResourceDesc(
if (isDepthFormat(srcDesc.format) &&
(srcDesc.allowedStates.contains(ResourceState::ShaderResource) ||
- srcDesc.allowedStates.contains(ResourceState::UnorderedAccess)))
+ srcDesc.allowedStates.contains(ResourceState::UnorderedAccess)))
{
resourceDesc.Format = getTypelessFormatFromDepthFormat(srcDesc.format);
}
@@ -424,7 +406,10 @@ Result uploadBufferDataImpl(
if (buffer->getDesc()->memoryType != MemoryType::Upload)
{
SLANG_RETURN_ON_FAIL(transientHeap->allocateStagingBuffer(
- size, uploadResource, uploadResourceOffset, MemoryType::Upload));
+ size,
+ uploadResource,
+ uploadResourceOffset,
+ MemoryType::Upload));
}
else
{
@@ -432,8 +417,8 @@ Result uploadBufferDataImpl(
}
D3D12Resource& uploadResourceRef =
(buffer->getDesc()->memoryType == MemoryType::Upload)
- ? buffer->m_resource
- : static_cast<BufferResourceImpl*>(uploadResource)->m_resource;
+ ? buffer->m_resource
+ : static_cast<BufferResourceImpl*>(uploadResource)->m_resource;
D3D12_RANGE readRange = {};
readRange.Begin = 0;
@@ -468,122 +453,105 @@ Result createNullDescriptor(
switch (bindingRange.bindingType)
{
case slang::BindingType::ConstantBuffer:
- {
- D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
- cbvDesc.BufferLocation = 0;
- cbvDesc.SizeInBytes = 0;
- d3dDevice->CreateConstantBufferView(&cbvDesc, destDescriptor);
- }
- break;
+ {
+ D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
+ cbvDesc.BufferLocation = 0;
+ cbvDesc.SizeInBytes = 0;
+ d3dDevice->CreateConstantBufferView(&cbvDesc, destDescriptor);
+ }
+ break;
case slang::BindingType::MutableRawBuffer:
- {
- D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
- uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
- uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
- uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
- d3dDevice->CreateUnorderedAccessView(nullptr, nullptr, &uavDesc, destDescriptor);
- }
- break;
+ {
+ D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
+ uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
+ uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
+ uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
+ d3dDevice->CreateUnorderedAccessView(nullptr, nullptr, &uavDesc, destDescriptor);
+ }
+ break;
case slang::BindingType::MutableTypedBuffer:
- {
- D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
- uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
- uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
- d3dDevice->CreateUnorderedAccessView(nullptr, nullptr, &uavDesc, destDescriptor);
- }
- break;
+ {
+ D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
+ uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
+ uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ d3dDevice->CreateUnorderedAccessView(nullptr, nullptr, &uavDesc, destDescriptor);
+ }
+ break;
case slang::BindingType::RawBuffer:
- {
- D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
- srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
- srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
- srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
- d3dDevice->CreateShaderResourceView(nullptr, &srvDesc, destDescriptor);
- }
- break;
+ {
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
+ srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
+ srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
+ srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ d3dDevice->CreateShaderResourceView(nullptr, &srvDesc, destDescriptor);
+ }
+ break;
case slang::BindingType::TypedBuffer:
- {
- D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
- srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
- srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
- d3dDevice->CreateShaderResourceView(nullptr, &srvDesc, destDescriptor);
- }
- break;
+ {
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
+ srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ d3dDevice->CreateShaderResourceView(nullptr, &srvDesc, destDescriptor);
+ }
+ break;
case slang::BindingType::Texture:
- {
- D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
- srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
- srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
- switch (bindingRange.resourceShape)
{
- case SLANG_TEXTURE_1D:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
- break;
- case SLANG_TEXTURE_1D_ARRAY:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
- break;
- case SLANG_TEXTURE_2D:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
- break;
- case SLANG_TEXTURE_2D_ARRAY:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
- break;
- case SLANG_TEXTURE_3D:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
- break;
- case SLANG_TEXTURE_CUBE:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
- break;
- case SLANG_TEXTURE_CUBE_ARRAY:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
- break;
- case SLANG_TEXTURE_2D_MULTISAMPLE:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS;
- break;
- case SLANG_TEXTURE_2D_MULTISAMPLE_ARRAY:
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY;
- break;
- default:
- return SLANG_OK;
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
+ srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ switch (bindingRange.resourceShape)
+ {
+ case SLANG_TEXTURE_1D: srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; break;
+ case SLANG_TEXTURE_1D_ARRAY:
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
+ break;
+ case SLANG_TEXTURE_2D: srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; break;
+ case SLANG_TEXTURE_2D_ARRAY:
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
+ break;
+ case SLANG_TEXTURE_3D: srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; break;
+ case SLANG_TEXTURE_CUBE: srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; break;
+ case SLANG_TEXTURE_CUBE_ARRAY:
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
+ break;
+ case SLANG_TEXTURE_2D_MULTISAMPLE:
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS;
+ break;
+ case SLANG_TEXTURE_2D_MULTISAMPLE_ARRAY:
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY;
+ break;
+ default: return SLANG_OK;
+ }
+ d3dDevice->CreateShaderResourceView(nullptr, &srvDesc, destDescriptor);
}
- d3dDevice->CreateShaderResourceView(nullptr, &srvDesc, destDescriptor);
- }
- break;
+ break;
case slang::BindingType::MutableTexture:
- {
- D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
- uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
- switch (bindingRange.resourceShape)
{
- case SLANG_TEXTURE_1D:
- uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
- break;
- case SLANG_TEXTURE_1D_ARRAY:
- uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
- break;
- case SLANG_TEXTURE_2D:
- uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
- break;
- case SLANG_TEXTURE_2D_ARRAY:
- uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
- break;
- case SLANG_TEXTURE_3D:
- uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
- break;
- case SLANG_TEXTURE_CUBE:
- case SLANG_TEXTURE_CUBE_ARRAY:
- case SLANG_TEXTURE_2D_MULTISAMPLE:
- case SLANG_TEXTURE_2D_MULTISAMPLE_ARRAY:
- default:
- return SLANG_OK;
+ D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
+ uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ switch (bindingRange.resourceShape)
+ {
+ case SLANG_TEXTURE_1D: uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; break;
+ case SLANG_TEXTURE_1D_ARRAY:
+ uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
+ break;
+ case SLANG_TEXTURE_2D: uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; break;
+ case SLANG_TEXTURE_2D_ARRAY:
+ uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
+ break;
+ case SLANG_TEXTURE_3D: uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; break;
+ case SLANG_TEXTURE_CUBE:
+ case SLANG_TEXTURE_CUBE_ARRAY:
+ case SLANG_TEXTURE_2D_MULTISAMPLE:
+ case SLANG_TEXTURE_2D_MULTISAMPLE_ARRAY:
+ default: return SLANG_OK;
+ }
+ d3dDevice->CreateUnorderedAccessView(nullptr, nullptr, &uavDesc, destDescriptor);
}
- d3dDevice->CreateUnorderedAccessView(nullptr, nullptr, &uavDesc, destDescriptor);
- }
- break;
- default:
break;
+ default: break;
}
return SLANG_OK;
}
@@ -603,27 +571,27 @@ void translatePostBuildInfoDescs(
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE;
postBuildInfoDescs[i].DestBuffer =
static_cast<PlainBufferProxyQueryPoolImpl*>(queryDescs[i].queryPool)
- ->m_bufferResource->getDeviceAddress() +
+ ->m_bufferResource->getDeviceAddress() +
sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC) *
- queryDescs[i].firstQueryIndex;
+ queryDescs[i].firstQueryIndex;
break;
case QueryType::AccelerationStructureCurrentSize:
postBuildInfoDescs[i].InfoType =
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE;
postBuildInfoDescs[i].DestBuffer =
static_cast<PlainBufferProxyQueryPoolImpl*>(queryDescs[i].queryPool)
- ->m_bufferResource->getDeviceAddress() +
+ ->m_bufferResource->getDeviceAddress() +
sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC) *
- queryDescs[i].firstQueryIndex;
+ queryDescs[i].firstQueryIndex;
break;
case QueryType::AccelerationStructureSerializedSize:
postBuildInfoDescs[i].InfoType =
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION;
postBuildInfoDescs[i].DestBuffer =
static_cast<PlainBufferProxyQueryPoolImpl*>(queryDescs[i].queryPool)
- ->m_bufferResource->getDeviceAddress() +
+ ->m_bufferResource->getDeviceAddress() +
sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION_DESC) *
- queryDescs[i].firstQueryIndex;
+ queryDescs[i].firstQueryIndex;
break;
}
}
@@ -634,7 +602,8 @@ void translatePostBuildInfoDescs(
Result SLANG_MCALL getD3D12Adapters(List<AdapterInfo>& outAdapters)
{
List<ComPtr<IDXGIAdapter>> dxgiAdapters;
- SLANG_RETURN_ON_FAIL(D3DUtil::findAdapters(DeviceCheckFlag::UseHardwareDevice, nullptr, dxgiAdapters));
+ SLANG_RETURN_ON_FAIL(
+ D3DUtil::findAdapters(DeviceCheckFlag::UseHardwareDevice, nullptr, dxgiAdapters));
outAdapters.clear();
for (const auto& dxgiAdapter : dxgiAdapters)
@@ -643,7 +612,10 @@ Result SLANG_MCALL getD3D12Adapters(List<AdapterInfo>& outAdapters)
dxgiAdapter->GetDesc(&desc);
AdapterInfo info = {};
auto name = String::fromWString(desc.Description);
- memcpy(info.name, name.getBuffer(), Math::Min(name.getLength(), (Index)sizeof(AdapterInfo::name) - 1));
+ memcpy(
+ info.name,
+ name.getBuffer(),
+ Math::Min(name.getLength(), (Index)sizeof(AdapterInfo::name) - 1));
info.vendorID = desc.VendorId;
info.deviceID = desc.DeviceId;
info.luid = D3DUtil::getAdapterLUID(dxgiAdapter);
diff --git a/tools/gfx/d3d12/d3d12-helper-functions.h b/tools/gfx/d3d12/d3d12-helper-functions.h
index 52b587529..e9eeb4c8f 100644
--- a/tools/gfx/d3d12/d3d12-helper-functions.h
+++ b/tools/gfx/d3d12/d3d12-helper-functions.h
@@ -1,17 +1,18 @@
// d3d12-helper-functions.h
#pragma once
-#include "slang-gfx.h"
+#include "../../../source/core/slang-list.h"
+#include "../../../source/core/slang-short-list.h"
#include "d3d12-base.h"
#include "d3d12-shader-object-layout.h"
#include "d3d12-submitter.h"
-#include "../../../source/core/slang-short-list.h"
-#include "../../../source/core/slang-list.h"
+#include "slang-gfx.h"
#ifndef __ID3D12GraphicsCommandList1_FWD_DEFINED__
// If can't find a definition of CommandList1, just use an empty definition
struct ID3D12GraphicsCommandList1
-{};
+{
+};
#endif
namespace gfx
@@ -35,7 +36,7 @@ struct BindingContext
TransientResourceHeapImpl* transientHeap;
DeviceImpl* device;
D3D12_DESCRIPTOR_HEAP_TYPE
- outOfMemoryHeap; // The type of descriptor heap that is OOM during binding.
+ outOfMemoryHeap; // The type of descriptor heap that is OOM during binding.
ShortList<PendingDescriptorTableBinding>* pendingTableBindings;
};
@@ -62,7 +63,8 @@ void initSrvDesc(
SubresourceRange subresourceRange,
D3D12_SHADER_RESOURCE_VIEW_DESC& descOut);
Result initTextureResourceDesc(
- D3D12_RESOURCE_DESC& resourceDesc, const ITextureResource::Desc& srcDesc);
+ D3D12_RESOURCE_DESC& resourceDesc,
+ const ITextureResource::Desc& srcDesc);
void initBufferResourceDesc(Size bufferSize, D3D12_RESOURCE_DESC& out);
Result uploadBufferDataImpl(
ID3D12Device* device,
diff --git a/tools/gfx/d3d12/d3d12-pipeline-state-stream.h b/tools/gfx/d3d12/d3d12-pipeline-state-stream.h
index 9848e96f9..db1f85d28 100644
--- a/tools/gfx/d3d12/d3d12-pipeline-state-stream.h
+++ b/tools/gfx/d3d12/d3d12-pipeline-state-stream.h
@@ -5,22 +5,25 @@
// `d3dx12_pipeline_state_stream.h`. Attribution Microsoft.
//
+#include "d3d12-sal-defs.h"
+
#include <climits>
#include <d3d12.h>
#include <dxgi1_4.h>
-#include "d3d12-sal-defs.h"
-
-struct CD3DX12_DEFAULT {};
+struct CD3DX12_DEFAULT
+{
+};
//------------------------------------------------------------------------------------------------
struct CD3DX12_DEPTH_STENCIL_DESC : public D3D12_DEPTH_STENCIL_DESC
{
CD3DX12_DEPTH_STENCIL_DESC() = default;
- explicit CD3DX12_DEPTH_STENCIL_DESC( const D3D12_DEPTH_STENCIL_DESC& o ) noexcept :
- D3D12_DEPTH_STENCIL_DESC( o )
- {}
- explicit CD3DX12_DEPTH_STENCIL_DESC( CD3DX12_DEFAULT ) noexcept
+ explicit CD3DX12_DEPTH_STENCIL_DESC(const D3D12_DEPTH_STENCIL_DESC& o) noexcept
+ : D3D12_DEPTH_STENCIL_DESC(o)
+ {
+ }
+ explicit CD3DX12_DEPTH_STENCIL_DESC(CD3DX12_DEFAULT) noexcept
{
DepthEnable = TRUE;
DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
@@ -28,8 +31,11 @@ struct CD3DX12_DEPTH_STENCIL_DESC : public D3D12_DEPTH_STENCIL_DESC
StencilEnable = FALSE;
StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK;
StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK;
- const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp =
- { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS };
+ const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp = {
+ D3D12_STENCIL_OP_KEEP,
+ D3D12_STENCIL_OP_KEEP,
+ D3D12_STENCIL_OP_KEEP,
+ D3D12_COMPARISON_FUNC_ALWAYS};
FrontFace = defaultStencilOp;
BackFace = defaultStencilOp;
}
@@ -47,7 +53,7 @@ struct CD3DX12_DEPTH_STENCIL_DESC : public D3D12_DEPTH_STENCIL_DESC
D3D12_STENCIL_OP backStencilFailOp,
D3D12_STENCIL_OP backStencilDepthFailOp,
D3D12_STENCIL_OP backStencilPassOp,
- D3D12_COMPARISON_FUNC backStencilFunc ) noexcept
+ D3D12_COMPARISON_FUNC backStencilFunc) noexcept
{
DepthEnable = depthEnable;
DepthWriteMask = depthWriteMask;
@@ -70,28 +76,29 @@ struct CD3DX12_DEPTH_STENCIL_DESC : public D3D12_DEPTH_STENCIL_DESC
struct CD3DX12_DEPTH_STENCIL_DESC1 : public D3D12_DEPTH_STENCIL_DESC1
{
CD3DX12_DEPTH_STENCIL_DESC1() = default;
- explicit CD3DX12_DEPTH_STENCIL_DESC1( const D3D12_DEPTH_STENCIL_DESC1& o ) noexcept :
- D3D12_DEPTH_STENCIL_DESC1( o )
- {}
- explicit CD3DX12_DEPTH_STENCIL_DESC1( const D3D12_DEPTH_STENCIL_DESC& o ) noexcept
+ explicit CD3DX12_DEPTH_STENCIL_DESC1(const D3D12_DEPTH_STENCIL_DESC1& o) noexcept
+ : D3D12_DEPTH_STENCIL_DESC1(o)
+ {
+ }
+ explicit CD3DX12_DEPTH_STENCIL_DESC1(const D3D12_DEPTH_STENCIL_DESC& o) noexcept
{
- DepthEnable = o.DepthEnable;
- DepthWriteMask = o.DepthWriteMask;
- DepthFunc = o.DepthFunc;
- StencilEnable = o.StencilEnable;
- StencilReadMask = o.StencilReadMask;
- StencilWriteMask = o.StencilWriteMask;
- FrontFace.StencilFailOp = o.FrontFace.StencilFailOp;
+ DepthEnable = o.DepthEnable;
+ DepthWriteMask = o.DepthWriteMask;
+ DepthFunc = o.DepthFunc;
+ StencilEnable = o.StencilEnable;
+ StencilReadMask = o.StencilReadMask;
+ StencilWriteMask = o.StencilWriteMask;
+ FrontFace.StencilFailOp = o.FrontFace.StencilFailOp;
FrontFace.StencilDepthFailOp = o.FrontFace.StencilDepthFailOp;
- FrontFace.StencilPassOp = o.FrontFace.StencilPassOp;
- FrontFace.StencilFunc = o.FrontFace.StencilFunc;
- BackFace.StencilFailOp = o.BackFace.StencilFailOp;
- BackFace.StencilDepthFailOp = o.BackFace.StencilDepthFailOp;
- BackFace.StencilPassOp = o.BackFace.StencilPassOp;
- BackFace.StencilFunc = o.BackFace.StencilFunc;
- DepthBoundsTestEnable = FALSE;
+ FrontFace.StencilPassOp = o.FrontFace.StencilPassOp;
+ FrontFace.StencilFunc = o.FrontFace.StencilFunc;
+ BackFace.StencilFailOp = o.BackFace.StencilFailOp;
+ BackFace.StencilDepthFailOp = o.BackFace.StencilDepthFailOp;
+ BackFace.StencilPassOp = o.BackFace.StencilPassOp;
+ BackFace.StencilFunc = o.BackFace.StencilFunc;
+ DepthBoundsTestEnable = FALSE;
}
- explicit CD3DX12_DEPTH_STENCIL_DESC1( CD3DX12_DEFAULT ) noexcept
+ explicit CD3DX12_DEPTH_STENCIL_DESC1(CD3DX12_DEFAULT) noexcept
{
DepthEnable = TRUE;
DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
@@ -99,8 +106,11 @@ struct CD3DX12_DEPTH_STENCIL_DESC1 : public D3D12_DEPTH_STENCIL_DESC1
StencilEnable = FALSE;
StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK;
StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK;
- const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp =
- { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS };
+ const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp = {
+ D3D12_STENCIL_OP_KEEP,
+ D3D12_STENCIL_OP_KEEP,
+ D3D12_STENCIL_OP_KEEP,
+ D3D12_COMPARISON_FUNC_ALWAYS};
FrontFace = defaultStencilOp;
BackFace = defaultStencilOp;
DepthBoundsTestEnable = FALSE;
@@ -120,7 +130,7 @@ struct CD3DX12_DEPTH_STENCIL_DESC1 : public D3D12_DEPTH_STENCIL_DESC1
D3D12_STENCIL_OP backStencilDepthFailOp,
D3D12_STENCIL_OP backStencilPassOp,
D3D12_COMPARISON_FUNC backStencilFunc,
- BOOL depthBoundsTestEnable ) noexcept
+ BOOL depthBoundsTestEnable) noexcept
{
DepthEnable = depthEnable;
DepthWriteMask = depthWriteMask;
@@ -141,20 +151,20 @@ struct CD3DX12_DEPTH_STENCIL_DESC1 : public D3D12_DEPTH_STENCIL_DESC1
operator D3D12_DEPTH_STENCIL_DESC() const noexcept
{
D3D12_DEPTH_STENCIL_DESC D;
- D.DepthEnable = DepthEnable;
- D.DepthWriteMask = DepthWriteMask;
- D.DepthFunc = DepthFunc;
- D.StencilEnable = StencilEnable;
- D.StencilReadMask = StencilReadMask;
- D.StencilWriteMask = StencilWriteMask;
- D.FrontFace.StencilFailOp = FrontFace.StencilFailOp;
+ D.DepthEnable = DepthEnable;
+ D.DepthWriteMask = DepthWriteMask;
+ D.DepthFunc = DepthFunc;
+ D.StencilEnable = StencilEnable;
+ D.StencilReadMask = StencilReadMask;
+ D.StencilWriteMask = StencilWriteMask;
+ D.FrontFace.StencilFailOp = FrontFace.StencilFailOp;
D.FrontFace.StencilDepthFailOp = FrontFace.StencilDepthFailOp;
- D.FrontFace.StencilPassOp = FrontFace.StencilPassOp;
- D.FrontFace.StencilFunc = FrontFace.StencilFunc;
- D.BackFace.StencilFailOp = BackFace.StencilFailOp;
- D.BackFace.StencilDepthFailOp = BackFace.StencilDepthFailOp;
- D.BackFace.StencilPassOp = BackFace.StencilPassOp;
- D.BackFace.StencilFunc = BackFace.StencilFunc;
+ D.FrontFace.StencilPassOp = FrontFace.StencilPassOp;
+ D.FrontFace.StencilFunc = FrontFace.StencilFunc;
+ D.BackFace.StencilFailOp = BackFace.StencilFailOp;
+ D.BackFace.StencilDepthFailOp = BackFace.StencilDepthFailOp;
+ D.BackFace.StencilPassOp = BackFace.StencilPassOp;
+ D.BackFace.StencilFunc = BackFace.StencilFunc;
return D;
}
};
@@ -163,23 +173,28 @@ struct CD3DX12_DEPTH_STENCIL_DESC1 : public D3D12_DEPTH_STENCIL_DESC1
struct CD3DX12_BLEND_DESC : public D3D12_BLEND_DESC
{
CD3DX12_BLEND_DESC() = default;
- explicit CD3DX12_BLEND_DESC( const D3D12_BLEND_DESC& o ) noexcept :
- D3D12_BLEND_DESC( o )
- {}
- explicit CD3DX12_BLEND_DESC( CD3DX12_DEFAULT ) noexcept
+ explicit CD3DX12_BLEND_DESC(const D3D12_BLEND_DESC& o) noexcept
+ : D3D12_BLEND_DESC(o)
+ {
+ }
+ explicit CD3DX12_BLEND_DESC(CD3DX12_DEFAULT) noexcept
{
AlphaToCoverageEnable = FALSE;
IndependentBlendEnable = FALSE;
- const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc =
- {
- FALSE,FALSE,
- D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
- D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
+ const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {
+ FALSE,
+ FALSE,
+ D3D12_BLEND_ONE,
+ D3D12_BLEND_ZERO,
+ D3D12_BLEND_OP_ADD,
+ D3D12_BLEND_ONE,
+ D3D12_BLEND_ZERO,
+ D3D12_BLEND_OP_ADD,
D3D12_LOGIC_OP_NOOP,
D3D12_COLOR_WRITE_ENABLE_ALL,
};
for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
- RenderTarget[ i ] = defaultRenderTargetBlendDesc;
+ RenderTarget[i] = defaultRenderTargetBlendDesc;
}
};
@@ -187,10 +202,11 @@ struct CD3DX12_BLEND_DESC : public D3D12_BLEND_DESC
struct CD3DX12_RASTERIZER_DESC : public D3D12_RASTERIZER_DESC
{
CD3DX12_RASTERIZER_DESC() = default;
- explicit CD3DX12_RASTERIZER_DESC( const D3D12_RASTERIZER_DESC& o ) noexcept :
- D3D12_RASTERIZER_DESC( o )
- {}
- explicit CD3DX12_RASTERIZER_DESC( CD3DX12_DEFAULT ) noexcept
+ explicit CD3DX12_RASTERIZER_DESC(const D3D12_RASTERIZER_DESC& o) noexcept
+ : D3D12_RASTERIZER_DESC(o)
+ {
+ }
+ explicit CD3DX12_RASTERIZER_DESC(CD3DX12_DEFAULT) noexcept
{
FillMode = D3D12_FILL_MODE_SOLID;
CullMode = D3D12_CULL_MODE_BACK;
@@ -235,10 +251,11 @@ struct CD3DX12_RASTERIZER_DESC : public D3D12_RASTERIZER_DESC
struct CD3DX12_VIEW_INSTANCING_DESC : public D3D12_VIEW_INSTANCING_DESC
{
CD3DX12_VIEW_INSTANCING_DESC() = default;
- explicit CD3DX12_VIEW_INSTANCING_DESC( const D3D12_VIEW_INSTANCING_DESC& o ) noexcept :
- D3D12_VIEW_INSTANCING_DESC( o )
- {}
- explicit CD3DX12_VIEW_INSTANCING_DESC( CD3DX12_DEFAULT ) noexcept
+ explicit CD3DX12_VIEW_INSTANCING_DESC(const D3D12_VIEW_INSTANCING_DESC& o) noexcept
+ : D3D12_VIEW_INSTANCING_DESC(o)
+ {
+ }
+ explicit CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT) noexcept
{
ViewInstanceCount = 0;
pViewInstanceLocations = nullptr;
@@ -261,8 +278,11 @@ struct CD3DX12_RT_FORMAT_ARRAY : public D3D12_RT_FORMAT_ARRAY
CD3DX12_RT_FORMAT_ARRAY() = default;
explicit CD3DX12_RT_FORMAT_ARRAY(const D3D12_RT_FORMAT_ARRAY& o) noexcept
: D3D12_RT_FORMAT_ARRAY(o)
- {}
- explicit CD3DX12_RT_FORMAT_ARRAY(_In_reads_(NumFormats) const DXGI_FORMAT* pFormats, UINT NumFormats) noexcept
+ {
+ }
+ explicit CD3DX12_RT_FORMAT_ARRAY(
+ _In_reads_(NumFormats) const DXGI_FORMAT* pFormats,
+ UINT NumFormats) noexcept
{
NumRenderTargets = NumFormats;
memcpy(RTFormats, pFormats, sizeof(RTFormats));
@@ -274,103 +294,203 @@ struct CD3DX12_RT_FORMAT_ARRAY : public D3D12_RT_FORMAT_ARRAY
struct CD3DX12_SHADER_BYTECODE : public D3D12_SHADER_BYTECODE
{
CD3DX12_SHADER_BYTECODE() = default;
- explicit CD3DX12_SHADER_BYTECODE(const D3D12_SHADER_BYTECODE &o) noexcept :
- D3D12_SHADER_BYTECODE(o)
- {}
- CD3DX12_SHADER_BYTECODE(
- _In_ ID3DBlob* pShaderBlob ) noexcept
+ explicit CD3DX12_SHADER_BYTECODE(const D3D12_SHADER_BYTECODE& o) noexcept
+ : D3D12_SHADER_BYTECODE(o)
+ {
+ }
+ CD3DX12_SHADER_BYTECODE(_In_ ID3DBlob* pShaderBlob) noexcept
{
pShaderBytecode = pShaderBlob->GetBufferPointer();
BytecodeLength = pShaderBlob->GetBufferSize();
}
- CD3DX12_SHADER_BYTECODE(
- const void* _pShaderBytecode,
- SIZE_T bytecodeLength ) noexcept
+ CD3DX12_SHADER_BYTECODE(const void* _pShaderBytecode, SIZE_T bytecodeLength) noexcept
{
pShaderBytecode = _pShaderBytecode;
BytecodeLength = bytecodeLength;
}
};
-struct DefaultSampleMask { operator UINT() noexcept { return UINT_MAX; } };
-struct DefaultSampleDesc { operator DXGI_SAMPLE_DESC() noexcept { return DXGI_SAMPLE_DESC{1, 0}; } };
+struct DefaultSampleMask
+{
+ operator UINT() noexcept { return UINT_MAX; }
+};
+struct DefaultSampleDesc
+{
+ operator DXGI_SAMPLE_DESC() noexcept { return DXGI_SAMPLE_DESC{1, 0}; }
+};
#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable : 4324)
+#pragma warning(push)
+#pragma warning(disable : 4324)
#endif
-template <typename InnerStructType, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE Type, typename DefaultArg = InnerStructType>
+template<
+ typename InnerStructType,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE Type,
+ typename DefaultArg = InnerStructType>
class alignas(void*) CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT
{
private:
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE pssType;
InnerStructType pssInner;
+
public:
- CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT() noexcept : pssType(Type), pssInner(DefaultArg()) {}
- CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT(InnerStructType const& i) noexcept : pssType(Type), pssInner(i) {}
- CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT& operator=(InnerStructType const& i) noexcept { pssType = Type; pssInner = i; return *this; }
+ CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT() noexcept
+ : pssType(Type), pssInner(DefaultArg())
+ {
+ }
+ CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT(InnerStructType const& i) noexcept
+ : pssType(Type), pssInner(i)
+ {
+ }
+ CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT& operator=(InnerStructType const& i) noexcept
+ {
+ pssType = Type;
+ pssInner = i;
+ return *this;
+ }
operator InnerStructType const&() const noexcept { return pssInner; }
operator InnerStructType&() noexcept { return pssInner; }
InnerStructType* operator&() noexcept { return &pssInner; }
InnerStructType const* operator&() const noexcept { return &pssInner; }
};
#ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
#endif
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_PIPELINE_STATE_FLAGS, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS> CD3DX12_PIPELINE_STATE_STREAM_FLAGS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< UINT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK> CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< ID3D12RootSignature*, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE> CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_INPUT_LAYOUT_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT> CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE> CD3DX12_PIPELINE_STATE_STREAM_IB_STRIP_CUT_VALUE;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_PRIMITIVE_TOPOLOGY_TYPE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY> CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS> CD3DX12_PIPELINE_STATE_STREAM_VS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS> CD3DX12_PIPELINE_STATE_STREAM_GS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_STREAM_OUTPUT_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT> CD3DX12_PIPELINE_STATE_STREAM_STREAM_OUTPUT;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS> CD3DX12_PIPELINE_STATE_STREAM_HS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS> CD3DX12_PIPELINE_STATE_STREAM_DS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS> CD3DX12_PIPELINE_STATE_STREAM_PS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS> CD3DX12_PIPELINE_STATE_STREAM_AS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS> CD3DX12_PIPELINE_STATE_STREAM_MS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS> CD3DX12_PIPELINE_STATE_STREAM_CS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_BLEND_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_DEPTH_STENCIL_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_DEPTH_STENCIL_DESC1, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL1;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< DXGI_FORMAT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT> CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_RASTERIZER_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_RT_FORMAT_ARRAY, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS> CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< DXGI_SAMPLE_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DefaultSampleDesc> CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< UINT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, DefaultSampleMask> CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_CACHED_PIPELINE_STATE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO> CD3DX12_PIPELINE_STATE_STREAM_CACHED_PSO;
-typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_VIEW_INSTANCING_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_VIEW_INSTANCING;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_PIPELINE_STATE_FLAGS,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS>
+ CD3DX12_PIPELINE_STATE_STREAM_FLAGS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<UINT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK>
+ CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ ID3D12RootSignature*,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE>
+ CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_INPUT_LAYOUT_DESC,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT>
+ CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE>
+ CD3DX12_PIPELINE_STATE_STREAM_IB_STRIP_CUT_VALUE;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_PRIMITIVE_TOPOLOGY_TYPE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY>
+ CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_SHADER_BYTECODE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS>
+ CD3DX12_PIPELINE_STATE_STREAM_VS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_SHADER_BYTECODE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS>
+ CD3DX12_PIPELINE_STATE_STREAM_GS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_STREAM_OUTPUT_DESC,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT>
+ CD3DX12_PIPELINE_STATE_STREAM_STREAM_OUTPUT;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_SHADER_BYTECODE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS>
+ CD3DX12_PIPELINE_STATE_STREAM_HS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_SHADER_BYTECODE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS>
+ CD3DX12_PIPELINE_STATE_STREAM_DS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_SHADER_BYTECODE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS>
+ CD3DX12_PIPELINE_STATE_STREAM_PS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_SHADER_BYTECODE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS>
+ CD3DX12_PIPELINE_STATE_STREAM_AS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_SHADER_BYTECODE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS>
+ CD3DX12_PIPELINE_STATE_STREAM_MS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_SHADER_BYTECODE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS>
+ CD3DX12_PIPELINE_STATE_STREAM_CS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ CD3DX12_BLEND_DESC,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND,
+ CD3DX12_DEFAULT>
+ CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ CD3DX12_DEPTH_STENCIL_DESC,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL,
+ CD3DX12_DEFAULT>
+ CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ CD3DX12_DEPTH_STENCIL_DESC1,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1,
+ CD3DX12_DEFAULT>
+ CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL1;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ DXGI_FORMAT,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT>
+ CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ CD3DX12_RASTERIZER_DESC,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER,
+ CD3DX12_DEFAULT>
+ CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_RT_FORMAT_ARRAY,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS>
+ CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ DXGI_SAMPLE_DESC,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC,
+ DefaultSampleDesc>
+ CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ UINT,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK,
+ DefaultSampleMask>
+ CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ D3D12_CACHED_PIPELINE_STATE,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO>
+ CD3DX12_PIPELINE_STATE_STREAM_CACHED_PSO;
+typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT<
+ CD3DX12_VIEW_INSTANCING_DESC,
+ D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING,
+ CD3DX12_DEFAULT>
+ CD3DX12_PIPELINE_STATE_STREAM_VIEW_INSTANCING;
struct D3DX12_MESH_SHADER_PIPELINE_STATE_DESC
{
- ID3D12RootSignature* pRootSignature;
- D3D12_SHADER_BYTECODE AS;
- D3D12_SHADER_BYTECODE MS;
- D3D12_SHADER_BYTECODE PS;
- D3D12_BLEND_DESC BlendState;
- UINT SampleMask;
- D3D12_RASTERIZER_DESC RasterizerState;
- D3D12_DEPTH_STENCIL_DESC DepthStencilState;
+ ID3D12RootSignature* pRootSignature;
+ D3D12_SHADER_BYTECODE AS;
+ D3D12_SHADER_BYTECODE MS;
+ D3D12_SHADER_BYTECODE PS;
+ D3D12_BLEND_DESC BlendState;
+ UINT SampleMask;
+ D3D12_RASTERIZER_DESC RasterizerState;
+ D3D12_DEPTH_STENCIL_DESC DepthStencilState;
D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType;
- UINT NumRenderTargets;
- DXGI_FORMAT RTVFormats[ D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT ];
- DXGI_FORMAT DSVFormat;
- DXGI_SAMPLE_DESC SampleDesc;
- UINT NodeMask;
- D3D12_CACHED_PIPELINE_STATE CachedPSO;
- D3D12_PIPELINE_STATE_FLAGS Flags;
+ UINT NumRenderTargets;
+ DXGI_FORMAT RTVFormats[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT];
+ DXGI_FORMAT DSVFormat;
+ DXGI_SAMPLE_DESC SampleDesc;
+ UINT NodeMask;
+ D3D12_CACHED_PIPELINE_STATE CachedPSO;
+ D3D12_PIPELINE_STATE_FLAGS Flags;
};
-// CD3DX12_PIPELINE_STATE_STREAM2 Works on OS Build 19041+ (where there is a new mesh shader pipeline).
-// Use CD3DX12_PIPELINE_STATE_STREAM1 for OS Build 16299+ (where there is a new view instancing subobject).
-// Use CD3DX12_PIPELINE_STATE_STREAM for OS Build 15063+ support.
+// CD3DX12_PIPELINE_STATE_STREAM2 Works on OS Build 19041+ (where there is a new mesh shader
+// pipeline). Use CD3DX12_PIPELINE_STATE_STREAM1 for OS Build 16299+ (where there is a new view
+// instancing subobject). Use CD3DX12_PIPELINE_STATE_STREAM for OS Build 15063+ support.
struct CD3DX12_PIPELINE_STATE_STREAM2
{
CD3DX12_PIPELINE_STATE_STREAM2() = default;
- // Mesh and amplification shaders must be set manually, since they do not have representation in D3D12_GRAPHICS_PIPELINE_STATE_DESC
+ // Mesh and amplification shaders must be set manually, since they do not have representation in
+ // D3D12_GRAPHICS_PIPELINE_STATE_DESC
CD3DX12_PIPELINE_STATE_STREAM2(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& Desc) noexcept
: Flags(Desc.Flags)
, NodeMask(Desc.NodeMask)
@@ -393,7 +513,8 @@ struct CD3DX12_PIPELINE_STATE_STREAM2
, SampleMask(Desc.SampleMask)
, CachedPSO(Desc.CachedPSO)
, ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT()))
- {}
+ {
+ }
CD3DX12_PIPELINE_STATE_STREAM2(const D3DX12_MESH_SHADER_PIPELINE_STATE_DESC& Desc) noexcept
: Flags(Desc.Flags)
, NodeMask(Desc.NodeMask)
@@ -411,7 +532,8 @@ struct CD3DX12_PIPELINE_STATE_STREAM2
, SampleMask(Desc.SampleMask)
, CachedPSO(Desc.CachedPSO)
, ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT()))
- {}
+ {
+ }
CD3DX12_PIPELINE_STATE_STREAM2(const D3D12_COMPUTE_PIPELINE_STATE_DESC& Desc) noexcept
: Flags(Desc.Flags)
, NodeMask(Desc.NodeMask)
@@ -448,37 +570,41 @@ struct CD3DX12_PIPELINE_STATE_STREAM2
D3D12_GRAPHICS_PIPELINE_STATE_DESC GraphicsDescV0() const noexcept
{
D3D12_GRAPHICS_PIPELINE_STATE_DESC D;
- D.Flags = this->Flags;
- D.NodeMask = this->NodeMask;
- D.pRootSignature = this->pRootSignature;
- D.InputLayout = this->InputLayout;
- D.IBStripCutValue = this->IBStripCutValue;
+ D.Flags = this->Flags;
+ D.NodeMask = this->NodeMask;
+ D.pRootSignature = this->pRootSignature;
+ D.InputLayout = this->InputLayout;
+ D.IBStripCutValue = this->IBStripCutValue;
D.PrimitiveTopologyType = this->PrimitiveTopologyType;
- D.VS = this->VS;
- D.GS = this->GS;
- D.StreamOutput = this->StreamOutput;
- D.HS = this->HS;
- D.DS = this->DS;
- D.PS = this->PS;
- D.BlendState = this->BlendState;
- D.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(D3D12_DEPTH_STENCIL_DESC1(this->DepthStencilState));
- D.DSVFormat = this->DSVFormat;
- D.RasterizerState = this->RasterizerState;
- D.NumRenderTargets = D3D12_RT_FORMAT_ARRAY(this->RTVFormats).NumRenderTargets;
- memcpy(D.RTVFormats, D3D12_RT_FORMAT_ARRAY(this->RTVFormats).RTFormats, sizeof(D.RTVFormats));
- D.SampleDesc = this->SampleDesc;
- D.SampleMask = this->SampleMask;
- D.CachedPSO = this->CachedPSO;
+ D.VS = this->VS;
+ D.GS = this->GS;
+ D.StreamOutput = this->StreamOutput;
+ D.HS = this->HS;
+ D.DS = this->DS;
+ D.PS = this->PS;
+ D.BlendState = this->BlendState;
+ D.DepthStencilState =
+ CD3DX12_DEPTH_STENCIL_DESC1(D3D12_DEPTH_STENCIL_DESC1(this->DepthStencilState));
+ D.DSVFormat = this->DSVFormat;
+ D.RasterizerState = this->RasterizerState;
+ D.NumRenderTargets = D3D12_RT_FORMAT_ARRAY(this->RTVFormats).NumRenderTargets;
+ memcpy(
+ D.RTVFormats,
+ D3D12_RT_FORMAT_ARRAY(this->RTVFormats).RTFormats,
+ sizeof(D.RTVFormats));
+ D.SampleDesc = this->SampleDesc;
+ D.SampleMask = this->SampleMask;
+ D.CachedPSO = this->CachedPSO;
return D;
}
D3D12_COMPUTE_PIPELINE_STATE_DESC ComputeDescV0() const noexcept
{
D3D12_COMPUTE_PIPELINE_STATE_DESC D;
- D.Flags = this->Flags;
- D.NodeMask = this->NodeMask;
- D.pRootSignature = this->pRootSignature;
- D.CS = this->CS;
- D.CachedPSO = this->CachedPSO;
+ D.Flags = this->Flags;
+ D.NodeMask = this->NodeMask;
+ D.pRootSignature = this->pRootSignature;
+ D.CS = this->CS;
+ D.CachedPSO = this->CachedPSO;
return D;
}
};
diff --git a/tools/gfx/d3d12/d3d12-pipeline-state.cpp b/tools/gfx/d3d12/d3d12-pipeline-state.cpp
index fc54b3884..df830960f 100644
--- a/tools/gfx/d3d12/d3d12-pipeline-state.cpp
+++ b/tools/gfx/d3d12/d3d12-pipeline-state.cpp
@@ -2,15 +2,15 @@
#include "d3d12-pipeline-state.h"
#ifdef GFX_NVAPI
-# include "../nvapi/nvapi-include.h"
+#include "../nvapi/nvapi-include.h"
#endif
#include "../nvapi/nvapi-util.h"
#include "d3d12-device.h"
#include "d3d12-framebuffer.h"
+#include "d3d12-pipeline-state-stream.h"
#include "d3d12-shader-program.h"
#include "d3d12-vertex-layout.h"
-#include "d3d12-pipeline-state-stream.h"
#include <climits>
@@ -61,7 +61,8 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
auto inputLayoutImpl = (InputLayoutImpl*)desc.graphics.inputLayout;
// A helper to fill common fields between graphics and mesh pipeline descs
- const auto fillCommonGraphicsState = [&](auto& psoDesc){
+ const auto fillCommonGraphicsState = [&](auto& psoDesc)
+ {
psoDesc.pRootSignature = programImpl->m_rootObjectLayout->m_rootSignature;
psoDesc.PrimitiveTopologyType = D3DUtil::getPrimitiveType(desc.graphics.primitiveType);
@@ -73,7 +74,8 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
if (framebufferLayout->m_hasDepthStencil)
{
- psoDesc.DSVFormat = D3DUtil::getMapFormat(framebufferLayout->m_depthStencil.format);
+ psoDesc.DSVFormat =
+ D3DUtil::getMapFormat(framebufferLayout->m_depthStencil.format);
psoDesc.SampleDesc.Count = framebufferLayout->m_depthStencil.sampleCount;
}
else
@@ -81,7 +83,8 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
psoDesc.DSVFormat = DXGI_FORMAT_UNKNOWN;
if (framebufferLayout->m_renderTargets.getCount())
{
- psoDesc.SampleDesc.Count = framebufferLayout->m_renderTargets[0].sampleCount;
+ psoDesc.SampleDesc.Count =
+ framebufferLayout->m_renderTargets[0].sampleCount;
}
}
psoDesc.NumRenderTargets = numRenderTargets;
@@ -100,8 +103,9 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
rs.FillMode = D3DUtil::getFillMode(desc.graphics.rasterizer.fillMode);
rs.CullMode = D3DUtil::getCullMode(desc.graphics.rasterizer.cullMode);
rs.FrontCounterClockwise =
- desc.graphics.rasterizer.frontFace == gfx::FrontFaceMode::CounterClockwise ? TRUE
- : FALSE;
+ desc.graphics.rasterizer.frontFace == gfx::FrontFaceMode::CounterClockwise
+ ? TRUE
+ : FALSE;
rs.DepthBias = desc.graphics.rasterizer.depthBias;
rs.DepthBiasClamp = desc.graphics.rasterizer.depthBiasClamp;
rs.SlopeScaledDepthBias = desc.graphics.rasterizer.slopeScaledDepthBias;
@@ -111,21 +115,24 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
desc.graphics.rasterizer.antialiasedLineEnable ? TRUE : FALSE;
rs.ForcedSampleCount = desc.graphics.rasterizer.forcedSampleCount;
rs.ConservativeRaster = desc.graphics.rasterizer.enableConservativeRasterization
- ? D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON
- : D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
+ ? D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON
+ : D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
}
{
D3D12_BLEND_DESC& blend = psoDesc.BlendState;
blend.IndependentBlendEnable = FALSE;
- blend.AlphaToCoverageEnable = desc.graphics.blend.alphaToCoverageEnable ? TRUE : FALSE;
- blend.RenderTarget[0].RenderTargetWriteMask = (uint8_t)RenderTargetWriteMask::EnableAll;
+ blend.AlphaToCoverageEnable =
+ desc.graphics.blend.alphaToCoverageEnable ? TRUE : FALSE;
+ blend.RenderTarget[0].RenderTargetWriteMask =
+ (uint8_t)RenderTargetWriteMask::EnableAll;
for (GfxIndex i = 0; i < desc.graphics.blend.targetCount; i++)
{
auto& d3dDesc = blend.RenderTarget[i];
d3dDesc.BlendEnable = desc.graphics.blend.targets[i].enableBlend ? TRUE : FALSE;
d3dDesc.BlendOp = D3DUtil::getBlendOp(desc.graphics.blend.targets[i].color.op);
- d3dDesc.BlendOpAlpha = D3DUtil::getBlendOp(desc.graphics.blend.targets[i].alpha.op);
+ d3dDesc.BlendOpAlpha =
+ D3DUtil::getBlendOp(desc.graphics.blend.targets[i].alpha.op);
d3dDesc.DestBlend =
D3DUtil::getBlendFactor(desc.graphics.blend.targets[i].color.dstFactor);
d3dDesc.DestBlendAlpha =
@@ -141,17 +148,17 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
for (GfxIndex i = 1; i < desc.graphics.blend.targetCount; i++)
{
if (memcmp(
- &desc.graphics.blend.targets[i],
- &desc.graphics.blend.targets[0],
- sizeof(desc.graphics.blend.targets[0])) != 0)
+ &desc.graphics.blend.targets[i],
+ &desc.graphics.blend.targets[0],
+ sizeof(desc.graphics.blend.targets[0])) != 0)
{
blend.IndependentBlendEnable = TRUE;
break;
}
}
for (uint32_t i = (uint32_t)desc.graphics.blend.targetCount;
- i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT;
- ++i)
+ i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT;
+ ++i)
{
blend.RenderTarget[i] = blend.RenderTarget[0];
}
@@ -162,21 +169,21 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
ds.DepthEnable = desc.graphics.depthStencil.depthTestEnable;
ds.DepthWriteMask = desc.graphics.depthStencil.depthWriteEnable
- ? D3D12_DEPTH_WRITE_MASK_ALL
- : D3D12_DEPTH_WRITE_MASK_ZERO;
+ ? D3D12_DEPTH_WRITE_MASK_ALL
+ : D3D12_DEPTH_WRITE_MASK_ZERO;
ds.DepthFunc = D3DUtil::getComparisonFunc(desc.graphics.depthStencil.depthFunc);
ds.StencilEnable = desc.graphics.depthStencil.stencilEnable;
ds.StencilReadMask = (UINT8)desc.graphics.depthStencil.stencilReadMask;
ds.StencilWriteMask = (UINT8)desc.graphics.depthStencil.stencilWriteMask;
- ds.FrontFace = D3DUtil::translateStencilOpDesc(desc.graphics.depthStencil.frontFace);
+ ds.FrontFace =
+ D3DUtil::translateStencilOpDesc(desc.graphics.depthStencil.frontFace);
ds.BackFace = D3DUtil::translateStencilOpDesc(desc.graphics.depthStencil.backFace);
}
psoDesc.PrimitiveTopologyType = D3DUtil::getPrimitiveType(desc.graphics.primitiveType);
-
};
- if(m_program->isMeshShaderProgram())
+ if (m_program->isMeshShaderProgram())
{
D3DX12_MESH_SHADER_PIPELINE_STATE_DESC meshDesc = {};
for (auto& shaderBin : programImpl->m_shaders)
@@ -184,13 +191,13 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
switch (shaderBin.stage)
{
case SLANG_STAGE_FRAGMENT:
- meshDesc.PS = { shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount()) };
+ meshDesc.PS = {shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount())};
break;
case SLANG_STAGE_AMPLIFICATION:
- meshDesc.AS = { shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount()) };
+ meshDesc.AS = {shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount())};
break;
case SLANG_STAGE_MESH:
- meshDesc.MS = { shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount()) };
+ meshDesc.MS = {shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount())};
break;
default:
getDebugCallback()->handleMessage(
@@ -213,10 +220,13 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
else
{
CD3DX12_PIPELINE_STATE_STREAM2 meshStateStream{meshDesc};
- D3D12_PIPELINE_STATE_STREAM_DESC streamDesc{sizeof(meshStateStream), &meshStateStream};
+ D3D12_PIPELINE_STATE_STREAM_DESC streamDesc{
+ sizeof(meshStateStream),
+ &meshStateStream};
SLANG_RETURN_ON_FAIL(m_device->m_device5->CreatePipelineState(
- &streamDesc, IID_PPV_ARGS(m_pipelineState.writeRef())));
+ &streamDesc,
+ IID_PPV_ARGS(m_pipelineState.writeRef())));
}
}
else
@@ -227,19 +237,29 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
switch (shaderBin.stage)
{
case SLANG_STAGE_VERTEX:
- graphicsDesc.VS = { shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount()) };
+ graphicsDesc.VS = {
+ shaderBin.code.getBuffer(),
+ SIZE_T(shaderBin.code.getCount())};
break;
case SLANG_STAGE_FRAGMENT:
- graphicsDesc.PS = { shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount()) };
+ graphicsDesc.PS = {
+ shaderBin.code.getBuffer(),
+ SIZE_T(shaderBin.code.getCount())};
break;
case SLANG_STAGE_DOMAIN:
- graphicsDesc.DS = { shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount()) };
+ graphicsDesc.DS = {
+ shaderBin.code.getBuffer(),
+ SIZE_T(shaderBin.code.getCount())};
break;
case SLANG_STAGE_HULL:
- graphicsDesc.HS = { shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount()) };
+ graphicsDesc.HS = {
+ shaderBin.code.getBuffer(),
+ SIZE_T(shaderBin.code.getCount())};
break;
case SLANG_STAGE_GEOMETRY:
- graphicsDesc.GS = { shaderBin.code.getBuffer(), SIZE_T(shaderBin.code.getCount()) };
+ graphicsDesc.GS = {
+ shaderBin.code.getBuffer(),
+ SIZE_T(shaderBin.code.getCount())};
break;
default:
getDebugCallback()->handleMessage(
@@ -254,7 +274,7 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
{
graphicsDesc.InputLayout = {
inputLayoutImpl->m_elements.getBuffer(),
- UINT(inputLayoutImpl->m_elements.getCount()) };
+ UINT(inputLayoutImpl->m_elements.getCount())};
}
fillCommonGraphicsState(graphicsDesc);
@@ -271,7 +291,8 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
else
{
SLANG_RETURN_ON_FAIL(m_device->m_device->CreateGraphicsPipelineState(
- &graphicsDesc, IID_PPV_ARGS(m_pipelineState.writeRef())));
+ &graphicsDesc,
+ IID_PPV_ARGS(m_pipelineState.writeRef())));
}
}
}
@@ -286,11 +307,11 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
D3D12_COMPUTE_PIPELINE_STATE_DESC computeDesc = {};
computeDesc.pRootSignature =
desc.compute.d3d12RootSignatureOverride
- ? static_cast<ID3D12RootSignature*>(desc.compute.d3d12RootSignatureOverride)
- : programImpl->m_rootObjectLayout->m_rootSignature;
+ ? static_cast<ID3D12RootSignature*>(desc.compute.d3d12RootSignatureOverride)
+ : programImpl->m_rootObjectLayout->m_rootSignature;
computeDesc.CS = {
programImpl->m_shaders[0].code.getBuffer(),
- SIZE_T(programImpl->m_shaders[0].code.getCount()) };
+ SIZE_T(programImpl->m_shaders[0].code.getCount())};
#ifdef GFX_NVAPI
if (m_device->m_nvapi)
@@ -307,7 +328,7 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
// Put the pointer to the extension into an array - there can be multiple extensions
// enabled at once.
- const NVAPI_D3D12_PSO_EXTENSION_DESC* extensions[] = { &extensionDesc };
+ const NVAPI_D3D12_PSO_EXTENSION_DESC* extensions[] = {&extensionDesc};
// Now create the PSO.
const NvAPI_Status nvapiStatus = NvAPI_D3D12_CreateComputePipelineState(
@@ -337,7 +358,8 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
else
{
SLANG_RETURN_ON_FAIL(m_device->m_device->CreateComputePipelineState(
- &computeDesc, IID_PPV_ARGS(m_pipelineState.writeRef())));
+ &computeDesc,
+ IID_PPV_ARGS(m_pipelineState.writeRef())));
}
}
}
@@ -350,7 +372,8 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
RayTracingPipelineStateImpl::RayTracingPipelineStateImpl(DeviceImpl* device)
: m_device(device)
-{}
+{
+}
void RayTracingPipelineStateImpl::init(const RayTracingPipelineStateDesc& inDesc)
{
@@ -405,12 +428,16 @@ Result RayTracingPipelineStateImpl::ensureAPIPipelineStateCreated()
subObjects.add(pipelineConfigSubobject);
auto compileShader = [&](slang::EntryPointLayout* entryPointInfo,
- slang::IComponentType* component,
- SlangInt entryPointIndex)
+ slang::IComponentType* component,
+ SlangInt entryPointIndex)
{
ComPtr<ISlangBlob> codeBlob;
- auto compileResult = m_device->getEntryPointCodeFromShaderCache(component,
- entryPointIndex, 0, codeBlob.writeRef(), diagnostics.writeRef());
+ auto compileResult = m_device->getEntryPointCodeFromShaderCache(
+ component,
+ entryPointIndex,
+ 0,
+ codeBlob.writeRef(),
+ diagnostics.writeRef());
if (diagnostics.get())
{
getDebugCallback()->handleMessage(
@@ -441,7 +468,9 @@ Result RayTracingPipelineStateImpl::ensureAPIPipelineStateCreated()
for (SlangUInt i = 0; i < programLayout->getEntryPointCount(); i++)
{
SLANG_RETURN_ON_FAIL(compileShader(
- programLayout->getEntryPointByIndex(i), program->linkedProgram, (SlangInt)i));
+ programLayout->getEntryPointByIndex(i),
+ program->linkedProgram,
+ (SlangInt)i));
}
}
else
@@ -458,8 +487,8 @@ Result RayTracingPipelineStateImpl::ensureAPIPipelineStateCreated()
auto& hitGroup = desc.rayTracing.hitGroups[i];
D3D12_HIT_GROUP_DESC hitGroupDesc = {};
hitGroupDesc.Type = hitGroup.intersectionEntryPoint.getLength() == 0
- ? D3D12_HIT_GROUP_TYPE_TRIANGLES
- : D3D12_HIT_GROUP_TYPE_PROCEDURAL_PRIMITIVE;
+ ? D3D12_HIT_GROUP_TYPE_TRIANGLES
+ : D3D12_HIT_GROUP_TYPE_PROCEDURAL_PRIMITIVE;
if (hitGroup.anyHitEntryPoint.getLength())
{
@@ -503,7 +532,8 @@ Result RayTracingPipelineStateImpl::ensureAPIPipelineStateCreated()
if (m_device->m_pipelineCreationAPIDispatcher)
{
m_device->m_pipelineCreationAPIDispatcher->beforeCreateRayTracingState(
- m_device, slangGlobalScope);
+ m_device,
+ slangGlobalScope);
}
D3D12_STATE_OBJECT_DESC rtpsoDesc = {};
@@ -516,7 +546,8 @@ Result RayTracingPipelineStateImpl::ensureAPIPipelineStateCreated()
if (m_device->m_pipelineCreationAPIDispatcher)
{
m_device->m_pipelineCreationAPIDispatcher->afterCreateRayTracingState(
- m_device, slangGlobalScope);
+ m_device,
+ slangGlobalScope);
}
return SLANG_OK;
}
diff --git a/tools/gfx/d3d12/d3d12-pipeline-state.h b/tools/gfx/d3d12/d3d12-pipeline-state.h
index a22e04a05..21645642a 100644
--- a/tools/gfx/d3d12/d3d12-pipeline-state.h
+++ b/tools/gfx/d3d12/d3d12-pipeline-state.h
@@ -15,7 +15,8 @@ class PipelineStateImpl : public PipelineStateBase
public:
PipelineStateImpl(DeviceImpl* device)
: m_device(device)
- {}
+ {
+ }
DeviceImpl* m_device;
ComPtr<ID3D12PipelineState> m_pipelineState;
void init(const GraphicsPipelineStateDesc& inDesc);
diff --git a/tools/gfx/d3d12/d3d12-posix-synchapi.cpp b/tools/gfx/d3d12/d3d12-posix-synchapi.cpp
index b979bb3cc..292f692d6 100644
--- a/tools/gfx/d3d12/d3d12-posix-synchapi.cpp
+++ b/tools/gfx/d3d12/d3d12-posix-synchapi.cpp
@@ -6,6 +6,7 @@
#include "core/slang-common.h"
+#include <cerrno>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
@@ -13,8 +14,6 @@
#include <sys/timerfd.h>
#include <unistd.h>
-#include <cerrno>
-
// To keep aligned with the d3d12 API, we store file descriptors in the low 32
// bits of HANDLEs.
static int _handleToFD(HANDLE h)
@@ -41,16 +40,16 @@ static HANDLE _fdToHandle(int fd, int flags)
HANDLE CreateEventEx(
LPSECURITY_ATTRIBUTES lpEventAttributes,
- LPCSTR lpName,
- DWORD dwFlags,
- DWORD dwDesiredAccess)
+ LPCSTR lpName,
+ DWORD dwFlags,
+ DWORD dwDesiredAccess)
{
int fd = ::eventfd(dwFlags & CREATE_EVENT_INITIAL_SET ? 1 : 0, EFD_CLOEXEC | EFD_NONBLOCK);
// Make sure not to return a zero handle, duplicate the fd if necessary
- if(fd == 0)
+ if (fd == 0)
{
int nextFd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
- if(fcntl(nextFd, F_SETFL, O_NONBLOCK) == -1)
+ if (fcntl(nextFd, F_SETFL, O_NONBLOCK) == -1)
{
close(nextFd);
nextFd = -1;
@@ -63,7 +62,7 @@ HANDLE CreateEventEx(
BOOL CloseHandle(HANDLE h)
{
- if(h == 0)
+ if (h == 0)
{
return 1;
}
@@ -79,22 +78,22 @@ BOOL ResetEvent(HANDLE h)
uint64_t x;
int r = 0;
int nEvents = poll(&pfd, 1, 0);
- if(pfd.revents != POLLIN)
+ if (pfd.revents != POLLIN)
{
// Nothing to read, already reset
return 1;
}
- if(nEvents != 1)
+ if (nEvents != 1)
{
return 0;
}
r = read(fd, &x, sizeof(x));
- if(r == sizeof(x))
+ if (r == sizeof(x))
{
// We reset it
return 1;
}
- if(r == -1 && errno == EAGAIN)
+ if (r == -1 && errno == EAGAIN)
{
// Something else reset it
return 1;
@@ -106,18 +105,18 @@ BOOL SetEvent(HANDLE h)
{
int fd = _handleToFD(h);
pollfd pfd{fd, POLLOUT, 0};
- for(;;)
+ for (;;)
{
int nEvents = poll(&pfd, 1, -1);
SLANG_ASSERT(nEvents != -1);
SLANG_ASSERT(nEvents != 0); // shouldn't have timed out
const uint64_t one = 1;
int w = ::write(fd, &one, sizeof(one));
- if(w == sizeof(one))
+ if (w == sizeof(one))
{
return 1;
}
- if(errno != EAGAIN)
+ if (errno != EAGAIN)
{
return 0;
}
@@ -137,11 +136,11 @@ DWORD WaitForSingleObject(const HANDLE h, const DWORD ms)
const bool isInfinite = ms == INFINITE;
const DWORD fiveSeconds = 5000;
int nEvents = poll(&pfd, 1, isInfinite ? fiveSeconds : ms);
- if(pfd.revents != POLLIN)
+ if (pfd.revents != POLLIN)
{
return WAIT_FAILED;
}
- if(nEvents == -1)
+ if (nEvents == -1)
{
return WAIT_FAILED;
}
@@ -149,29 +148,25 @@ DWORD WaitForSingleObject(const HANDLE h, const DWORD ms)
{
return isInfinite ? WAIT_FAILED : WAIT_TIMEOUT;
}
- if(manualReset)
+ if (manualReset)
{
return WAIT_OBJECT_0;
}
r = read(fd, &x, sizeof(x));
- if(r == sizeof(x))
+ if (r == sizeof(x))
{
return WAIT_OBJECT_0;
}
- if(r == -1 && errno == EAGAIN)
+ if (r == -1 && errno == EAGAIN)
{
return isInfinite ? WAIT_FAILED : WAIT_TIMEOUT;
}
return WAIT_FAILED;
}
-DWORD WaitForMultipleObjects(
- DWORD n,
- const HANDLE *hs,
- BOOL bWaitAll,
- DWORD requestedMs)
+DWORD WaitForMultipleObjects(DWORD n, const HANDLE* hs, BOOL bWaitAll, DWORD requestedMs)
{
- if(n == 0)
+ if (n == 0)
{
return bWaitAll ? WAIT_OBJECT_0 : WAIT_FAILED;
}
@@ -185,22 +180,22 @@ DWORD WaitForMultipleObjects(
DWORD res;
int fds[n];
int flagss[n];
- epoll_event evs[n+1]; // +1 for our timer
+ epoll_event evs[n + 1]; // +1 for our timer
int ufd = -1;
int epfd = epoll_create1(EPOLL_CLOEXEC);
- if(epfd == -1)
+ if (epfd == -1)
{
goto fail;
}
- for(int i = 0; i < n; ++i)
+ for (int i = 0; i < n; ++i)
{
fds[i] = _handleToFD(hs[i]);
flagss[i] = _handleToFlags(hs[i]);
epoll_event ev;
ev.data.fd = fds[i];
ev.events = EPOLLIN | EPOLLONESHOT;
- if(epoll_ctl(epfd, EPOLL_CTL_ADD, fds[i], &ev) == -1)
+ if (epoll_ctl(epfd, EPOLL_CTL_ADD, fds[i], &ev) == -1)
{
goto fail;
}
@@ -214,13 +209,13 @@ DWORD WaitForMultipleObjects(
// after the other, and put the values back if we can't claim them all, it
// sucks.
//
- if(bWaitAll)
+ if (bWaitAll)
{
// Use a timer to easily know for sure when we've timed out
- if(dwMilliseconds != INFINITE)
+ if (dwMilliseconds != INFINITE)
{
ufd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
- if(ufd == -1)
+ if (ufd == -1)
{
goto fail;
}
@@ -229,13 +224,13 @@ DWORD WaitForMultipleObjects(
spec.it_interval.tv_nsec = 0;
spec.it_value.tv_sec = 0;
spec.it_value.tv_nsec = 1000000 * dwMilliseconds;
- if(timerfd_settime(ufd, 0, &spec, nullptr) == -1)
+ if (timerfd_settime(ufd, 0, &spec, nullptr) == -1)
{
goto fail;
}
evs[n].data.fd = ufd;
evs[n].events = EPOLLIN | EPOLLONESHOT;
- if(epoll_ctl(epfd, EPOLL_CTL_ADD, ufd, &evs[n]) == -1)
+ if (epoll_ctl(epfd, EPOLL_CTL_ADD, ufd, &evs[n]) == -1)
{
goto fail;
}
@@ -250,29 +245,29 @@ DWORD WaitForMultipleObjects(
do
{
// Wait until epoll tells us they're all available, or the timer is
- const int nEvents = epoll_wait(epfd, evs, n+1, -1);
+ const int nEvents = epoll_wait(epfd, evs, n + 1, -1);
// We didn't specify a timeout, so 0 results is abnormal
- if(nEvents < 1)
+ if (nEvents < 1)
{
goto fail;
}
// Process all the returned fds
- for(int i = 0; i < nEvents; ++i)
+ for (int i = 0; i < nEvents; ++i)
{
- if(!(evs[i].events & EPOLLIN))
+ if (!(evs[i].events & EPOLLIN))
{
// Something exceptional happened on the fd
// Possibly we could just continue and hope it doesn't
// happen again?
goto fail;
}
- if(evs[i].data.fd == ufd)
+ if (evs[i].data.fd == ufd)
{
// We're out of time, make this the last loop
uint64_t x;
int r = read(ufd, &x, sizeof(x));
- if(r == sizeof(x))
+ if (r == sizeof(x))
{
timesUp = true;
}
@@ -287,11 +282,10 @@ DWORD WaitForMultipleObjects(
++nSeenEvents;
}
}
- }
- while(!(timesUp || nSeenEvents == n));
+ } while (!(timesUp || nSeenEvents == n));
// If we got here without seeing enough events, we must have timed out
- if(nSeenEvents < n)
+ if (nSeenEvents < n)
{
res = isInfinite ? WAIT_FAILED : WAIT_TIMEOUT;
goto end;
@@ -303,51 +297,52 @@ DWORD WaitForMultipleObjects(
// makes the code a bit cleaner.
// Put all the events back in our epoll instance and see if they're
// all readable.
- for(int i = 0; i < n; ++i)
+ for (int i = 0; i < n; ++i)
{
epoll_event modEv;
modEv.data.fd = fds[i];
modEv.events = EPOLLIN | EPOLLONESHOT;
- if(epoll_ctl(epfd, EPOLL_CTL_MOD, fds[i], &modEv) == -1)
+ if (epoll_ctl(epfd, EPOLL_CTL_MOD, fds[i], &modEv) == -1)
{
goto fail;
}
}
// Remove the timer if we're using it
- if(dwMilliseconds != INFINITE && epoll_ctl(epfd, EPOLL_CTL_DEL, ufd, nullptr) == -1)
+ if (dwMilliseconds != INFINITE && epoll_ctl(epfd, EPOLL_CTL_DEL, ufd, nullptr) == -1)
{
goto fail;
}
int nEvents = epoll_wait(epfd, evs, n, 0);
- if(nEvents < 0)
+ if (nEvents < 0)
{
goto fail;
}
- else if(nEvents < n)
+ else if (nEvents < n)
{
// They're not all still available :(
// Put our timer back in and try again from the top
- if(dwMilliseconds != INFINITE && epoll_ctl(epfd, EPOLL_CTL_ADD, ufd, &evs[n]) == -1)
+ if (dwMilliseconds != INFINITE &&
+ epoll_ctl(epfd, EPOLL_CTL_ADD, ufd, &evs[n]) == -1)
{
goto fail;
}
// Put back the any fds which did trigger
- for(int i = 0; i < nEvents; ++i)
+ for (int i = 0; i < nEvents; ++i)
{
epoll_event modEv = evs[i];
modEv.events = EPOLLIN | EPOLLONESHOT;
- if(epoll_ctl(epfd, EPOLL_CTL_MOD, modEv.data.fd, &modEv) == -1)
+ if (epoll_ctl(epfd, EPOLL_CTL_MOD, modEv.data.fd, &modEv) == -1)
{
goto fail;
}
}
continue;
}
- else if(nEvents == n)
+ else if (nEvents == n)
{
- for(int i = 0; i < nEvents; ++i)
+ for (int i = 0; i < nEvents; ++i)
{
- if(!(evs->events & EPOLLIN))
+ if (!(evs->events & EPOLLIN))
{
goto fail;
}
@@ -358,19 +353,19 @@ DWORD WaitForMultipleObjects(
uint64_t vs[n];
int i;
bool failure = false;
- for(i = 0; i < n; ++i)
+ for (i = 0; i < n; ++i)
{
- if(flagss[i] & CREATE_EVENT_MANUAL_RESET)
+ if (flagss[i] & CREATE_EVENT_MANUAL_RESET)
{
// We don't need to read this to unset it
continue;
}
int r = read(fds[i], &vs[i], sizeof(vs[i]));
- if(r == sizeof(vs[i]))
+ if (r == sizeof(vs[i]))
{
continue;
}
- else if(r == -1 && errno == EAGAIN)
+ else if (r == -1 && errno == EAGAIN)
{
// contention, put things back and try again
break;
@@ -385,9 +380,9 @@ DWORD WaitForMultipleObjects(
if (i < n)
{
// contention or failure
- for(int j = 0; j < i; ++j)
+ for (int j = 0; j < i; ++j)
{
- if(flagss[i] & CREATE_EVENT_MANUAL_RESET)
+ if (flagss[i] & CREATE_EVENT_MANUAL_RESET)
{
// We didn't read, so we shouldn't write
continue;
@@ -401,7 +396,7 @@ DWORD WaitForMultipleObjects(
int w = write(fds[j], &vs[j], sizeof(vs[j]));
SLANG_ASSERT(w == sizeof(vs[j]));
}
- if(failure)
+ if (failure)
{
goto fail;
}
@@ -413,28 +408,29 @@ DWORD WaitForMultipleObjects(
goto end;
}
- // If we get here then we've got some contention, go back to the top and try again (or timeout)
- }
- while(!timesUp);
+ // If we get here then we've got some contention, go back to the top and try again (or
+ // timeout)
+ } while (!timesUp);
}
else
{
// Wait any
- const int nEvents = epoll_wait(epfd, evs, n, dwMilliseconds == INFINITE ? -1 : dwMilliseconds);
- if(nEvents == -1)
+ const int nEvents =
+ epoll_wait(epfd, evs, n, dwMilliseconds == INFINITE ? -1 : dwMilliseconds);
+ if (nEvents == -1)
{
goto fail;
}
- if(nEvents == 0)
+ if (nEvents == 0)
{
res = isInfinite ? WAIT_FAILED : WAIT_TIMEOUT;
goto end;
}
// Try reads until we get one
- for(int i = 0; i < nEvents; ++i)
+ for (int i = 0; i < nEvents; ++i)
{
uint64_t x;
- if(!evs[i].events & EPOLLIN)
+ if (!evs[i].events & EPOLLIN)
{
continue;
}
diff --git a/tools/gfx/d3d12/d3d12-posix-synchapi.h b/tools/gfx/d3d12/d3d12-posix-synchapi.h
index ba5a15b0a..15aef9418 100644
--- a/tools/gfx/d3d12/d3d12-posix-synchapi.h
+++ b/tools/gfx/d3d12/d3d12-posix-synchapi.h
@@ -33,20 +33,20 @@
#define WAIT_FAILED 0xffffffff
#define WAIT_OBJECT_0 0
-typedef struct _SECURITY_ATTRIBUTES *LPSECURITY_ATTRIBUTES;
+typedef struct _SECURITY_ATTRIBUTES* LPSECURITY_ATTRIBUTES;
#define CREATE_EVENT_MANUAL_RESET 1
-#define CREATE_EVENT_INITIAL_SET 2
+#define CREATE_EVENT_INITIAL_SET 2
-#define SYNCHRONIZE 0x00100000
-#define STANDARD_RIGHTS_REQUIRED 0x000f0000
-#define EVENT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3)
+#define SYNCHRONIZE 0x00100000
+#define STANDARD_RIGHTS_REQUIRED 0x000f0000
+#define EVENT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3)
HANDLE CreateEventEx(
LPSECURITY_ATTRIBUTES lpEventAttributes,
- LPCSTR lpName,
- DWORD dwFlags,
- DWORD dwDesiredAccess);
+ LPCSTR lpName,
+ DWORD dwFlags,
+ DWORD dwDesiredAccess);
BOOL CloseHandle(HANDLE h);
@@ -57,9 +57,9 @@ BOOL SetEvent(HANDLE h);
DWORD WaitForSingleObject(HANDLE h, DWORD ms);
DWORD WaitForMultipleObjects(
- DWORD nHandles,
- const HANDLE *handles,
- BOOL bWaitAll,
- DWORD dwMilliseconds);
+ DWORD nHandles,
+ const HANDLE* handles,
+ BOOL bWaitAll,
+ DWORD dwMilliseconds);
#endif // SLANG_LINUX_FAMILY
diff --git a/tools/gfx/d3d12/d3d12-query.cpp b/tools/gfx/d3d12/d3d12-query.cpp
index 6b2e92980..d0191e349 100644
--- a/tools/gfx/d3d12/d3d12-query.cpp
+++ b/tools/gfx/d3d12/d3d12-query.cpp
@@ -2,7 +2,6 @@
#include "d3d12-query.h"
#include "d3d12-command-queue.h"
-
#include "d3d12-helper-functions.h"
namespace gfx
@@ -26,8 +25,7 @@ Result QueryPoolImpl::init(const IQueryPool::Desc& desc, DeviceImpl* device)
heapDesc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
m_queryType = D3D12_QUERY_TYPE_TIMESTAMP;
break;
- default:
- return SLANG_E_INVALID_ARG;
+ default: return SLANG_E_INVALID_ARG;
}
// Create query heap.
@@ -54,7 +52,8 @@ Result QueryPoolImpl::init(const IQueryPool::Desc& desc, DeviceImpl* device)
// Create command allocator.
SLANG_RETURN_ON_FAIL(d3dDevice->CreateCommandAllocator(
- D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(m_commandAllocator.writeRef())));
+ D3D12_COMMAND_LIST_TYPE_DIRECT,
+ IID_PPV_ARGS(m_commandAllocator.writeRef())));
// Create command list.
SLANG_RETURN_ON_FAIL(d3dDevice->CreateCommandList(
@@ -99,7 +98,8 @@ Result QueryPoolImpl::getResult(GfxIndex queryIndex, GfxCount count, uint64_t* d
int8_t* mappedData = nullptr;
D3D12_RANGE readRange = {
- sizeof(uint64_t) * queryIndex, sizeof(uint64_t) * (queryIndex + count) };
+ sizeof(uint64_t) * queryIndex,
+ sizeof(uint64_t) * (queryIndex + count)};
m_readBackBuffer.getResource()->Map(0, &readRange, (void**)&mappedData);
memcpy(data, mappedData + sizeof(uint64_t) * queryIndex, sizeof(uint64_t) * count);
m_readBackBuffer.getResource()->Unmap(0, nullptr);
@@ -119,7 +119,9 @@ IQueryPool* PlainBufferProxyQueryPoolImpl::getInterface(const Guid& guid)
}
Result PlainBufferProxyQueryPoolImpl::init(
- const IQueryPool::Desc& desc, DeviceImpl* device, uint32_t stride)
+ const IQueryPool::Desc& desc,
+ DeviceImpl* device,
+ uint32_t stride)
{
ComPtr<IBufferResource> bufferResource;
IBufferResource::Desc bufferDesc = {};
@@ -187,8 +189,8 @@ Result PlainBufferProxyQueryPoolImpl::getResult(GfxIndex queryIndex, GfxCount co
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr));
- encodeInfo.d3dCommandList->CopyBufferRegion(
- stageBuf, 0, m_bufferResource->m_resource.getResource(), 0, size);
+ encodeInfo.d3dCommandList
+ ->CopyBufferRegion(stageBuf, 0, m_bufferResource->m_resource.getResource(), 0, size);
m_device->submitResourceCommandsAndWait(encodeInfo);
void* ptr = nullptr;
stageBuf.getResource()->Map(0, nullptr, &ptr);
diff --git a/tools/gfx/d3d12/d3d12-query.h b/tools/gfx/d3d12/d3d12-query.h
index 770990e81..dff3fbd21 100644
--- a/tools/gfx/d3d12/d3d12-query.h
+++ b/tools/gfx/d3d12/d3d12-query.h
@@ -2,8 +2,8 @@
#pragma once
#include "d3d12-base.h"
-#include "d3d12-device.h"
#include "d3d12-buffer.h"
+#include "d3d12-device.h"
namespace gfx
{
@@ -18,7 +18,7 @@ public:
Result init(const IQueryPool::Desc& desc, DeviceImpl* device);
virtual SLANG_NO_THROW Result SLANG_MCALL
- getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
+ getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
void writeTimestamp(ID3D12GraphicsCommandList* cmdList, GfxIndex index);
@@ -41,14 +41,14 @@ class PlainBufferProxyQueryPoolImpl : public QueryPoolBase
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
- IQueryPool* getInterface(const Guid& guid);
+ IQueryPool* getInterface(const Guid& guid);
public:
Result init(const IQueryPool::Desc& desc, DeviceImpl* device, uint32_t stride);
virtual SLANG_NO_THROW Result SLANG_MCALL reset() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
+ getResult(GfxIndex queryIndex, GfxCount count, uint64_t* data) override;
public:
QueryType m_queryType;
diff --git a/tools/gfx/d3d12/d3d12-resource-views.cpp b/tools/gfx/d3d12/d3d12-resource-views.cpp
index b156f6ab6..a760caef8 100644
--- a/tools/gfx/d3d12/d3d12-resource-views.cpp
+++ b/tools/gfx/d3d12/d3d12-resource-views.cpp
@@ -1,5 +1,6 @@
// d3d12-resource-views.cpp
#include "d3d12-resource-views.h"
+
#include "d3d12-device.h"
namespace gfx
@@ -34,104 +35,106 @@ SlangResult createD3D12BufferDescriptor(
const auto counterResourceImpl = static_cast<BufferResourceImpl*>(counterBuffer);
uint64_t offset = desc.bufferRange.offset;
- uint64_t size = desc.bufferRange.size == 0 ? buffer->getDesc()->sizeInBytes - offset : desc.bufferRange.size;
+ uint64_t size = desc.bufferRange.size == 0 ? buffer->getDesc()->sizeInBytes - offset
+ : desc.bufferRange.size;
switch (desc.type)
{
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
case IResourceView::Type::UnorderedAccess:
- {
- D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
- uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
- uavDesc.Format = D3DUtil::getMapFormat(desc.format);
- if (bufferStride)
- {
- uavDesc.Buffer.FirstElement = offset / bufferStride;
- uavDesc.Buffer.NumElements = UINT(size / bufferStride);
- uavDesc.Buffer.StructureByteStride = bufferStride;
- }
- else if (desc.format == Format::Unknown)
- {
- uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
- uavDesc.Buffer.FirstElement = offset / 4;
- uavDesc.Buffer.NumElements = UINT(size / 4);
- uavDesc.Buffer.Flags |= D3D12_BUFFER_UAV_FLAG_RAW;
- }
- else
{
- FormatInfo sizeInfo;
- gfxGetFormatInfo(desc.format, &sizeInfo);
- assert(sizeInfo.pixelsPerBlock == 1);
- uavDesc.Buffer.FirstElement = offset / sizeInfo.blockSizeInBytes;
- uavDesc.Buffer.NumElements = UINT(size / sizeInfo.blockSizeInBytes);
+ D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
+ uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
+ uavDesc.Format = D3DUtil::getMapFormat(desc.format);
+ if (bufferStride)
+ {
+ uavDesc.Buffer.FirstElement = offset / bufferStride;
+ uavDesc.Buffer.NumElements = UINT(size / bufferStride);
+ uavDesc.Buffer.StructureByteStride = bufferStride;
+ }
+ else if (desc.format == Format::Unknown)
+ {
+ uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
+ uavDesc.Buffer.FirstElement = offset / 4;
+ uavDesc.Buffer.NumElements = UINT(size / 4);
+ uavDesc.Buffer.Flags |= D3D12_BUFFER_UAV_FLAG_RAW;
+ }
+ else
+ {
+ FormatInfo sizeInfo;
+ gfxGetFormatInfo(desc.format, &sizeInfo);
+ assert(sizeInfo.pixelsPerBlock == 1);
+ uavDesc.Buffer.FirstElement = offset / sizeInfo.blockSizeInBytes;
+ uavDesc.Buffer.NumElements = UINT(size / sizeInfo.blockSizeInBytes);
+ }
+
+ if (size >= (1ull << 32) - 8)
+ {
+ // D3D12 does not support view descriptors that has size near 4GB.
+ // We will not create actual SRV/UAVs for such large buffers.
+ // However, a buffer this large can still be bound as root parameter.
+ // So instead of failing, we quietly ignore descriptor creation.
+ outDescriptor->cpuHandle.ptr = 0;
+ }
+ else
+ {
+ SLANG_RETURN_ON_FAIL(descriptorHeap->allocate(outDescriptor));
+ device->m_device->CreateUnorderedAccessView(
+ resourceImpl->m_resource,
+ counterResourceImpl ? counterResourceImpl->m_resource.getResource() : nullptr,
+ &uavDesc,
+ outDescriptor->cpuHandle);
+ }
}
-
- if (size >= (1ull << 32) - 8)
- {
- // D3D12 does not support view descriptors that has size near 4GB.
- // We will not create actual SRV/UAVs for such large buffers.
- // However, a buffer this large can still be bound as root parameter.
- // So instead of failing, we quietly ignore descriptor creation.
- outDescriptor->cpuHandle.ptr = 0;
- }
- else
- {
- SLANG_RETURN_ON_FAIL(descriptorHeap->allocate(outDescriptor));
- device->m_device->CreateUnorderedAccessView(
- resourceImpl->m_resource,
- counterResourceImpl ? counterResourceImpl->m_resource.getResource() : nullptr,
- &uavDesc,
- outDescriptor->cpuHandle);
- }
- }
- break;
+ break;
case IResourceView::Type::ShaderResource:
- {
- D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
- srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
- srvDesc.Format = D3DUtil::getMapFormat(desc.format);
- srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
- if (bufferStride)
- {
- srvDesc.Buffer.FirstElement = offset / bufferStride;
- srvDesc.Buffer.NumElements = UINT(size / bufferStride);
- srvDesc.Buffer.StructureByteStride = bufferStride;
- }
- else if (desc.format == Format::Unknown)
{
- srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
- srvDesc.Buffer.FirstElement = offset / 4;
- srvDesc.Buffer.NumElements = UINT(size / 4);
- srvDesc.Buffer.Flags |= D3D12_BUFFER_SRV_FLAG_RAW;
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
+ srvDesc.Format = D3DUtil::getMapFormat(desc.format);
+ srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ if (bufferStride)
+ {
+ srvDesc.Buffer.FirstElement = offset / bufferStride;
+ srvDesc.Buffer.NumElements = UINT(size / bufferStride);
+ srvDesc.Buffer.StructureByteStride = bufferStride;
+ }
+ else if (desc.format == Format::Unknown)
+ {
+ srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
+ srvDesc.Buffer.FirstElement = offset / 4;
+ srvDesc.Buffer.NumElements = UINT(size / 4);
+ srvDesc.Buffer.Flags |= D3D12_BUFFER_SRV_FLAG_RAW;
+ }
+ else
+ {
+ FormatInfo sizeInfo;
+ gfxGetFormatInfo(desc.format, &sizeInfo);
+ assert(sizeInfo.pixelsPerBlock == 1);
+ srvDesc.Buffer.FirstElement = offset / sizeInfo.blockSizeInBytes;
+ srvDesc.Buffer.NumElements = UINT(size / sizeInfo.blockSizeInBytes);
+ }
+
+ if (size >= (1ull << 32) - 8)
+ {
+ // D3D12 does not support view descriptors that has size near 4GB.
+ // We will not create actual SRV/UAVs for such large buffers.
+ // However, a buffer this large can still be bound as root parameter.
+ // So instead of failing, we quietly ignore descriptor creation.
+ outDescriptor->cpuHandle.ptr = 0;
+ }
+ else
+ {
+ SLANG_RETURN_ON_FAIL(descriptorHeap->allocate(outDescriptor));
+ device->m_device->CreateShaderResourceView(
+ resourceImpl->m_resource,
+ &srvDesc,
+ outDescriptor->cpuHandle);
+ }
}
- else
- {
- FormatInfo sizeInfo;
- gfxGetFormatInfo(desc.format, &sizeInfo);
- assert(sizeInfo.pixelsPerBlock == 1);
- srvDesc.Buffer.FirstElement = offset / sizeInfo.blockSizeInBytes;
- srvDesc.Buffer.NumElements = UINT(size / sizeInfo.blockSizeInBytes);
- }
-
- if (size >= (1ull << 32) - 8)
- {
- // D3D12 does not support view descriptors that has size near 4GB.
- // We will not create actual SRV/UAVs for such large buffers.
- // However, a buffer this large can still be bound as root parameter.
- // So instead of failing, we quietly ignore descriptor creation.
- outDescriptor->cpuHandle.ptr = 0;
- }
- else
- {
- SLANG_RETURN_ON_FAIL(descriptorHeap->allocate(outDescriptor));
- device->m_device->CreateShaderResourceView(
- resourceImpl->m_resource, &srvDesc, outDescriptor->cpuHandle);
- }
- }
- break;
+ break;
}
return SLANG_OK;
}
diff --git a/tools/gfx/d3d12/d3d12-resource-views.h b/tools/gfx/d3d12/d3d12-resource-views.h
index ac80a9368..379aaa7aa 100644
--- a/tools/gfx/d3d12/d3d12-resource-views.h
+++ b/tools/gfx/d3d12/d3d12-resource-views.h
@@ -1,8 +1,8 @@
// d3d12-resource-views.h
#pragma once
-#include "d3d12-base.h"
#include "../d3d/d3d-util.h"
+#include "d3d12-base.h"
#include "d3d12-buffer.h"
namespace gfx
@@ -44,9 +44,7 @@ SlangResult createD3D12BufferDescriptor(
D3D12GeneralExpandingDescriptorHeap* descriptorHeap,
D3D12Descriptor* outDescriptor);
-class ResourceViewImpl
- : public ResourceViewBase
- , public ResourceViewInternalImpl
+class ResourceViewImpl : public ResourceViewBase, public ResourceViewInternalImpl
{
public:
Slang::RefPtr<Resource> m_resource;
@@ -57,9 +55,7 @@ public:
#if SLANG_GFX_HAS_DXR_SUPPORT
-class AccelerationStructureImpl
- : public AccelerationStructureBase
- , public ResourceViewInternalImpl
+class AccelerationStructureImpl : public AccelerationStructureBase, public ResourceViewInternalImpl
{
public:
RefPtr<BufferResourceImpl> m_buffer;
diff --git a/tools/gfx/d3d12/d3d12-resource.cpp b/tools/gfx/d3d12/d3d12-resource.cpp
index 8975f5825..273e14f29 100644
--- a/tools/gfx/d3d12/d3d12-resource.cpp
+++ b/tools/gfx/d3d12/d3d12-resource.cpp
@@ -1,29 +1,34 @@
// d3d12-resource.cpp
#include "d3d12-resource.h"
-namespace gfx {
+namespace gfx
+{
using namespace Slang;
-/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! D3D12BarrierSubmitter !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
+/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! D3D12BarrierSubmitter
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
void D3D12BarrierSubmitter::_flush()
{
- assert(m_numBarriers > 0);
+ assert(m_numBarriers > 0);
- if (m_commandList)
- {
- m_commandList->ResourceBarrier(UINT(m_numBarriers), m_barriers);
- }
- m_numBarriers = 0;
+ if (m_commandList)
+ {
+ m_commandList->ResourceBarrier(UINT(m_numBarriers), m_barriers);
+ }
+ m_numBarriers = 0;
}
D3D12_RESOURCE_BARRIER& D3D12BarrierSubmitter::_expandOne()
{
- _flush();
- return m_barriers[m_numBarriers++];
+ _flush();
+ return m_barriers[m_numBarriers++];
}
-void D3D12BarrierSubmitter::transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES prevState, D3D12_RESOURCE_STATES nextState)
+void D3D12BarrierSubmitter::transition(
+ ID3D12Resource* resource,
+ D3D12_RESOURCE_STATES prevState,
+ D3D12_RESOURCE_STATES nextState)
{
if (nextState != prevState)
{
@@ -53,11 +58,13 @@ void D3D12BarrierSubmitter::transition(ID3D12Resource* resource, D3D12_RESOURCE_
}
}
-/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! D3D12ResourceBase !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
+/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! D3D12ResourceBase
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
-/* static */DXGI_FORMAT D3D12ResourceBase::calcFormat(D3DUtil::UsageType usage, ID3D12Resource* resource)
+/* static */ DXGI_FORMAT
+D3D12ResourceBase::calcFormat(D3DUtil::UsageType usage, ID3D12Resource* resource)
{
- return resource ? D3DUtil::calcFormat(usage, resource->GetDesc().Format) : DXGI_FORMAT_UNKNOWN;
+ return resource ? D3DUtil::calcFormat(usage, resource->GetDesc().Format) : DXGI_FORMAT_UNKNOWN;
}
void D3D12ResourceBase::transition(
@@ -65,16 +72,16 @@ void D3D12ResourceBase::transition(
D3D12_RESOURCE_STATES nextState,
D3D12BarrierSubmitter& submitter)
{
- // Transition only if there is a resource
+ // Transition only if there is a resource
if (m_resource && oldState != nextState)
- {
+ {
submitter.transition(m_resource, oldState, nextState);
}
}
/* !!!!!!!!!!!!!!!!!!!!!!!!! D3D12Resource !!!!!!!!!!!!!!!!!!!!!!!! */
-/* static */void D3D12Resource::setDebugName(ID3D12Resource* resource, const char* name)
+/* static */ void D3D12Resource::setDebugName(ID3D12Resource* resource, const char* name)
{
if (resource)
{
@@ -84,63 +91,75 @@ void D3D12ResourceBase::transition(
void D3D12Resource::setDebugName(const char* name)
{
- setDebugName(m_resource, name);
+ setDebugName(m_resource, name);
}
void D3D12Resource::setDebugName(const wchar_t* name)
{
- if (m_resource)
- {
- m_resource->SetName(name);
- }
+ if (m_resource)
+ {
+ m_resource->SetName(name);
+ }
}
void D3D12Resource::setResource(ID3D12Resource* resource)
{
- if (resource != m_resource)
- {
- if (resource)
- {
- resource->AddRef();
- }
- if (m_resource)
- {
- m_resource->Release();
- }
- m_resource = resource;
- }
+ if (resource != m_resource)
+ {
+ if (resource)
+ {
+ resource->AddRef();
+ }
+ if (m_resource)
+ {
+ m_resource->Release();
+ }
+ m_resource = resource;
+ }
}
void D3D12Resource::setResourceNull()
{
- if (m_resource)
- {
- m_resource->Release();
- m_resource = nullptr;
- }
+ if (m_resource)
+ {
+ m_resource->Release();
+ m_resource = nullptr;
+ }
}
-Result D3D12Resource::initCommitted(ID3D12Device* device, const D3D12_HEAP_PROPERTIES& heapProps, D3D12_HEAP_FLAGS heapFlags, const D3D12_RESOURCE_DESC& resourceDesc, D3D12_RESOURCE_STATES initState, const D3D12_CLEAR_VALUE * clearValue)
+Result D3D12Resource::initCommitted(
+ ID3D12Device* device,
+ const D3D12_HEAP_PROPERTIES& heapProps,
+ D3D12_HEAP_FLAGS heapFlags,
+ const D3D12_RESOURCE_DESC& resourceDesc,
+ D3D12_RESOURCE_STATES initState,
+ const D3D12_CLEAR_VALUE* clearValue)
{
- setResourceNull();
- ComPtr<ID3D12Resource> resource;
- SLANG_RETURN_ON_FAIL(device->CreateCommittedResource(&heapProps, heapFlags, &resourceDesc, initState, clearValue, IID_PPV_ARGS(resource.writeRef())));
- setResource(resource);
- return SLANG_OK;
+ setResourceNull();
+ ComPtr<ID3D12Resource> resource;
+ SLANG_RETURN_ON_FAIL(device->CreateCommittedResource(
+ &heapProps,
+ heapFlags,
+ &resourceDesc,
+ initState,
+ clearValue,
+ IID_PPV_ARGS(resource.writeRef())));
+ setResource(resource);
+ return SLANG_OK;
}
ID3D12Resource* D3D12Resource::detach()
{
- ID3D12Resource* resource = m_resource;
- m_resource = nullptr;
- return resource;
+ ID3D12Resource* resource = m_resource;
+ m_resource = nullptr;
+ return resource;
}
void D3D12Resource::swap(ComPtr<ID3D12Resource>& resourceInOut)
{
- ID3D12Resource* tmp = m_resource;
- m_resource = resourceInOut.detach();
- resourceInOut.attach(tmp);
+ ID3D12Resource* tmp = m_resource;
+ m_resource = resourceInOut.detach();
+ resourceInOut.attach(tmp);
}
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/d3d12/d3d12-resource.h b/tools/gfx/d3d12/d3d12-resource.h
index cd56793cc..cbf47ed66 100644
--- a/tools/gfx/d3d12/d3d12-resource.h
+++ b/tools/gfx/d3d12/d3d12-resource.h
@@ -11,13 +11,14 @@
#pragma pop_macro("NOMINMAX")
#pragma pop_macro("WIN32_LEAN_AND_MEAN")
-#include <dxgi1_4.h>
-#include <d3d12.h>
-
-#include "slang-com-ptr.h"
#include "../d3d/d3d-util.h"
+#include "slang-com-ptr.h"
-namespace gfx {
+#include <d3d12.h>
+#include <dxgi1_4.h>
+
+namespace gfx
+{
// Enables more conservative barriers - restoring the state of resources after they are used.
// Should not need to be enabled in normal builds, as the barriers should correctly sync resources
@@ -26,95 +27,120 @@ namespace gfx {
struct D3D12BarrierSubmitter
{
- enum { MAX_BARRIERS = 8 };
-
- /// Expand one space to hold a barrier
- SLANG_FORCE_INLINE D3D12_RESOURCE_BARRIER& expandOne() { return (m_numBarriers < MAX_BARRIERS) ? m_barriers[m_numBarriers++] : _expandOne(); }
- /// Flush barriers to command list
- SLANG_FORCE_INLINE void flush() { if (m_numBarriers > 0) _flush(); }
-
- /// Transition resource from prevState to nextState
- void transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES prevState, D3D12_RESOURCE_STATES nextState);
-
- /// Ctor
- SLANG_FORCE_INLINE D3D12BarrierSubmitter(ID3D12GraphicsCommandList* commandList) : m_numBarriers(0), m_commandList(commandList) { }
- /// Dtor
- SLANG_FORCE_INLINE ~D3D12BarrierSubmitter() { flush(); }
+ enum
+ {
+ MAX_BARRIERS = 8
+ };
+
+ /// Expand one space to hold a barrier
+ SLANG_FORCE_INLINE D3D12_RESOURCE_BARRIER& expandOne()
+ {
+ return (m_numBarriers < MAX_BARRIERS) ? m_barriers[m_numBarriers++] : _expandOne();
+ }
+ /// Flush barriers to command list
+ SLANG_FORCE_INLINE void flush()
+ {
+ if (m_numBarriers > 0)
+ _flush();
+ }
+
+ /// Transition resource from prevState to nextState
+ void transition(
+ ID3D12Resource* resource,
+ D3D12_RESOURCE_STATES prevState,
+ D3D12_RESOURCE_STATES nextState);
+
+ /// Ctor
+ SLANG_FORCE_INLINE D3D12BarrierSubmitter(ID3D12GraphicsCommandList* commandList)
+ : m_numBarriers(0), m_commandList(commandList)
+ {
+ }
+ /// Dtor
+ SLANG_FORCE_INLINE ~D3D12BarrierSubmitter() { flush(); }
protected:
- D3D12_RESOURCE_BARRIER& _expandOne();
- void _flush();
+ D3D12_RESOURCE_BARRIER& _expandOne();
+ void _flush();
- ID3D12GraphicsCommandList* m_commandList;
- int m_numBarriers;
- D3D12_RESOURCE_BARRIER m_barriers[MAX_BARRIERS];
+ ID3D12GraphicsCommandList* m_commandList;
+ int m_numBarriers;
+ D3D12_RESOURCE_BARRIER m_barriers[MAX_BARRIERS];
};
-/** The base class for resource types allows for tracking of state. It does not allow for setting of the resource though, such that
-an interface can return a D3D12ResourceBase, and a client cant manipulate it's state, but it cannot replace/change the actual resource */
+/** The base class for resource types allows for tracking of state. It does not allow for setting of
+the resource though, such that an interface can return a D3D12ResourceBase, and a client cant
+manipulate it's state, but it cannot replace/change the actual resource */
struct D3D12ResourceBase
{
- /// Add a transition if necessary to the list
+ /// Add a transition if necessary to the list
void transition(
- D3D12_RESOURCE_STATES currentState,
- D3D12_RESOURCE_STATES nextState,
- D3D12BarrierSubmitter& submitter);
- /// Get the associated resource
- SLANG_FORCE_INLINE ID3D12Resource* getResource() const { return m_resource; }
+ D3D12_RESOURCE_STATES currentState,
+ D3D12_RESOURCE_STATES nextState,
+ D3D12BarrierSubmitter& submitter);
+ /// Get the associated resource
+ SLANG_FORCE_INLINE ID3D12Resource* getResource() const { return m_resource; }
- /// True if a resource is set
- SLANG_FORCE_INLINE bool isSet() const { return m_resource != nullptr; }
+ /// True if a resource is set
+ SLANG_FORCE_INLINE bool isSet() const { return m_resource != nullptr; }
- /// Coercible into ID3D12Resource
- SLANG_FORCE_INLINE operator ID3D12Resource*() const { return m_resource; }
+ /// Coercible into ID3D12Resource
+ SLANG_FORCE_INLINE operator ID3D12Resource*() const { return m_resource; }
- /// Given the usage, flags, and format will return the most suitable format. Will return DXGI_UNKNOWN if combination is not possible
- static DXGI_FORMAT calcFormat(D3DUtil::UsageType usage, ID3D12Resource* resource);
+ /// Given the usage, flags, and format will return the most suitable format. Will return
+ /// DXGI_UNKNOWN if combination is not possible
+ static DXGI_FORMAT calcFormat(D3DUtil::UsageType usage, ID3D12Resource* resource);
- /// Ctor
- SLANG_FORCE_INLINE D3D12ResourceBase() :
- m_resource(nullptr)
- {}
+ /// Ctor
+ SLANG_FORCE_INLINE D3D12ResourceBase()
+ : m_resource(nullptr)
+ {
+ }
protected:
- /// This is protected so as clients cannot slice the class, and so state tracking is lost
- ~D3D12ResourceBase() {}
+ /// This is protected so as clients cannot slice the class, and so state tracking is lost
+ ~D3D12ResourceBase() {}
- ID3D12Resource* m_resource; ///< The resource (ref counted)
+ ID3D12Resource* m_resource; ///< The resource (ref counted)
};
struct D3D12Resource : public D3D12ResourceBase
{
- /// Dtor
- ~D3D12Resource()
- {
- if (m_resource)
- {
- m_resource->Release();
- }
- }
-
- /// Initialize as committed resource
- Slang::Result initCommitted(ID3D12Device* device, const D3D12_HEAP_PROPERTIES& heapProps, D3D12_HEAP_FLAGS heapFlags, const D3D12_RESOURCE_DESC& resourceDesc, D3D12_RESOURCE_STATES initState, const D3D12_CLEAR_VALUE * clearValue);
-
- /// Set a resource.
- void setResource(ID3D12Resource* resource);
- /// Make the resource null
- void setResourceNull();
- /// Returns the attached resource (with any ref counts) and sets to nullptr on this.
- ID3D12Resource* detach();
-
- /// Swaps the resource contents with the contents of the smart pointer
- void swap(Slang::ComPtr<ID3D12Resource>& resourceInOut);
-
- /// Set the debug name on a resource
- static void setDebugName(ID3D12Resource* resource, const char* name);
-
- /// Set the the debug name on the resource
- void setDebugName(const wchar_t* name);
- /// Set the debug name
- void setDebugName(const char* name);
+ /// Dtor
+ ~D3D12Resource()
+ {
+ if (m_resource)
+ {
+ m_resource->Release();
+ }
+ }
+
+ /// Initialize as committed resource
+ Slang::Result initCommitted(
+ ID3D12Device* device,
+ const D3D12_HEAP_PROPERTIES& heapProps,
+ D3D12_HEAP_FLAGS heapFlags,
+ const D3D12_RESOURCE_DESC& resourceDesc,
+ D3D12_RESOURCE_STATES initState,
+ const D3D12_CLEAR_VALUE* clearValue);
+
+ /// Set a resource.
+ void setResource(ID3D12Resource* resource);
+ /// Make the resource null
+ void setResourceNull();
+ /// Returns the attached resource (with any ref counts) and sets to nullptr on this.
+ ID3D12Resource* detach();
+
+ /// Swaps the resource contents with the contents of the smart pointer
+ void swap(Slang::ComPtr<ID3D12Resource>& resourceInOut);
+
+ /// Set the debug name on a resource
+ static void setDebugName(ID3D12Resource* resource, const char* name);
+
+ /// Set the the debug name on the resource
+ void setDebugName(const wchar_t* name);
+ /// Set the debug name
+ void setDebugName(const char* name);
};
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/d3d12/d3d12-sal-defs.h b/tools/gfx/d3d12/d3d12-sal-defs.h
index 058fbb14c..26df704d9 100644
--- a/tools/gfx/d3d12/d3d12-sal-defs.h
+++ b/tools/gfx/d3d12/d3d12-sal-defs.h
@@ -6,194 +6,194 @@
//
#if !defined(_In_)
-# define _In_
+#define _In_
#endif
#if !defined(_Out_)
-# define _Out_
+#define _Out_
#endif
#if !defined(_Inout_)
-# define _Inout_
+#define _Inout_
#endif
#if !defined(_In_z_)
-# define _In_z_
+#define _In_z_
#endif
#if !defined(_Inout_z_)
-# define _Inout_z_
+#define _Inout_z_
#endif
#if !defined(_In_reads_)
-# define _In_reads_(s)
+#define _In_reads_(s)
#endif
#if !defined(_In_reads_z_)
-# define _In_reads_z_(s)
+#define _In_reads_z_(s)
#endif
#if !defined(_In_reads_or_z_)
-# define _In_reads_or_z_(s)
+#define _In_reads_or_z_(s)
#endif
#if !defined(_Out_writes_)
-# define _Out_writes_(s)
+#define _Out_writes_(s)
#endif
#if !defined(_Out_writes_z_)
-# define _Out_writes_z_(s)
+#define _Out_writes_z_(s)
#endif
#if !defined(_Inout_updates_)
-# define _Inout_updates_(s)
+#define _Inout_updates_(s)
#endif
#if !defined(_Inout_updates_z_)
-# define _Inout_updates_z_(s)
+#define _Inout_updates_z_(s)
#endif
#if !defined(_Out_writes_to_)
-# define _Out_writes_to_(s,c)
+#define _Out_writes_to_(s, c)
#endif
#if !defined(_Inout_updates_to_)
-# define _Inout_updates_to_(s,c)
+#define _Inout_updates_to_(s, c)
#endif
#if !defined(_Inout_updates_all_)
-# define _Inout_updates_all_(s)
+#define _Inout_updates_all_(s)
#endif
#if !defined(_In_reads_to_ptr_)
-# define _In_reads_to_ptr_(p)
+#define _In_reads_to_ptr_(p)
#endif
#if !defined(_In_reads_to_ptr_z_)
-# define _In_reads_to_ptr_z_(p)
+#define _In_reads_to_ptr_z_(p)
#endif
#if !defined(_Out_writes_to_ptr_)
-# define _Out_writes_to_ptr_(p)
+#define _Out_writes_to_ptr_(p)
#endif
#if !defined(_Out_writes_to_ptr_z_)
-# define _Out_writes_to_ptr_z_(p)
+#define _Out_writes_to_ptr_z_(p)
#endif
#if !defined(_Outptr_)
-# define _Outptr_
+#define _Outptr_
#endif
#if !defined(_Outptr_opt_)
-# define _Outptr_opt_
+#define _Outptr_opt_
#endif
#if !defined(_Outptr_result_maybenull_)
-# define _Outptr_result_maybenull_
+#define _Outptr_result_maybenull_
#endif
#if !defined(_Outptr_opt_result_maybenull_)
-# define _Outptr_opt_result_maybenull_
+#define _Outptr_opt_result_maybenull_
#endif
#if !defined(_Outptr_result_z_)
-# define _Outptr_result_z_
+#define _Outptr_result_z_
#endif
#if !defined(_COM_Outptr_)
-# define _COM_Outptr_
+#define _COM_Outptr_
#endif
#if !defined(_Outptr_result_buffer_)
-# define _Outptr_result_buffer_(s)
+#define _Outptr_result_buffer_(s)
#endif
#if !defined(_Outptr_result_buffer_to_)
-# define _Outptr_result_buffer_to_(s, c)
+#define _Outptr_result_buffer_to_(s, c)
#endif
#if !defined(_Result_nullonfailure_)
-# define _Result_nullonfailure_
+#define _Result_nullonfailure_
#endif
#if !defined(_Result_zeroonfailure_)
-# define _Result_zeroonfailure_
+#define _Result_zeroonfailure_
#endif
#if !defined(_Outptr_result_nullonfailure_)
-# define _Outptr_result_nullonfailure_
+#define _Outptr_result_nullonfailure_
#endif
#if !defined(_Outptr_opt_result_nullonfailure_)
-# define _Outptr_opt_result_nullonfailure_
+#define _Outptr_opt_result_nullonfailure_
#endif
#if !defined(_Outref_result_nullonfailure_)
-# define _Outref_result_nullonfailure_
+#define _Outref_result_nullonfailure_
#endif
#if !defined(_Outref_)
-# define _Outref_
+#define _Outref_
#endif
#if !defined(_Outref_result_maybenull_)
-# define _Outref_result_maybenull_
+#define _Outref_result_maybenull_
#endif
#if !defined(_Outref_result_buffer_)
-# define _Outref_result_buffer_(s)
+#define _Outref_result_buffer_(s)
#endif
#if !defined(_Outref_result_bytebuffer_)
-# define _Outref_result_bytebuffer_(s)
+#define _Outref_result_bytebuffer_(s)
#endif
#if !defined(_Outref_result_buffer_to_)
-# define _Outref_result_buffer_to_(s, c)
+#define _Outref_result_buffer_to_(s, c)
#endif
#if !defined(_Outref_result_bytebuffer_to_)
-# define _Outref_result_bytebuffer_to_(s, c)
+#define _Outref_result_bytebuffer_to_(s, c)
#endif
#if !defined(_Outref_result_buffer_all_)
-# define _Outref_result_buffer_all_(s)
+#define _Outref_result_buffer_all_(s)
#endif
#if !defined(_Outref_result_bytebuffer_all_)
-# define _Outref_result_bytebuffer_all_(s)
+#define _Outref_result_bytebuffer_all_(s)
#endif
#if !defined(_Outref_result_buffer_maybenull_)
-# define _Outref_result_buffer_maybenull_(s)
+#define _Outref_result_buffer_maybenull_(s)
#endif
#if !defined(_Outref_result_bytebuffer_maybenull_)
-# define _Outref_result_bytebuffer_maybenull_(s)
+#define _Outref_result_bytebuffer_maybenull_(s)
#endif
#if !defined(_Outref_result_buffer_to_maybenull_)
-# define _Outref_result_buffer_to_maybenull_(s, c)
+#define _Outref_result_buffer_to_maybenull_(s, c)
#endif
#if !defined(_Outref_result_bytebuffer_to_maybenull_)
-# define _Outref_result_bytebuffer_to_maybenull_(s,c)
+#define _Outref_result_bytebuffer_to_maybenull_(s, c)
#endif
#if !defined(_Outref_result_buffer_all_maybenull_)
-# define _Outref_result_buffer_all_maybenull_(s)
+#define _Outref_result_buffer_all_maybenull_(s)
#endif
#if !defined(_Outref_result_bytebuffer_all_maybenull_)
-# define _Outref_result_bytebuffer_all_maybenull_(s)
+#define _Outref_result_bytebuffer_all_maybenull_(s)
#endif
#if !defined(_Printf_format_string_)
-# define _Printf_format_string_
+#define _Printf_format_string_
#endif
#if !defined(_Scanf_format_string_)
-# define _Scanf_format_string_
+#define _Scanf_format_string_
#endif
#if !defined(_Scanf_s_format_string_)
-# define _Scanf_s_format_string_
+#define _Scanf_s_format_string_
#endif
#if !defined(_In_range_)
-# define _In_range_(low, hi)
+#define _In_range_(low, hi)
#endif
#if !defined(_Pre_equal_to_)
-# define _Pre_equal_to_(expr)
+#define _Pre_equal_to_(expr)
#endif
#if !defined(_Struct_size_bytes_)
-# define _Struct_size_bytes_(size)
+#define _Struct_size_bytes_(size)
#endif
#if !defined(_Called_from_function_class_)
-# define _Called_from_function_class_(name)
+#define _Called_from_function_class_(name)
#endif
#if !defined(_Check_return_)
-# define _Check_return_
+#define _Check_return_
#endif
#if !defined(_Function_class_)
-# define _Function_class_(name)
+#define _Function_class_(name)
#endif
#if !defined(_Raises_SEH_exception_)
-# define _Raises_SEH_exception_
+#define _Raises_SEH_exception_
#endif
#if !defined(_Maybe_raises_SEH_exception_)
-# define _Maybe_raises_SEH_exception_
+#define _Maybe_raises_SEH_exception_
#endif
#if !defined(_Must_inspect_result_)
-# define _Must_inspect_result_
+#define _Must_inspect_result_
#endif
#if !defined(_Use_decl_annotations_)
-# define _Use_decl_annotations_
+#define _Use_decl_annotations_
#endif
#if !defined(_Always_)
-# define _Always_(anno_list)
+#define _Always_(anno_list)
#endif
#if !defined(_On_failure_)
-# define _On_failure_(anno_list)
+#define _On_failure_(anno_list)
#endif
#if !defined(_Return_type_success_)
-# define _Return_type_success_(expr)
+#define _Return_type_success_(expr)
#endif
#if !defined(_Success_)
-# define _Success_(expr)
+#define _Success_(expr)
#endif
#if !defined(__analysis_assume)
-# define __analysis_assume(expr)
+#define __analysis_assume(expr)
#endif
diff --git a/tools/gfx/d3d12/d3d12-sampler.cpp b/tools/gfx/d3d12/d3d12-sampler.cpp
index b96fb4c90..9f739a268 100644
--- a/tools/gfx/d3d12/d3d12-sampler.cpp
+++ b/tools/gfx/d3d12/d3d12-sampler.cpp
@@ -8,7 +8,10 @@ namespace d3d12
using namespace Slang;
-SamplerStateImpl::~SamplerStateImpl() { m_allocator->free(m_descriptor); }
+SamplerStateImpl::~SamplerStateImpl()
+{
+ m_allocator->free(m_descriptor);
+}
Result SamplerStateImpl::getNativeHandle(InteropHandle* outHandle)
{
diff --git a/tools/gfx/d3d12/d3d12-shader-object-layout.cpp b/tools/gfx/d3d12/d3d12-shader-object-layout.cpp
index c93ddf2cd..ad60fb12d 100644
--- a/tools/gfx/d3d12/d3d12-shader-object-layout.cpp
+++ b/tools/gfx/d3d12/d3d12-shader-object-layout.cpp
@@ -63,7 +63,7 @@ Result ShaderObjectLayoutImpl::init(Builder* builder)
{
auto renderer = builder->m_renderer;
- initBase(renderer, builder->m_session, builder->m_elementTypeLayout);
+ initBase(renderer, builder->m_session, builder->m_elementTypeLayout);
m_containerType = builder->m_containerType;
@@ -116,7 +116,7 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(
uint32_t count = (uint32_t)typeLayout->getBindingRangeBindingCount(r);
slang::TypeLayoutReflection* slangLeafTypeLayout =
typeLayout->getBindingRangeLeafTypeLayout(r);
-
+
BindingRangeInfo bindingRangeInfo = {};
bindingRangeInfo.bindingType = slangBindingType;
bindingRangeInfo.resourceShape = slangLeafTypeLayout->getResourceShape();
@@ -198,8 +198,7 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(
break;
case slang::BindingType::VaryingInput:
- case slang::BindingType::VaryingOutput:
- break;
+ case slang::BindingType::VaryingOutput: break;
default:
bindingRangeInfo.baseIndex = m_ownCounts.resource;
@@ -240,7 +239,11 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(
{
if (auto pendingTypeLayout = slangLeafTypeLayout->getPendingDataTypeLayout())
{
- createForElementType(m_renderer, m_session, pendingTypeLayout, subObjectLayout.writeRef());
+ createForElementType(
+ m_renderer,
+ m_session,
+ pendingTypeLayout,
+ subObjectLayout.writeRef());
}
}
else
@@ -294,53 +297,53 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(
switch (slangBindingType)
{
default:
- {
- // We only treat buffers of interface types as actual sub-object binding
- // range.
- auto bindingRangeTypeLayout =
- typeLayout->getBindingRangeLeafTypeLayout(bindingRangeIndex);
- if (!bindingRangeTypeLayout)
- continue;
- auto elementType = typeLayout->getBindingRangeLeafTypeLayout(bindingRangeIndex)
- ->getElementTypeLayout();
- if (!elementType)
- continue;
- if (elementType->getKind() != slang::TypeReflection::Kind::Interface)
{
- continue;
+ // We only treat buffers of interface types as actual sub-object binding
+ // range.
+ auto bindingRangeTypeLayout =
+ typeLayout->getBindingRangeLeafTypeLayout(bindingRangeIndex);
+ if (!bindingRangeTypeLayout)
+ continue;
+ auto elementType = typeLayout->getBindingRangeLeafTypeLayout(bindingRangeIndex)
+ ->getElementTypeLayout();
+ if (!elementType)
+ continue;
+ if (elementType->getKind() != slang::TypeReflection::Kind::Interface)
+ {
+ continue;
+ }
}
- }
- break;
+ break;
case slang::BindingType::ConstantBuffer:
- {
- SLANG_ASSERT(subObjectLayout);
+ {
+ SLANG_ASSERT(subObjectLayout);
- // The resource and sampler descriptors of a nested
- // constant buffer will "leak" into those of the
- // parent type, and we need to account for them
- // whenever we allocate storage.
- //
- objectCounts.resource = subObjectLayout->getTotalResourceDescriptorCount();
- objectCounts.sampler = subObjectLayout->getTotalSamplerDescriptorCount();
- objectCounts.rootParam = subObjectRange.layout->getChildRootParameterCount();
- }
- break;
+ // The resource and sampler descriptors of a nested
+ // constant buffer will "leak" into those of the
+ // parent type, and we need to account for them
+ // whenever we allocate storage.
+ //
+ objectCounts.resource = subObjectLayout->getTotalResourceDescriptorCount();
+ objectCounts.sampler = subObjectLayout->getTotalSamplerDescriptorCount();
+ objectCounts.rootParam = subObjectRange.layout->getChildRootParameterCount();
+ }
+ break;
case slang::BindingType::ParameterBlock:
- {
- SLANG_ASSERT(subObjectLayout);
+ {
+ SLANG_ASSERT(subObjectLayout);
- // In contrast to a constant buffer, a parameter block can hide
- // the resource and sampler descriptor allocation it uses (since they
- // are allocated into the tables that make up the parameter block.
- //
- // The only resource usage that leaks into the surrounding context
- // is the number of root parameters consumed.
- //
- objectCounts.rootParam = subObjectRange.layout->getTotalRootTableParameterCount();
- }
- break;
+ // In contrast to a constant buffer, a parameter block can hide
+ // the resource and sampler descriptor allocation it uses (since they
+ // are allocated into the tables that make up the parameter block.
+ //
+ // The only resource usage that leaks into the surrounding context
+ // is the number of root parameters consumed.
+ //
+ objectCounts.rootParam = subObjectRange.layout->getTotalRootTableParameterCount();
+ }
+ break;
case slang::BindingType::ExistentialValue:
// An unspecialized existential/interface value cannot consume any resources
@@ -446,7 +449,8 @@ void RootShaderObjectLayoutImpl::Builder::addGlobalParams(
}
void RootShaderObjectLayoutImpl::Builder::addEntryPoint(
- SlangStage stage, ShaderObjectLayoutImpl* entryPointLayout)
+ SlangStage stage,
+ ShaderObjectLayoutImpl* entryPointLayout)
{
EntryPointInfo info;
info.layout = entryPointLayout;
@@ -465,7 +469,8 @@ void RootShaderObjectLayoutImpl::Builder::addEntryPoint(
}
Result RootShaderObjectLayoutImpl::RootSignatureDescBuilder::translateDescriptorRangeType(
- slang::BindingType c, D3D12_DESCRIPTOR_RANGE_TYPE* outType)
+ slang::BindingType c,
+ D3D12_DESCRIPTOR_RANGE_TYPE* outType)
{
switch (c)
{
@@ -486,8 +491,7 @@ Result RootShaderObjectLayoutImpl::RootSignatureDescBuilder::translateDescriptor
case slang::BindingType::Sampler:
*outType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
return SLANG_OK;
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
}
}
@@ -592,11 +596,14 @@ Result RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addDescriptorRange(
bool isRootParameter)
{
auto bindingType = typeLayout->getDescriptorSetDescriptorRangeType(
- logicalDescriptorSetIndex, descriptorRangeIndex);
+ logicalDescriptorSetIndex,
+ descriptorRangeIndex);
auto count = typeLayout->getDescriptorSetDescriptorRangeDescriptorCount(
- logicalDescriptorSetIndex, descriptorRangeIndex);
+ logicalDescriptorSetIndex,
+ descriptorRangeIndex);
auto index = typeLayout->getDescriptorSetDescriptorRangeIndexOffset(
- logicalDescriptorSetIndex, descriptorRangeIndex);
+ logicalDescriptorSetIndex,
+ descriptorRangeIndex);
auto space = typeLayout->getDescriptorSetSpaceOffset(logicalDescriptorSetIndex);
D3D12_DESCRIPTOR_RANGE_TYPE rangeType;
@@ -662,7 +669,8 @@ void RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addBindingRange(
}
void RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addAsValue(
- slang::VariableLayoutReflection* varLayout, Index physicalDescriptorSetIndex)
+ slang::VariableLayoutReflection* varLayout,
+ Index physicalDescriptorSetIndex)
{
BindingRegisterOffsetPair offset(varLayout);
auto elementOffset = offset;
@@ -697,7 +705,8 @@ void RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addAsConstantBuffer(
if (typeLayout->getSize(SLANG_PARAMETER_CATEGORY_UNIFORM) != 0)
{
auto descriptorRangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
- auto& offsetForRangeType = offsetForOrdinaryChildren.primary.offsetForRangeType[descriptorRangeType];
+ auto& offsetForRangeType =
+ offsetForOrdinaryChildren.primary.offsetForRangeType[descriptorRangeType];
addDescriptorRange(
physicalDescriptorSetIndex,
descriptorRangeType,
@@ -708,7 +717,11 @@ void RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addAsConstantBuffer(
offsetForRangeType++;
}
- addAsValue(typeLayout, physicalDescriptorSetIndex, offsetForChildrenThatNeedNewSpace, offsetForOrdinaryChildren);
+ addAsValue(
+ typeLayout,
+ physicalDescriptorSetIndex,
+ offsetForChildrenThatNeedNewSpace,
+ offsetForOrdinaryChildren);
}
void RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addAsValue(
@@ -735,11 +748,9 @@ void RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addAsValue(
{
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ParameterBlock:
- case slang::BindingType::ExistentialValue:
- continue;
+ case slang::BindingType::ExistentialValue: continue;
- default:
- break;
+ default: break;
}
// For binding ranges that don't represent sub-objects, we will add
@@ -756,7 +767,7 @@ void RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addAsValue(
// Next we need to recursively include everything bound via sub-objects
Index subObjectRangeCount = typeLayout->getSubObjectRangeCount();
for (Index subObjectRangeIndex = 0; subObjectRangeIndex < subObjectRangeCount;
- subObjectRangeIndex++)
+ subObjectRangeIndex++)
{
auto bindingRangeIndex =
typeLayout->getSubObjectRangeBindingRangeIndex(subObjectRangeIndex);
@@ -776,86 +787,90 @@ void RootShaderObjectLayoutImpl::RootSignatureDescBuilder::addAsValue(
switch (bindingType)
{
case slang::BindingType::ConstantBuffer:
- {
- auto containerVarLayout = subObjectTypeLayout->getContainerVarLayout();
- SLANG_ASSERT(containerVarLayout);
+ {
+ auto containerVarLayout = subObjectTypeLayout->getContainerVarLayout();
+ SLANG_ASSERT(containerVarLayout);
- auto elementVarLayout = subObjectTypeLayout->getElementVarLayout();
- SLANG_ASSERT(elementVarLayout);
+ auto elementVarLayout = subObjectTypeLayout->getElementVarLayout();
+ SLANG_ASSERT(elementVarLayout);
- auto elementTypeLayout = elementVarLayout->getTypeLayout();
- SLANG_ASSERT(elementTypeLayout);
+ auto elementTypeLayout = elementVarLayout->getTypeLayout();
+ SLANG_ASSERT(elementTypeLayout);
- BindingRegisterOffsetPair containerOffset = subObjectRangeContainerOffset;
- containerOffset += BindingRegisterOffsetPair(containerVarLayout);
+ BindingRegisterOffsetPair containerOffset = subObjectRangeContainerOffset;
+ containerOffset += BindingRegisterOffsetPair(containerVarLayout);
- BindingRegisterOffsetPair elementOffset = subObjectRangeElementOffset;
- elementOffset += BindingRegisterOffsetPair(elementVarLayout);
+ BindingRegisterOffsetPair elementOffset = subObjectRangeElementOffset;
+ elementOffset += BindingRegisterOffsetPair(elementVarLayout);
- addAsConstantBuffer(
- elementTypeLayout, physicalDescriptorSetIndex, containerOffset, elementOffset);
- }
- break;
+ addAsConstantBuffer(
+ elementTypeLayout,
+ physicalDescriptorSetIndex,
+ containerOffset,
+ elementOffset);
+ }
+ break;
case slang::BindingType::ParameterBlock:
- {
- auto containerVarLayout = subObjectTypeLayout->getContainerVarLayout();
- SLANG_ASSERT(containerVarLayout);
-
- auto elementVarLayout = subObjectTypeLayout->getElementVarLayout();
- SLANG_ASSERT(elementVarLayout);
-
- auto elementTypeLayout = elementVarLayout->getTypeLayout();
- SLANG_ASSERT(elementTypeLayout);
-
- BindingRegisterOffsetPair subDescriptorSetOffset;
- subDescriptorSetOffset.primary.spaceOffset =
- subObjectRangeContainerOffset.primary.spaceOffset;
- subDescriptorSetOffset.pending.spaceOffset =
- subObjectRangeContainerOffset.pending.spaceOffset;
-
- auto subPhysicalDescriptorSetIndex = addDescriptorSet();
-
- // We recursively call `addAsConstantBuffer` to actually generate
- // the root signature bindings for children in the parameter block.
- // We must compute `containerOffset`, which include a space offset
- // that any sub ParameterBlocks should start from, and `elementOffset`
- // that encodes the space offset of the current parameter block.
- // The space offset of the current parameter block can be obtained from the
- // `containerVarLayout`, and the space offset of any sub ParameterBlocks
- // are obatined from `elementVarLayout`.
- BindingRegisterOffsetPair offsetForChildrenThatNeedNewSpace = subDescriptorSetOffset;
- offsetForChildrenThatNeedNewSpace += BindingRegisterOffsetPair(elementVarLayout);
- BindingRegisterOffsetPair offsetForOrindaryChildren = subDescriptorSetOffset;
- offsetForOrindaryChildren += BindingRegisterOffsetPair(containerVarLayout);
-
- addAsConstantBuffer(
- elementTypeLayout,
- subPhysicalDescriptorSetIndex,
- offsetForChildrenThatNeedNewSpace,
- offsetForOrindaryChildren);
- }
- break;
+ {
+ auto containerVarLayout = subObjectTypeLayout->getContainerVarLayout();
+ SLANG_ASSERT(containerVarLayout);
+
+ auto elementVarLayout = subObjectTypeLayout->getElementVarLayout();
+ SLANG_ASSERT(elementVarLayout);
+
+ auto elementTypeLayout = elementVarLayout->getTypeLayout();
+ SLANG_ASSERT(elementTypeLayout);
+
+ BindingRegisterOffsetPair subDescriptorSetOffset;
+ subDescriptorSetOffset.primary.spaceOffset =
+ subObjectRangeContainerOffset.primary.spaceOffset;
+ subDescriptorSetOffset.pending.spaceOffset =
+ subObjectRangeContainerOffset.pending.spaceOffset;
+
+ auto subPhysicalDescriptorSetIndex = addDescriptorSet();
+
+ // We recursively call `addAsConstantBuffer` to actually generate
+ // the root signature bindings for children in the parameter block.
+ // We must compute `containerOffset`, which include a space offset
+ // that any sub ParameterBlocks should start from, and `elementOffset`
+ // that encodes the space offset of the current parameter block.
+ // The space offset of the current parameter block can be obtained from the
+ // `containerVarLayout`, and the space offset of any sub ParameterBlocks
+ // are obatined from `elementVarLayout`.
+ BindingRegisterOffsetPair offsetForChildrenThatNeedNewSpace =
+ subDescriptorSetOffset;
+ offsetForChildrenThatNeedNewSpace += BindingRegisterOffsetPair(elementVarLayout);
+ BindingRegisterOffsetPair offsetForOrindaryChildren = subDescriptorSetOffset;
+ offsetForOrindaryChildren += BindingRegisterOffsetPair(containerVarLayout);
+
+ addAsConstantBuffer(
+ elementTypeLayout,
+ subPhysicalDescriptorSetIndex,
+ offsetForChildrenThatNeedNewSpace,
+ offsetForOrindaryChildren);
+ }
+ break;
case slang::BindingType::ExistentialValue:
- {
- // Any nested binding ranges in the sub-object will "leak" into the
- // binding ranges for the surrounding context.
- //
- auto specializedTypeLayout = subObjectTypeLayout->getPendingDataTypeLayout();
- if (specializedTypeLayout)
{
- BindingRegisterOffsetPair pendingOffset;
- pendingOffset.primary = subObjectRangeElementOffset.pending;
-
- addAsValue(
- specializedTypeLayout,
- physicalDescriptorSetIndex,
- pendingOffset,
- pendingOffset);
+ // Any nested binding ranges in the sub-object will "leak" into the
+ // binding ranges for the surrounding context.
+ //
+ auto specializedTypeLayout = subObjectTypeLayout->getPendingDataTypeLayout();
+ if (specializedTypeLayout)
+ {
+ BindingRegisterOffsetPair pendingOffset;
+ pendingOffset.primary = subObjectRangeElementOffset.pending;
+
+ addAsValue(
+ specializedTypeLayout,
+ physicalDescriptorSetIndex,
+ pendingOffset,
+ pendingOffset);
+ }
}
- }
- break;
+ break;
}
}
}
@@ -957,9 +972,9 @@ Result RootShaderObjectLayoutImpl::createRootSignatureFromSlang(
ComPtr<ID3DBlob> signature;
ComPtr<ID3DBlob> error;
if (SLANG_FAILED(device->m_D3D12SerializeVersionedRootSignature(
- &versionedDesc,
- signature.writeRef(),
- error.writeRef())))
+ &versionedDesc,
+ signature.writeRef(),
+ error.writeRef())))
{
getDebugCallback()->handleMessage(
DebugMessageType::Error,
@@ -1001,7 +1016,10 @@ Result RootShaderObjectLayoutImpl::create(
auto slangEntryPoint = programLayout->getEntryPointByIndex(e);
RefPtr<ShaderObjectLayoutImpl> entryPointLayout;
SLANG_RETURN_ON_FAIL(ShaderObjectLayoutImpl::createForElementType(
- device, program->getSession(), slangEntryPoint->getTypeLayout(), entryPointLayout.writeRef()));
+ device,
+ program->getSession(),
+ slangEntryPoint->getTypeLayout(),
+ entryPointLayout.writeRef()));
builder.addEntryPoint(slangEntryPoint->getStage(), entryPointLayout);
}
@@ -1017,7 +1035,11 @@ Result RootShaderObjectLayoutImpl::create(
// We build out this array along with root signature construction and store
// it in `m_gpuDescriptorSetInfos`.
SLANG_RETURN_ON_FAIL(createRootSignatureFromSlang(
- device, layout, program, layout->m_rootSignature.writeRef(), outError));
+ device,
+ layout,
+ program,
+ layout->m_rootSignature.writeRef(),
+ outError));
}
*outLayout = layout.detach();
diff --git a/tools/gfx/d3d12/d3d12-shader-object-layout.h b/tools/gfx/d3d12/d3d12-shader-object-layout.h
index 2b27a1d98..c6219d1a2 100644
--- a/tools/gfx/d3d12/d3d12-shader-object-layout.h
+++ b/tools/gfx/d3d12/d3d12-shader-object-layout.h
@@ -71,7 +71,8 @@ public:
bool isRootParameter;
- /// Is this binding range represent a specialization point, such as an existential value, or a `ParameterBlock<IFoo>`.
+ /// Is this binding range represent a specialization point, such as an existential value, or
+ /// a `ParameterBlock<IFoo>`.
bool isSpecializable;
};
@@ -129,7 +130,8 @@ public:
public:
Builder(RendererBase* renderer, slang::ISession* session)
: m_renderer(renderer), m_session(session)
- {}
+ {
+ }
RendererBase* m_renderer;
slang::ISession* m_session;
@@ -246,7 +248,8 @@ public:
: Super::Builder(renderer, program->getSession())
, m_program(program)
, m_programLayout(programLayout)
- {}
+ {
+ }
Result build(RootShaderObjectLayoutImpl** outLayout);
@@ -277,7 +280,8 @@ public:
RootSignatureDescBuilder(DeviceImpl* device)
: m_device(device)
- {}
+ {
+ }
// We will use one descriptor set for the global scope and one additional
// descriptor set for each `ParameterBlock` binding range in the shader object
@@ -289,7 +293,8 @@ public:
D3D12_ROOT_SIGNATURE_DESC1 m_rootSignatureDesc = {};
static Result translateDescriptorRangeType(
- slang::BindingType c, D3D12_DESCRIPTOR_RANGE_TYPE* outType);
+ slang::BindingType c,
+ D3D12_DESCRIPTOR_RANGE_TYPE* outType);
/// Stores offset information to apply to the reflected register/space for a descriptor
/// range.
@@ -309,7 +314,7 @@ public:
/// Note that the `D3D12_DESCRIPTOR_RANGE_TYPE` enumeration has
/// values between 0 and 3, inclusive.
///
- uint32_t offsetForRangeType[kRangeTypeCount] = { 0, 0, 0, 0 };
+ uint32_t offsetForRangeType[kRangeTypeCount] = {0, 0, 0, 0};
uint32_t& operator[](D3D12_DESCRIPTOR_RANGE_TYPE type)
{
@@ -327,8 +332,8 @@ public:
{
if (varLayout)
{
- spaceOffset =
- (UINT)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_SUB_ELEMENT_REGISTER_SPACE);
+ spaceOffset = (UINT)varLayout->getOffset(
+ SLANG_PARAMETER_CATEGORY_SUB_ELEMENT_REGISTER_SPACE);
offsetForRangeType[D3D12_DESCRIPTOR_RANGE_TYPE_CBV] =
(UINT)varLayout->getOffset(SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER);
offsetForRangeType[D3D12_DESCRIPTOR_RANGE_TYPE_SRV] =
@@ -358,9 +363,9 @@ public:
BindingRegisterOffsetPair() {}
BindingRegisterOffsetPair(slang::VariableLayoutReflection* varLayout)
- : primary(varLayout)
- , pending(varLayout->getPendingDataLayout())
- {}
+ : primary(varLayout), pending(varLayout->getPendingDataLayout())
+ {
+ }
void operator+=(BindingRegisterOffsetPair const& other)
{
@@ -433,7 +438,8 @@ public:
Index bindingRangeIndex);
void addAsValue(
- slang::VariableLayoutReflection* varLayout, Index physicalDescriptorSetIndex);
+ slang::VariableLayoutReflection* varLayout,
+ Index physicalDescriptorSetIndex);
/// Add binding ranges and parameter blocks to the root signature.
///
diff --git a/tools/gfx/d3d12/d3d12-shader-object.cpp b/tools/gfx/d3d12/d3d12-shader-object.cpp
index beb88b636..77d3553ba 100644
--- a/tools/gfx/d3d12/d3d12-shader-object.cpp
+++ b/tools/gfx/d3d12/d3d12-shader-object.cpp
@@ -4,13 +4,12 @@
#include "d3d12-buffer.h"
#include "d3d12-command-encoder.h"
#include "d3d12-device.h"
+#include "d3d12-helper-functions.h"
#include "d3d12-resource-views.h"
#include "d3d12-sampler.h"
#include "d3d12-shader-object-layout.h"
#include "d3d12-transient-heap.h"
-#include "d3d12-helper-functions.h"
-
namespace gfx
{
namespace d3d12
@@ -18,7 +17,10 @@ namespace d3d12
using namespace Slang;
-GfxCount ShaderObjectImpl::getEntryPointCount() { return 0; }
+GfxCount ShaderObjectImpl::getEntryPointCount()
+{
+ return 0;
+}
Result ShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
{
@@ -26,9 +28,15 @@ Result ShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryP
return SLANG_OK;
}
-const void* ShaderObjectImpl::getRawData() { return m_data.getBuffer(); }
+const void* ShaderObjectImpl::getRawData()
+{
+ return m_data.getBuffer();
+}
-Size ShaderObjectImpl::getSize() { return (Size)m_data.getCount(); }
+Size ShaderObjectImpl::getSize()
+{
+ return (Size)m_data.getCount();
+}
// TODO: Change Index to Offset/Size?
Result ShaderObjectImpl::setData(ShaderOffset const& inOffset, void const* data, size_t inSize)
@@ -97,7 +105,9 @@ Result ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* s
}
Result ShaderObjectImpl::setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler)
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler)
{
#if 0
if (offset.bindingRangeIndex < 0)
@@ -182,7 +192,7 @@ Result ShaderObjectImpl::init(
// freed while the object is still live.
//
// The doubling here is because any buffer resource could
- // have a counter buffer associated with it, which we
+ // have a counter buffer associated with it, which we
// also need to ensure isn't destroyed prematurely.
m_boundResources.setCount(resourceCount);
m_boundCounterResources.setCount(resourceCount);
@@ -354,7 +364,8 @@ bool ShaderObjectImpl::shouldAllocateConstantBuffer(TransientResourceHeapImpl* t
/// Ensure that the `m_ordinaryDataBuffer` has been created, if it is needed
Result ShaderObjectImpl::_ensureOrdinaryDataBufferCreatedIfNeeded(
- PipelineCommandEncoder* encoder, ShaderObjectLayoutImpl* specializedLayout)
+ PipelineCommandEncoder* encoder,
+ ShaderObjectLayoutImpl* specializedLayout)
{
// If data has been changed since last allocation/filling of constant buffer,
// we will need to allocate a new one.
@@ -385,7 +396,9 @@ Result ShaderObjectImpl::_ensureOrdinaryDataBufferCreatedIfNeeded(
//
auto alignedConstantBufferSize = D3DUtil::calcAligned(m_constantBufferSize, 256);
SLANG_RETURN_ON_FAIL(encoder->m_commandBuffer->m_transientHeap->allocateConstantBuffer(
- alignedConstantBufferSize, m_constantBufferWeakPtr, m_constantBufferOffset));
+ alignedConstantBufferSize,
+ m_constantBufferWeakPtr,
+ m_constantBufferOffset));
// Once the buffer is allocated, we can use `_writeOrdinaryData` to fill it in.
//
@@ -410,9 +423,9 @@ Result ShaderObjectImpl::_ensureOrdinaryDataBufferCreatedIfNeeded(
auto descriptorTable = m_descriptorSet.resourceTable;
D3D12_CONSTANT_BUFFER_VIEW_DESC viewDesc = {};
viewDesc.BufferLocation = static_cast<BufferResourceImpl*>(m_constantBufferWeakPtr)
- ->m_resource.getResource()
- ->GetGPUVirtualAddress() +
- m_constantBufferOffset;
+ ->m_resource.getResource()
+ ->GetGPUVirtualAddress() +
+ m_constantBufferOffset;
viewDesc.SizeInBytes = (UINT)alignedConstantBufferSize;
encoder->m_device->CreateConstantBufferView(&viewDesc, descriptorTable.getCpuHandle());
}
@@ -426,21 +439,22 @@ void ShaderObjectImpl::updateSubObjectsRecursive()
return;
auto& subObjectRanges = getLayout()->getSubObjectRanges();
for (Slang::Index subObjectRangeIndex = 0; subObjectRangeIndex < subObjectRanges.getCount();
- subObjectRangeIndex++)
+ subObjectRangeIndex++)
{
auto const& subObjectRange = subObjectRanges[subObjectRangeIndex];
auto const& bindingRange = getLayout()->getBindingRange(subObjectRange.bindingRangeIndex);
Slang::Index count = bindingRange.count;
for (Slang::Index subObjectIndexInRange = 0; subObjectIndexInRange < count;
- subObjectIndexInRange++)
+ subObjectIndexInRange++)
{
Slang::Index objectIndex = bindingRange.subObjectIndex + subObjectIndexInRange;
auto subObject = m_objects[objectIndex].Ptr();
if (!subObject)
continue;
subObject->updateSubObjectsRecursive();
- if (m_subObjectVersions.getCount() > objectIndex && m_subObjectVersions[objectIndex] != m_objects[objectIndex]->m_version)
+ if (m_subObjectVersions.getCount() > objectIndex &&
+ m_subObjectVersions[objectIndex] != m_objects[objectIndex]->m_version)
{
ShaderOffset offset;
offset.bindingRangeIndex = (GfxIndex)subObjectRange.bindingRangeIndex;
@@ -516,7 +530,8 @@ Result ShaderObjectImpl::prepareToBindAsParameterBlock(
// root parameter.
//
auto tableRootParamIndex = rootParamIndex++;
- context->pendingTableBindings->add(PendingDescriptorTableBinding{ tableRootParamIndex, table.getGpuHandle() });
+ context->pendingTableBindings->add(
+ PendingDescriptorTableBinding{tableRootParamIndex, table.getGpuHandle()});
}
if (auto descriptorCount = specializedLayout->getTotalSamplerDescriptorCount())
{
@@ -539,7 +554,8 @@ Result ShaderObjectImpl::prepareToBindAsParameterBlock(
// root parameter.
//
auto tableRootParamIndex = rootParamIndex++;
- context->pendingTableBindings->add(PendingDescriptorTableBinding{ tableRootParamIndex, table.getGpuHandle() });
+ context->pendingTableBindings->add(
+ PendingDescriptorTableBinding{tableRootParamIndex, table.getGpuHandle()});
}
return SLANG_OK;
@@ -553,16 +569,16 @@ bool ShaderObjectImpl::checkIfCachedDescriptorSetIsValidRecursive(BindingContext
return false;
if (m_cachedGPUDescriptorSet.resourceTable.getDescriptorCount() != 0 &&
m_cachedGPUDescriptorSet.resourceTable.m_heap.ptr.linearHeap->getHeap() !=
- m_cachedTransientHeap->getCurrentViewHeap().getHeap())
+ m_cachedTransientHeap->getCurrentViewHeap().getHeap())
return false;
if (m_cachedGPUDescriptorSet.samplerTable.getDescriptorCount() != 0 &&
m_cachedGPUDescriptorSet.samplerTable.m_heap.ptr.linearHeap->getHeap() !=
- m_cachedTransientHeap->getCurrentSamplerHeap().getHeap())
+ m_cachedTransientHeap->getCurrentSamplerHeap().getHeap())
return false;
auto& subObjectRanges = getLayout()->getSubObjectRanges();
for (Slang::Index subObjectRangeIndex = 0; subObjectRangeIndex < subObjectRanges.getCount();
- subObjectRangeIndex++)
+ subObjectRangeIndex++)
{
auto const& subObjectRange = subObjectRanges[subObjectRangeIndex];
auto const& bindingRange = getLayout()->getBindingRange(subObjectRange.bindingRangeIndex);
@@ -571,7 +587,7 @@ bool ShaderObjectImpl::checkIfCachedDescriptorSetIsValidRecursive(BindingContext
Slang::Index count = bindingRange.count;
for (Slang::Index subObjectIndexInRange = 0; subObjectIndexInRange < count;
- subObjectIndexInRange++)
+ subObjectIndexInRange++)
{
Slang::Index objectIndex = bindingRange.subObjectIndex + subObjectIndexInRange;
auto subObject = m_objects[objectIndex].Ptr();
@@ -587,7 +603,9 @@ bool ShaderObjectImpl::checkIfCachedDescriptorSetIsValidRecursive(BindingContext
/// Bind this object as a `ParameterBlock<X>`
Result ShaderObjectImpl::bindAsParameterBlock(
- BindingContext* context, BindingOffset const& offset, ShaderObjectLayoutImpl* specializedLayout)
+ BindingContext* context,
+ BindingOffset const& offset,
+ ShaderObjectLayoutImpl* specializedLayout)
{
if (checkIfCachedDescriptorSetIsValidRecursive(context))
{
@@ -598,13 +616,15 @@ Result ShaderObjectImpl::bindAsParameterBlock(
{
auto tableRootParamIndex = rootParamIndex++;
context->submitter->setRootDescriptorTable(
- tableRootParamIndex, m_cachedGPUDescriptorSet.resourceTable.getGpuHandle());
+ tableRootParamIndex,
+ m_cachedGPUDescriptorSet.resourceTable.getGpuHandle());
}
if (m_cachedGPUDescriptorSet.samplerTable.getDescriptorCount())
{
auto tableRootParamIndex = rootParamIndex++;
context->submitter->setRootDescriptorTable(
- tableRootParamIndex, m_cachedGPUDescriptorSet.samplerTable.getGpuHandle());
+ tableRootParamIndex,
+ m_cachedGPUDescriptorSet.samplerTable.getGpuHandle());
}
return SLANG_OK;
}
@@ -619,7 +639,10 @@ Result ShaderObjectImpl::bindAsParameterBlock(
context->pendingTableBindings = &pendingTableBindings;
SLANG_RETURN_ON_FAIL(prepareToBindAsParameterBlock(
- context, /* inout */ subOffset, specializedLayout, m_cachedGPUDescriptorSet));
+ context,
+ /* inout */ subOffset,
+ specializedLayout,
+ m_cachedGPUDescriptorSet));
// Next we bind the object into that descriptor set as if it were being used
// as a `ConstantBuffer<X>`.
@@ -766,30 +789,33 @@ Result ShaderObjectImpl::_bindImpl(
switch (bindingRange.bindingType)
{
case slang::BindingType::ConstantBuffer:
- {
- auto objOffset = rangeOffset;
- for (uint32_t j = 0; j < bindingRange.count; j++)
{
- auto& object = m_objects[subObjectIndex + j];
- SLANG_RETURN_ON_FAIL(object->bindAsConstantBuffer(
- context, descriptorSet, objOffset, subObjectLayout));
- objOffset += rangeStride;
+ auto objOffset = rangeOffset;
+ for (uint32_t j = 0; j < bindingRange.count; j++)
+ {
+ auto& object = m_objects[subObjectIndex + j];
+ SLANG_RETURN_ON_FAIL(object->bindAsConstantBuffer(
+ context,
+ descriptorSet,
+ objOffset,
+ subObjectLayout));
+ objOffset += rangeStride;
+ }
}
- }
- break;
+ break;
case slang::BindingType::ParameterBlock:
- {
- auto objOffset = rangeOffset;
- for (uint32_t j = 0; j < bindingRange.count; j++)
{
- auto& object = m_objects[subObjectIndex + j];
- SLANG_RETURN_ON_FAIL(
- object->bindAsParameterBlock(context, objOffset, subObjectLayout));
- objOffset += rangeStride;
+ auto objOffset = rangeOffset;
+ for (uint32_t j = 0; j < bindingRange.count; j++)
+ {
+ auto& object = m_objects[subObjectIndex + j];
+ SLANG_RETURN_ON_FAIL(
+ object->bindAsParameterBlock(context, objOffset, subObjectLayout));
+ objOffset += rangeStride;
+ }
}
- }
- break;
+ break;
case slang::BindingType::ExistentialValue:
if (subObjectLayout)
@@ -824,8 +850,7 @@ Result ShaderObjectImpl::bindRootArguments(BindingContext* context, uint32_t& in
case IResourceView::Type::UnorderedAccess:
context->submitter->setRootUAV(index, m_rootArguments[i]);
break;
- default:
- continue;
+ default: continue;
}
index++;
}
@@ -897,31 +922,31 @@ Result ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView*
switch (resourceView->getViewDesc()->type)
{
case IResourceView::Type::AccelerationStructure:
- {
- auto resourceViewImpl = static_cast<AccelerationStructureImpl*>(resourceView);
- rootArg = resourceViewImpl->getDeviceAddress();
- }
- break;
- case IResourceView::Type::ShaderResource:
- case IResourceView::Type::UnorderedAccess:
- {
- auto resourceViewImpl = static_cast<ResourceViewImpl*>(resourceView);
- if (resourceViewImpl->m_resource->isBuffer())
{
- rootArg = static_cast<BufferResourceImpl*>(resourceViewImpl->m_resource.Ptr())
- ->getDeviceAddress();
+ auto resourceViewImpl = static_cast<AccelerationStructureImpl*>(resourceView);
+ rootArg = resourceViewImpl->getDeviceAddress();
}
- else
+ break;
+ case IResourceView::Type::ShaderResource:
+ case IResourceView::Type::UnorderedAccess:
{
- getDebugCallback()->handleMessage(
- DebugMessageType::Error,
- DebugMessageSource::Layer,
- "The shader parameter at the specified offset is a root parameter, and "
- "therefore can only be a buffer view.");
- return SLANG_FAIL;
+ auto resourceViewImpl = static_cast<ResourceViewImpl*>(resourceView);
+ if (resourceViewImpl->m_resource->isBuffer())
+ {
+ rootArg = static_cast<BufferResourceImpl*>(resourceViewImpl->m_resource.Ptr())
+ ->getDeviceAddress();
+ }
+ else
+ {
+ getDebugCallback()->handleMessage(
+ DebugMessageType::Error,
+ DebugMessageSource::Layer,
+ "The shader parameter at the specified offset is a root parameter, and "
+ "therefore can only be a buffer view.");
+ return SLANG_FAIL;
+ }
}
- }
- break;
+ break;
}
return SLANG_OK;
}
@@ -945,23 +970,23 @@ Result ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView*
{
#if SLANG_GFX_HAS_DXR_SUPPORT
case IResourceView::Type::AccelerationStructure:
- {
- auto asImpl = static_cast<AccelerationStructureImpl*>(resourceView);
- // Hold a reference to the resource to prevent its destruction.
- m_boundResources[bindingRange.baseIndex + offset.bindingArrayIndex] = asImpl->m_buffer;
- internalResourceView = asImpl;
- }
- break;
+ {
+ auto asImpl = static_cast<AccelerationStructureImpl*>(resourceView);
+ // Hold a reference to the resource to prevent its destruction.
+ m_boundResources[bindingRange.baseIndex + offset.bindingArrayIndex] = asImpl->m_buffer;
+ internalResourceView = asImpl;
+ }
+ break;
#endif
default:
- {
- // Hold a reference to the resource to prevent its destruction.
- const auto resourceOffset = bindingRange.baseIndex + offset.bindingArrayIndex;
- m_boundResources[resourceOffset] = resourceViewImpl->m_resource;
- m_boundCounterResources[resourceOffset] = resourceViewImpl->m_counterResource;
- internalResourceView = resourceViewImpl;
- }
- break;
+ {
+ // Hold a reference to the resource to prevent its destruction.
+ const auto resourceOffset = bindingRange.baseIndex + offset.bindingArrayIndex;
+ m_boundResources[resourceOffset] = resourceViewImpl->m_resource;
+ m_boundCounterResources[resourceOffset] = resourceViewImpl->m_counterResource;
+ internalResourceView = resourceViewImpl;
+ }
+ break;
}
auto descriptorSlotIndex = bindingRange.baseIndex + (int32_t)offset.bindingArrayIndex;
@@ -999,7 +1024,9 @@ Result ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView*
}
Result ShaderObjectImpl::create(
- DeviceImpl* device, ShaderObjectLayoutImpl* layout, ShaderObjectImpl** outShaderObject)
+ DeviceImpl* device,
+ ShaderObjectLayoutImpl* layout,
+ ShaderObjectImpl** outShaderObject)
{
auto object = RefPtr<ShaderObjectImpl>(new ShaderObjectImpl());
SLANG_RETURN_ON_FAIL(
@@ -1008,14 +1035,20 @@ Result ShaderObjectImpl::create(
return SLANG_OK;
}
-ShaderObjectImpl::~ShaderObjectImpl() { m_descriptorSet.freeIfSupported(); }
+ShaderObjectImpl::~ShaderObjectImpl()
+{
+ m_descriptorSet.freeIfSupported();
+}
RootShaderObjectLayoutImpl* RootShaderObjectImpl::getLayout()
{
return static_cast<RootShaderObjectLayoutImpl*>(m_layout.Ptr());
}
-GfxCount RootShaderObjectImpl::getEntryPointCount() { return (GfxCount)m_entryPoints.getCount(); }
+GfxCount RootShaderObjectImpl::getEntryPointCount()
+{
+ return (GfxCount)m_entryPoints.getCount();
+}
SlangResult RootShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
{
@@ -1141,7 +1174,8 @@ Result RootShaderObjectImpl::copyFrom(IShaderObject* object, ITransientResourceH
}
Result RootShaderObjectImpl::bindAsRoot(
- BindingContext* context, RootShaderObjectLayoutImpl* specializedLayout)
+ BindingContext* context,
+ RootShaderObjectLayoutImpl* specializedLayout)
{
// Pull updates from sub-objects when this is a mutable root shader object.
updateSubObjectsRecursive();
@@ -1159,13 +1193,16 @@ Result RootShaderObjectImpl::bindAsRoot(
context->pendingTableBindings = &pendingTableBindings;
BindingOffset rootOffset;
-
+
// Bind all root parameters first.
Super::bindRootArguments(context, rootOffset.rootParam);
DescriptorSet descriptorSet;
SLANG_RETURN_ON_FAIL(prepareToBindAsParameterBlock(
- context, /* inout */ rootOffset, specializedLayout, descriptorSet));
+ context,
+ /* inout */ rootOffset,
+ specializedLayout,
+ descriptorSet));
SLANG_RETURN_ON_FAIL(
Super::bindAsConstantBuffer(context, descriptorSet, rootOffset, specializedLayout));
@@ -1182,7 +1219,10 @@ Result RootShaderObjectImpl::bindAsRoot(
entryPoint->updateSubObjectsRecursive();
SLANG_RETURN_ON_FAIL(entryPoint->bindAsConstantBuffer(
- context, descriptorSet, entryPointOffset, entryPointInfo.layout));
+ context,
+ descriptorSet,
+ entryPointOffset,
+ entryPointInfo.layout));
}
bindPendingTables(context);
@@ -1214,10 +1254,16 @@ Result RootShaderObjectImpl::resetImpl(
}
Result RootShaderObjectImpl::reset(
- DeviceImpl* device, RootShaderObjectLayoutImpl* layout, TransientResourceHeapImpl* heap)
+ DeviceImpl* device,
+ RootShaderObjectLayoutImpl* layout,
+ TransientResourceHeapImpl* heap)
{
return resetImpl(
- device, layout, &heap->m_stagingCpuViewHeap, &heap->m_stagingCpuSamplerHeap, false);
+ device,
+ layout,
+ &heap->m_stagingCpuViewHeap,
+ &heap->m_stagingCpuSamplerHeap,
+ false);
}
} // namespace d3d12
diff --git a/tools/gfx/d3d12/d3d12-shader-object.h b/tools/gfx/d3d12/d3d12-shader-object.h
index 6251a970c..f0276fa7f 100644
--- a/tools/gfx/d3d12/d3d12-shader-object.h
+++ b/tools/gfx/d3d12/d3d12-shader-object.h
@@ -88,7 +88,9 @@ class ShaderObjectImpl
public:
static Result create(
- DeviceImpl* device, ShaderObjectLayoutImpl* layout, ShaderObjectImpl** outShaderObject);
+ DeviceImpl* device,
+ ShaderObjectLayoutImpl* layout,
+ ShaderObjectImpl** outShaderObject);
~ShaderObjectImpl();
@@ -97,7 +99,7 @@ public:
virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override;
@@ -105,18 +107,20 @@ public:
// TODO: What to do with size_t?
virtual SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& inOffset, void const* data, size_t inSize) override;
+ setData(ShaderOffset const& inOffset, void const* data, size_t inSize) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setObject(ShaderOffset const& offset, IShaderObject* object) override;
+ setObject(ShaderOffset const& offset, IShaderObject* object) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* resourceView) override;
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
+ setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) override;
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) override;
protected:
Result init(
@@ -138,7 +142,8 @@ protected:
/// Ensure that the `m_ordinaryDataBuffer` has been created, if it is needed
Result _ensureOrdinaryDataBufferCreatedIfNeeded(
- PipelineCommandEncoder* encoder, ShaderObjectLayoutImpl* specializedLayout);
+ PipelineCommandEncoder* encoder,
+ ShaderObjectLayoutImpl* specializedLayout);
public:
void updateSubObjectsRecursive();
@@ -255,10 +260,10 @@ public:
virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- copyFrom(IShaderObject* object, ITransientResourceHeap* transientHeap) override;
+ copyFrom(IShaderObject* object, ITransientResourceHeap* transientHeap) override;
public:
Result bindAsRoot(BindingContext* context, RootShaderObjectLayoutImpl* specializedLayout);
@@ -274,7 +279,9 @@ public:
bool isMutable);
Result reset(
- DeviceImpl* device, RootShaderObjectLayoutImpl* layout, TransientResourceHeapImpl* heap);
+ DeviceImpl* device,
+ RootShaderObjectLayoutImpl* layout,
+ TransientResourceHeapImpl* heap);
protected:
virtual Result _createSpecializedLayout(ShaderObjectLayoutImpl** outLayout) override;
diff --git a/tools/gfx/d3d12/d3d12-shader-program.cpp b/tools/gfx/d3d12/d3d12-shader-program.cpp
index f2476232c..a39f20465 100644
--- a/tools/gfx/d3d12/d3d12-shader-program.cpp
+++ b/tools/gfx/d3d12/d3d12-shader-program.cpp
@@ -9,7 +9,8 @@ namespace d3d12
using namespace Slang;
Result ShaderProgramImpl::createShaderModule(
- slang::EntryPointReflection* entryPointInfo, ComPtr<ISlangBlob> kernelCode)
+ slang::EntryPointReflection* entryPointInfo,
+ ComPtr<ISlangBlob> kernelCode)
{
ShaderBinary shaderBin;
shaderBin.stage = entryPointInfo->getStage();
diff --git a/tools/gfx/d3d12/d3d12-shader-program.h b/tools/gfx/d3d12/d3d12-shader-program.h
index eafa898fe..669bce960 100644
--- a/tools/gfx/d3d12/d3d12-shader-program.h
+++ b/tools/gfx/d3d12/d3d12-shader-program.h
@@ -26,7 +26,8 @@ public:
List<ShaderBinary> m_shaders;
virtual Result createShaderModule(
- slang::EntryPointReflection* entryPointInfo, ComPtr<ISlangBlob> kernelCode) override;
+ slang::EntryPointReflection* entryPointInfo,
+ ComPtr<ISlangBlob> kernelCode) override;
};
} // namespace d3d12
diff --git a/tools/gfx/d3d12/d3d12-shader-table.cpp b/tools/gfx/d3d12/d3d12-shader-table.cpp
index f54b7c5e9..be537c737 100644
--- a/tools/gfx/d3d12/d3d12-shader-table.cpp
+++ b/tools/gfx/d3d12/d3d12-shader-table.cpp
@@ -24,9 +24,11 @@ RefPtr<BufferResource> ShaderTableImpl::createDeviceBuffer(
m_rayGenTableOffset = 0;
m_missTableOffset = raygenTableSize;
m_hitGroupTableOffset = (uint32_t)D3DUtil::calcAligned(
- m_missTableOffset + missTableSize, D3D12_RAYTRACING_SHADER_TABLE_BYTE_ALIGNMENT);
+ m_missTableOffset + missTableSize,
+ D3D12_RAYTRACING_SHADER_TABLE_BYTE_ALIGNMENT);
m_callableTableOffset = (uint32_t)D3DUtil::calcAligned(
- m_hitGroupTableOffset + hitgroupTableSize, D3D12_RAYTRACING_SHADER_TABLE_BYTE_ALIGNMENT);
+ m_hitGroupTableOffset + hitgroupTableSize,
+ D3D12_RAYTRACING_SHADER_TABLE_BYTE_ALIGNMENT);
uint32_t tableSize = m_callableTableOffset + callableTableSize;
auto pipelineImpl = static_cast<RayTracingPipelineStateImpl*>(pipeline);
@@ -47,8 +49,8 @@ RefPtr<BufferResource> ShaderTableImpl::createDeviceBuffer(
IBufferResource* stagingBuffer = nullptr;
Offset stagingBufferOffset = 0;
- transientHeapImpl->allocateStagingBuffer(
- tableSize, stagingBuffer, stagingBufferOffset, MemoryType::Upload);
+ transientHeapImpl
+ ->allocateStagingBuffer(tableSize, stagingBuffer, stagingBufferOffset, MemoryType::Upload);
assert(stagingBuffer);
void* stagingPtr = nullptr;
diff --git a/tools/gfx/d3d12/d3d12-submitter.cpp b/tools/gfx/d3d12/d3d12-submitter.cpp
index 0abd21d70..2870d8836 100644
--- a/tools/gfx/d3d12/d3d12-submitter.cpp
+++ b/tools/gfx/d3d12/d3d12-submitter.cpp
@@ -11,7 +11,8 @@ namespace d3d12
using namespace Slang;
void GraphicsSubmitter::setRootConstantBufferView(
- int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation)
+ int index,
+ D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation)
{
m_commandList->SetGraphicsRootConstantBufferView(index, gpuBufferLocation);
}
@@ -27,7 +28,8 @@ void GraphicsSubmitter::setRootSRV(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBuffe
}
void GraphicsSubmitter::setRootDescriptorTable(
- int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor)
+ int index,
+ D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor)
{
m_commandList->SetGraphicsRootDescriptorTable(index, baseDescriptor);
}
@@ -44,7 +46,10 @@ void GraphicsSubmitter::setRootConstants(
void const* srcData)
{
m_commandList->SetGraphicsRoot32BitConstants(
- UINT(rootParamIndex), UINT(countOf32BitValues), srcData, UINT(dstOffsetIn32BitValues));
+ UINT(rootParamIndex),
+ UINT(countOf32BitValues),
+ srcData,
+ UINT(dstOffsetIn32BitValues));
}
void GraphicsSubmitter::setPipelineState(PipelineStateBase* pipeline)
@@ -54,7 +59,8 @@ void GraphicsSubmitter::setPipelineState(PipelineStateBase* pipeline)
}
void ComputeSubmitter::setRootConstantBufferView(
- int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation)
+ int index,
+ D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation)
{
m_commandList->SetComputeRootConstantBufferView(index, gpuBufferLocation);
}
@@ -69,8 +75,7 @@ void ComputeSubmitter::setRootSRV(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBuffer
m_commandList->SetComputeRootShaderResourceView(index, gpuBufferLocation);
}
-void ComputeSubmitter::setRootDescriptorTable(
- int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor)
+void ComputeSubmitter::setRootDescriptorTable(int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor)
{
m_commandList->SetComputeRootDescriptorTable(index, baseDescriptor);
}
@@ -87,7 +92,10 @@ void ComputeSubmitter::setRootConstants(
void const* srcData)
{
m_commandList->SetComputeRoot32BitConstants(
- UINT(rootParamIndex), UINT(countOf32BitValues), srcData, UINT(dstOffsetIn32BitValues));
+ UINT(rootParamIndex),
+ UINT(countOf32BitValues),
+ srcData,
+ UINT(dstOffsetIn32BitValues));
}
void ComputeSubmitter::setPipelineState(PipelineStateBase* pipeline)
diff --git a/tools/gfx/d3d12/d3d12-submitter.h b/tools/gfx/d3d12/d3d12-submitter.h
index 77c3f8c0d..3c605ad17 100644
--- a/tools/gfx/d3d12/d3d12-submitter.h
+++ b/tools/gfx/d3d12/d3d12-submitter.h
@@ -13,7 +13,8 @@ using namespace Slang;
struct Submitter
{
virtual void setRootConstantBufferView(
- int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) = 0;
+ int index,
+ D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) = 0;
virtual void setRootUAV(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) = 0;
virtual void setRootSRV(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) = 0;
virtual void setRootDescriptorTable(int index, D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) = 0;
@@ -28,12 +29,12 @@ struct Submitter
struct GraphicsSubmitter : public Submitter
{
- virtual void setRootConstantBufferView(
- int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) override;
+ virtual void setRootConstantBufferView(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation)
+ override;
virtual void setRootUAV(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) override;
virtual void setRootSRV(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) override;
- virtual void setRootDescriptorTable(
- int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor) override;
+ virtual void setRootDescriptorTable(int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor)
+ override;
virtual void setRootSignature(ID3D12RootSignature* rootSignature) override;
virtual void setRootConstants(
Index rootParamIndex,
@@ -44,19 +45,20 @@ struct GraphicsSubmitter : public Submitter
GraphicsSubmitter(ID3D12GraphicsCommandList* commandList)
: m_commandList(commandList)
- {}
+ {
+ }
ID3D12GraphicsCommandList* m_commandList;
};
struct ComputeSubmitter : public Submitter
{
- virtual void setRootConstantBufferView(
- int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) override;
+ virtual void setRootConstantBufferView(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation)
+ override;
virtual void setRootUAV(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) override;
virtual void setRootSRV(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) override;
- virtual void setRootDescriptorTable(
- int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor) override;
+ virtual void setRootDescriptorTable(int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor)
+ override;
virtual void setRootSignature(ID3D12RootSignature* rootSignature) override;
virtual void setRootConstants(
Index rootParamIndex,
@@ -66,7 +68,8 @@ struct ComputeSubmitter : public Submitter
virtual void setPipelineState(PipelineStateBase* pipeline) override;
ComputeSubmitter(ID3D12GraphicsCommandList* commandList)
: m_commandList(commandList)
- {}
+ {
+ }
ID3D12GraphicsCommandList* m_commandList;
};
diff --git a/tools/gfx/d3d12/d3d12-swap-chain.cpp b/tools/gfx/d3d12/d3d12-swap-chain.cpp
index 8d4e723ea..098156c90 100644
--- a/tools/gfx/d3d12/d3d12-swap-chain.cpp
+++ b/tools/gfx/d3d12/d3d12-swap-chain.cpp
@@ -13,13 +13,18 @@ namespace d3d12
using namespace Slang;
Result SwapchainImpl::init(
- DeviceImpl* renderer, const ISwapchain::Desc& swapchainDesc, WindowHandle window)
+ DeviceImpl* renderer,
+ const ISwapchain::Desc& swapchainDesc,
+ WindowHandle window)
{
m_queue = static_cast<CommandQueueImpl*>(swapchainDesc.queue)->m_d3dQueue;
m_dxgiFactory = renderer->m_deviceInfo.m_dxgiFactory;
SLANG_RETURN_ON_FAIL(
D3DSwapchainBase::init(swapchainDesc, window, DXGI_SWAP_EFFECT_FLIP_DISCARD));
- SLANG_RETURN_ON_FAIL(renderer->m_device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(m_fence.writeRef())));
+ SLANG_RETURN_ON_FAIL(renderer->m_device->CreateFence(
+ 0,
+ D3D12_FENCE_FLAG_NONE,
+ IID_PPV_ARGS(m_fence.writeRef())));
SLANG_RETURN_ON_FAIL(m_swapChain->QueryInterface(m_swapChain3.writeRef()));
for (GfxIndex i = 0; i < swapchainDesc.imageCount; i++)
@@ -51,7 +56,9 @@ void SwapchainImpl::createSwapchainBufferImages()
m_swapChain->GetBuffer(i, IID_PPV_ARGS(d3dResource.writeRef()));
ITextureResource::Desc imageDesc = {};
imageDesc.allowedStates = ResourceStateSet(
- ResourceState::Present, ResourceState::RenderTarget, ResourceState::CopyDestination);
+ ResourceState::Present,
+ ResourceState::RenderTarget,
+ ResourceState::CopyDestination);
imageDesc.type = IResource::Type::Texture2D;
imageDesc.arraySize = 0;
imageDesc.format = m_desc.format;
@@ -80,7 +87,8 @@ int SwapchainImpl::acquireNextImage()
Result SwapchainImpl::present()
{
m_fence->SetEventOnCompletion(
- fenceValue, m_frameEvents[m_swapChain3->GetCurrentBackBufferIndex()]);
+ fenceValue,
+ m_frameEvents[m_swapChain3->GetCurrentBackBufferIndex()]);
SLANG_RETURN_ON_FAIL(D3DSwapchainBase::present());
fenceValue++;
m_queue->Signal(m_fence, fenceValue);
diff --git a/tools/gfx/d3d12/d3d12-texture.cpp b/tools/gfx/d3d12/d3d12-texture.cpp
index 9f47760e5..fdd9aab1b 100644
--- a/tools/gfx/d3d12/d3d12-texture.cpp
+++ b/tools/gfx/d3d12/d3d12-texture.cpp
@@ -9,9 +9,9 @@ namespace d3d12
using namespace Slang;
TextureResourceImpl::TextureResourceImpl(const Desc& desc)
- : Parent(desc)
- , m_defaultState(D3DUtil::getResourceState(desc.defaultState))
-{}
+ : Parent(desc), m_defaultState(D3DUtil::getResourceState(desc.defaultState))
+{
+}
TextureResourceImpl::~TextureResourceImpl()
{
@@ -45,7 +45,11 @@ Result TextureResourceImpl::getSharedHandle(InteropHandle* outHandle)
auto pResource = m_resource.getResource();
pResource->GetDevice(IID_PPV_ARGS(pDevice.writeRef()));
SLANG_RETURN_ON_FAIL(pDevice->CreateSharedHandle(
- pResource, NULL, GENERIC_ALL, nullptr, (HANDLE*)&outHandle->handleValue));
+ pResource,
+ NULL,
+ GENERIC_ALL,
+ nullptr,
+ (HANDLE*)&outHandle->handleValue));
outHandle->api = InteropHandleAPI::D3D12;
return SLANG_OK;
#endif
diff --git a/tools/gfx/d3d12/d3d12-texture.h b/tools/gfx/d3d12/d3d12-texture.h
index 3f6ed398b..e8bc4aa66 100644
--- a/tools/gfx/d3d12/d3d12-texture.h
+++ b/tools/gfx/d3d12/d3d12-texture.h
@@ -23,7 +23,7 @@ public:
D3D12_RESOURCE_STATES m_defaultState;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeResourceHandle(InteropHandle* outHandle) override;
+ getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
diff --git a/tools/gfx/d3d12/d3d12-transient-heap.cpp b/tools/gfx/d3d12/d3d12-transient-heap.cpp
index 60f40cc66..92b4de544 100644
--- a/tools/gfx/d3d12/d3d12-transient-heap.cpp
+++ b/tools/gfx/d3d12/d3d12-transient-heap.cpp
@@ -1,9 +1,9 @@
// d3d12-transient-heap.cpp
#include "d3d12-transient-heap.h"
-#include "d3d12-device.h"
#include "d3d12-buffer.h"
#include "d3d12-command-buffer.h"
+#include "d3d12-device.h"
namespace gfx
{
@@ -15,7 +15,10 @@ using namespace Slang;
Result TransientResourceHeapImpl::synchronize()
{
WaitForMultipleObjects(
- (DWORD)m_waitHandles.getCount(), m_waitHandles.getArrayView().getBuffer(), TRUE, INFINITE);
+ (DWORD)m_waitHandles.getCount(),
+ m_waitHandles.getArrayView().getBuffer(),
+ TRUE,
+ INFINITE);
m_waitHandles.clear();
return SLANG_OK;
}
@@ -139,7 +142,8 @@ Result TransientResourceHeapImpl::init(
auto d3dDevice = device->m_device;
SLANG_RETURN_ON_FAIL(d3dDevice->CreateCommandAllocator(
- D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(m_commandAllocator.writeRef())));
+ D3D12_COMMAND_LIST_TYPE_DIRECT,
+ IID_PPV_ARGS(m_commandAllocator.writeRef())));
allocateNewViewDescriptorHeap(device);
allocateNewSamplerDescriptorHeap(device);
diff --git a/tools/gfx/d3d12/d3d12-transient-heap.h b/tools/gfx/d3d12/d3d12-transient-heap.h
index 6b05367e8..1986d6326 100644
--- a/tools/gfx/d3d12/d3d12-transient-heap.h
+++ b/tools/gfx/d3d12/d3d12-transient-heap.h
@@ -11,8 +11,8 @@ namespace d3d12
using namespace Slang;
class TransientResourceHeapImpl
- : public TransientResourceHeapBaseImpl<DeviceImpl, BufferResourceImpl>
- , public ITransientResourceHeapD3D12
+ : public TransientResourceHeapBaseImpl<DeviceImpl, BufferResourceImpl>,
+ public ITransientResourceHeapD3D12
{
private:
typedef TransientResourceHeapBaseImpl<DeviceImpl, BufferResourceImpl> Super;
@@ -39,7 +39,7 @@ public:
//
// We will thus keep a single heap of each type that we hope will hold
// all the descriptors that actually get needed in a frame.
- ShortList<D3D12DescriptorHeap, 4> m_viewHeaps; // Cbv, Srv, Uav
+ ShortList<D3D12DescriptorHeap, 4> m_viewHeaps; // Cbv, Srv, Uav
ShortList<D3D12DescriptorHeap, 4> m_samplerHeaps; // Heap for samplers
int32_t m_currentViewHeapIndex = -1;
int32_t m_currentSamplerHeapIndex = -1;
@@ -55,7 +55,7 @@ public:
D3D12LinearExpandingDescriptorHeap m_stagingCpuSamplerHeap;
virtual SLANG_NO_THROW Result SLANG_MCALL
- queryInterface(SlangUUID const& uuid, void** outObject) override;
+ queryInterface(SlangUUID const& uuid, void** outObject) override;
virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() override { return Super::addRef(); }
virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() override { return Super::release(); }
@@ -81,7 +81,7 @@ public:
Result allocateNewSamplerDescriptorHeap(DeviceImpl* device);
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandBuffer(ICommandBuffer** outCommandBuffer) override;
+ createCommandBuffer(ICommandBuffer** outCommandBuffer) override;
Result synchronize();
diff --git a/tools/gfx/debug-layer/debug-base.h b/tools/gfx/debug-layer/debug-base.h
index aa269cc7b..c235102c4 100644
--- a/tools/gfx/debug-layer/debug-base.h
+++ b/tools/gfx/debug-layer/debug-base.h
@@ -1,11 +1,11 @@
// debug-base.h
#pragma once
-#include "slang-gfx.h"
-#include "slang-com-ptr.h"
-#include "core/slang-com-object.h"
#include "../command-encoder-com-forward.h"
#include "../renderer-shared.h"
+#include "core/slang-com-object.h"
+#include "slang-com-ptr.h"
+#include "slang-gfx.h"
namespace gfx
{
@@ -14,61 +14,57 @@ using namespace Slang;
namespace debug
{
- class DebugObjectBase : public Slang::ComObject
+class DebugObjectBase : public Slang::ComObject
+{
+public:
+ uint64_t uid;
+ DebugObjectBase()
{
- public:
- uint64_t uid;
- DebugObjectBase()
- {
- static uint64_t uidCounter = 0;
- uid = ++uidCounter;
- }
- };
+ static uint64_t uidCounter = 0;
+ uid = ++uidCounter;
+ }
+};
- template<typename TInterface>
- class DebugObject
- : public TInterface
- , public DebugObjectBase
- {
- public:
- Slang::ComPtr<TInterface> baseObject;
- };
+template<typename TInterface>
+class DebugObject : public TInterface, public DebugObjectBase
+{
+public:
+ Slang::ComPtr<TInterface> baseObject;
+};
- template <typename TInterface>
- class UnownedDebugObject
- : public TInterface
- , public DebugObjectBase
- {
- public:
- TInterface* baseObject = nullptr;
- };
+template<typename TInterface>
+class UnownedDebugObject : public TInterface, public DebugObjectBase
+{
+public:
+ TInterface* baseObject = nullptr;
+};
- class DebugDevice;
- class DebugShaderTable;
- class DebugQueryPool;
- class DebugBufferResource;
- class DebugTextureResource;
- class DebugResourceView;
- class DebugAccelerationStructure;
- class DebugSamplerState;
- class DebugShaderObject;
- class DebugRootShaderObject;
- class DebugCommandBuffer;
- class DebugResourceCommandEncoderImpl;
- class DebugComputeCommandEncoder;
- class DebugResourceCommandEncoder;
- class DebugRenderCommandEncoder;
- class DebugRayTracingCommandEncoder;
- class DebugFence;
- class DebugCommandQueue;
- class DebugFramebuffer;
- class DebugFramebufferLayout;
- class DebugInputLayout;
- class DebugPipelineState;
- class DebugRenderPassLayout;
- class DebugShaderProgram;
- class DebugTransientResourceHeap;
- class DebugSwapchain;
+class DebugDevice;
+class DebugShaderTable;
+class DebugQueryPool;
+class DebugBufferResource;
+class DebugTextureResource;
+class DebugResourceView;
+class DebugAccelerationStructure;
+class DebugSamplerState;
+class DebugShaderObject;
+class DebugRootShaderObject;
+class DebugCommandBuffer;
+class DebugResourceCommandEncoderImpl;
+class DebugComputeCommandEncoder;
+class DebugResourceCommandEncoder;
+class DebugRenderCommandEncoder;
+class DebugRayTracingCommandEncoder;
+class DebugFence;
+class DebugCommandQueue;
+class DebugFramebuffer;
+class DebugFramebufferLayout;
+class DebugInputLayout;
+class DebugPipelineState;
+class DebugRenderPassLayout;
+class DebugShaderProgram;
+class DebugTransientResourceHeap;
+class DebugSwapchain;
} // namespace debug
} // namespace gfx
diff --git a/tools/gfx/debug-layer/debug-buffer.h b/tools/gfx/debug-layer/debug-buffer.h
index 56c79c3d5..95720324c 100644
--- a/tools/gfx/debug-layer/debug-buffer.h
+++ b/tools/gfx/debug-layer/debug-buffer.h
@@ -19,14 +19,15 @@ public:
virtual SLANG_NO_THROW Type SLANG_MCALL getType() override;
virtual SLANG_NO_THROW Desc* SLANG_MCALL getDesc() override;
virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setDebugName(const char* name) override;
virtual SLANG_NO_THROW const char* SLANG_MCALL getDebugName() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- map(MemoryRange* rangeToRead, void** outPointer) override;
+ map(MemoryRange* rangeToRead, void** outPointer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL unmap(MemoryRange* writtenRange) override;
};
diff --git a/tools/gfx/debug-layer/debug-command-buffer.cpp b/tools/gfx/debug-layer/debug-command-buffer.cpp
index f3c71cb77..37e1c9e71 100644
--- a/tools/gfx/debug-layer/debug-command-buffer.cpp
+++ b/tools/gfx/debug-layer/debug-command-buffer.cpp
@@ -2,9 +2,8 @@
#include "debug-command-buffer.h"
#include "debug-framebuffer.h"
-#include "debug-render-pass.h"
-
#include "debug-helper-functions.h"
+#include "debug-render-pass.h"
namespace gfx
{
@@ -43,7 +42,9 @@ void DebugCommandBuffer::encodeRenderCommands(
auto innerFramebuffer = getInnerObj(framebuffer);
m_renderCommandEncoder.isOpen = true;
baseObject->encodeRenderCommands(
- innerRenderPass, innerFramebuffer, &m_renderCommandEncoder.baseObject);
+ innerRenderPass,
+ innerFramebuffer,
+ &m_renderCommandEncoder.baseObject);
if (m_renderCommandEncoder.baseObject)
*outEncoder = &m_renderCommandEncoder;
else
@@ -116,15 +117,15 @@ void DebugCommandBuffer::close()
}
if (m_computeCommandEncoder.isOpen)
{
- GFX_DIAGNOSE_ERROR(
- "A compute command encoder on this command buffer is still open. "
- "IComputeCommandEncoder::endEncoding() must be called before closing a command buffer.");
+ GFX_DIAGNOSE_ERROR("A compute command encoder on this command buffer is still open. "
+ "IComputeCommandEncoder::endEncoding() must be called before closing a "
+ "command buffer.");
}
if (m_resourceCommandEncoder.isOpen)
{
- GFX_DIAGNOSE_ERROR(
- "A resource command encoder on this command buffer is still open. "
- "IResourceCommandEncoder::endEncoding() must be called before closing a command buffer.");
+ GFX_DIAGNOSE_ERROR("A resource command encoder on this command buffer is still open. "
+ "IResourceCommandEncoder::endEncoding() must be called before closing a "
+ "command buffer.");
}
isOpen = false;
baseObject->close();
@@ -140,9 +141,12 @@ void DebugCommandBuffer::invalidateDescriptorHeapBinding()
{
SLANG_GFX_API_FUNC;
ComPtr<ICommandBufferD3D12> cmdBuf;
- if (SLANG_FAILED(baseObject->queryInterface(SlangUUID SLANG_UUID_ICommandBufferD3D12, (void**)cmdBuf.writeRef())))
+ if (SLANG_FAILED(baseObject->queryInterface(
+ SlangUUID SLANG_UUID_ICommandBufferD3D12,
+ (void**)cmdBuf.writeRef())))
{
- GFX_DIAGNOSE_ERROR("The current command buffer implementation does not provide ICommandBufferD3D12 interface.");
+ GFX_DIAGNOSE_ERROR("The current command buffer implementation does not provide "
+ "ICommandBufferD3D12 interface.");
return;
}
return cmdBuf->invalidateDescriptorHeapBinding();
@@ -152,9 +156,12 @@ void DebugCommandBuffer::ensureInternalDescriptorHeapsBound()
{
SLANG_GFX_API_FUNC;
ComPtr<ICommandBufferD3D12> cmdBuf;
- if (SLANG_FAILED(baseObject->queryInterface(SlangUUID SLANG_UUID_ICommandBufferD3D12, (void**)cmdBuf.writeRef())))
+ if (SLANG_FAILED(baseObject->queryInterface(
+ SlangUUID SLANG_UUID_ICommandBufferD3D12,
+ (void**)cmdBuf.writeRef())))
{
- GFX_DIAGNOSE_ERROR("The current command buffer implementation does not provide ICommandBufferD3D12 interface.");
+ GFX_DIAGNOSE_ERROR("The current command buffer implementation does not provide "
+ "ICommandBufferD3D12 interface.");
return;
}
return cmdBuf->ensureInternalDescriptorHeapsBound();
diff --git a/tools/gfx/debug-layer/debug-command-buffer.h b/tools/gfx/debug-layer/debug-command-buffer.h
index 33709fb2c..d2d6a1365 100644
--- a/tools/gfx/debug-layer/debug-command-buffer.h
+++ b/tools/gfx/debug-layer/debug-command-buffer.h
@@ -1,7 +1,6 @@
// debug-command-buffer.h
#pragma once
#include "debug-base.h"
-
#include "debug-command-encoder.h"
#include "debug-shader-object.h"
@@ -19,6 +18,7 @@ public:
public:
DebugTransientResourceHeap* m_transientHeap;
+
private:
DebugRenderCommandEncoder m_renderCommandEncoder;
DebugComputeCommandEncoder m_computeCommandEncoder;
@@ -33,11 +33,11 @@ public:
IFramebuffer* framebuffer,
IRenderCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
+ encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
+ encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
+ encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL close() override;
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW void SLANG_MCALL invalidateDescriptorHeapBinding() override;
@@ -46,6 +46,7 @@ public:
private:
void checkEncodersClosedBeforeNewEncoder();
void checkCommandBufferOpenWhenCreatingEncoder();
+
public:
DebugRootShaderObject rootObject;
bool isOpen = true;
diff --git a/tools/gfx/debug-layer/debug-command-encoder.cpp b/tools/gfx/debug-layer/debug-command-encoder.cpp
index 6838732a0..f09130d98 100644
--- a/tools/gfx/debug-layer/debug-command-encoder.cpp
+++ b/tools/gfx/debug-layer/debug-command-encoder.cpp
@@ -3,13 +3,12 @@
#include "debug-buffer.h"
#include "debug-command-buffer.h"
+#include "debug-helper-functions.h"
#include "debug-pipeline-state.h"
#include "debug-query.h"
#include "debug-resource-views.h"
#include "debug-texture.h"
-#include "debug-helper-functions.h"
-
namespace gfx
{
using namespace Slang;
@@ -40,7 +39,8 @@ Result DebugComputeCommandEncoder::bindPipeline(
}
Result DebugComputeCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* state, IShaderObject* rootObject)
+ IPipelineState* state,
+ IShaderObject* rootObject)
{
SLANG_GFX_API_FUNC;
return baseObject->bindPipelineWithRootObject(getInnerObj(state), getInnerObj(rootObject));
@@ -53,7 +53,8 @@ Result DebugComputeCommandEncoder::dispatchCompute(int x, int y, int z)
}
Result DebugComputeCommandEncoder::dispatchComputeIndirect(
- IBufferResource* cmdBuffer, Offset offset)
+ IBufferResource* cmdBuffer,
+ Offset offset)
{
SLANG_GFX_API_FUNC;
return baseObject->dispatchComputeIndirect(getInnerObj(cmdBuffer), offset);
@@ -82,7 +83,8 @@ Result DebugRenderCommandEncoder::bindPipeline(
}
Result DebugRenderCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* state, IShaderObject* rootObject)
+ IPipelineState* state,
+ IShaderObject* rootObject)
{
SLANG_GFX_API_FUNC;
return baseObject->bindPipelineWithRootObject(getInnerObj(state), getInnerObj(rootObject));
@@ -123,7 +125,9 @@ void DebugRenderCommandEncoder::setVertexBuffers(
}
void DebugRenderCommandEncoder::setIndexBuffer(
- IBufferResource* buffer, Format indexFormat, Offset offset)
+ IBufferResource* buffer,
+ Format indexFormat,
+ Offset offset)
{
SLANG_GFX_API_FUNC;
auto innerBuffer = static_cast<DebugBufferResource*>(buffer)->baseObject.get();
@@ -137,7 +141,9 @@ Result DebugRenderCommandEncoder::draw(GfxCount vertexCount, GfxIndex startVerte
}
Result DebugRenderCommandEncoder::drawIndexed(
- GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex)
+ GfxCount indexCount,
+ GfxIndex startIndex,
+ GfxIndex baseVertex)
{
SLANG_GFX_API_FUNC;
return baseObject->drawIndexed(indexCount, startIndex, baseVertex);
@@ -152,7 +158,11 @@ Result DebugRenderCommandEncoder::drawIndirect(
{
SLANG_GFX_API_FUNC;
return baseObject->drawIndirect(
- maxDrawCount, getInnerObj(argBuffer), argOffset, getInnerObj(countBuffer), countOffset);
+ maxDrawCount,
+ getInnerObj(argBuffer),
+ argOffset,
+ getInnerObj(countBuffer),
+ countOffset);
}
Result DebugRenderCommandEncoder::drawIndexedIndirect(
@@ -164,7 +174,11 @@ Result DebugRenderCommandEncoder::drawIndexedIndirect(
{
SLANG_GFX_API_FUNC;
return baseObject->drawIndexedIndirect(
- maxDrawCount, getInnerObj(argBuffer), argOffset, getInnerObj(countBuffer), countOffset);
+ maxDrawCount,
+ getInnerObj(argBuffer),
+ argOffset,
+ getInnerObj(countBuffer),
+ countOffset);
}
void DebugRenderCommandEncoder::setStencilReference(uint32_t referenceValue)
@@ -174,7 +188,9 @@ void DebugRenderCommandEncoder::setStencilReference(uint32_t referenceValue)
}
Result DebugRenderCommandEncoder::setSamplePositions(
- GfxCount samplesPerPixel, GfxCount pixelCount, const SamplePosition* samplePositions)
+ GfxCount samplesPerPixel,
+ GfxCount pixelCount,
+ const SamplePosition* samplePositions)
{
SLANG_GFX_API_FUNC;
return baseObject->setSamplePositions(samplesPerPixel, pixelCount, samplePositions);
@@ -187,8 +203,8 @@ Result DebugRenderCommandEncoder::drawInstanced(
GfxIndex startInstanceLocation)
{
SLANG_GFX_API_FUNC;
- return baseObject->drawInstanced(
- vertexCount, instanceCount, startVertex, startInstanceLocation);
+ return baseObject
+ ->drawInstanced(vertexCount, instanceCount, startVertex, startInstanceLocation);
}
Result DebugRenderCommandEncoder::drawIndexedInstanced(
@@ -200,7 +216,11 @@ Result DebugRenderCommandEncoder::drawIndexedInstanced(
{
SLANG_GFX_API_FUNC;
return baseObject->drawIndexedInstanced(
- indexCount, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation);
+ indexCount,
+ instanceCount,
+ startIndexLocation,
+ baseVertexLocation,
+ startInstanceLocation);
}
Result DebugRenderCommandEncoder::drawMeshTasks(int x, int y, int z)
@@ -232,8 +252,8 @@ void DebugResourceCommandEncoderImpl::copyBuffer(
SLANG_GFX_API_FUNC;
auto dstImpl = static_cast<DebugBufferResource*>(dst);
auto srcImpl = static_cast<DebugBufferResource*>(src);
- getBaseResourceEncoder()->copyBuffer(
- dstImpl->baseObject, dstOffset, srcImpl->baseObject, srcOffset, size);
+ getBaseResourceEncoder()
+ ->copyBuffer(dstImpl->baseObject, dstOffset, srcImpl->baseObject, srcOffset, size);
}
void DebugResourceCommandEncoderImpl::uploadBufferData(
@@ -272,7 +292,7 @@ void DebugResourceCommandEncoderImpl::bufferBarrier(
SLANG_GFX_API_FUNC;
List<IBufferResource*> innerBuffers;
- for(GfxIndex i = 0; i < count; i++)
+ for (GfxIndex i = 0; i < count; i++)
{
innerBuffers.add(static_cast<DebugBufferResource*>(buffers[i])->baseObject.get());
}
@@ -313,19 +333,25 @@ void DebugResourceCommandEncoderImpl::uploadTextureData(
{
SLANG_GFX_API_FUNC;
getBaseResourceEncoder()->uploadTextureData(
- getInnerObj(dst), subResourceRange, offset, extent, subResourceData, subResourceDataCount);
+ getInnerObj(dst),
+ subResourceRange,
+ offset,
+ extent,
+ subResourceData,
+ subResourceDataCount);
}
void DebugResourceCommandEncoderImpl::clearResourceView(
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags)
+ IResourceView* view,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags)
{
SLANG_GFX_API_FUNC;
switch (view->getViewDesc()->type)
{
case IResourceView::Type::DepthStencil:
case IResourceView::Type::RenderTarget:
- case IResourceView::Type::UnorderedAccess:
- break;
+ case IResourceView::Type::UnorderedAccess: break;
default:
GFX_DIAGNOSE_ERROR_FORMAT(
"Resource view %lld cannot be cleared. Only DepthStencil, "
@@ -345,14 +371,24 @@ void DebugResourceCommandEncoderImpl::resolveResource(
{
SLANG_GFX_API_FUNC;
getBaseResourceEncoder()->resolveResource(
- getInnerObj(source), sourceState, sourceRange, getInnerObj(dest), destState, destRange);
+ getInnerObj(source),
+ sourceState,
+ sourceRange,
+ getInnerObj(dest),
+ destState,
+ destRange);
}
void DebugResourceCommandEncoderImpl::resolveQuery(
- IQueryPool* queryPool, GfxIndex index, GfxCount count, IBufferResource* buffer, Offset offset)
+ IQueryPool* queryPool,
+ GfxIndex index,
+ GfxCount count,
+ IBufferResource* buffer,
+ Offset offset)
{
SLANG_GFX_API_FUNC;
- getBaseResourceEncoder()->resolveQuery(getInnerObj(queryPool), index, count, getInnerObj(buffer), offset);
+ getBaseResourceEncoder()
+ ->resolveQuery(getInnerObj(queryPool), index, count, getInnerObj(buffer), offset);
}
void DebugResourceCommandEncoderImpl::copyTextureToBuffer(
@@ -368,7 +404,15 @@ void DebugResourceCommandEncoderImpl::copyTextureToBuffer(
{
SLANG_GFX_API_FUNC;
getBaseResourceEncoder()->copyTextureToBuffer(
- getInnerObj(dst), dstOffset, dstSize, dstRowStride, getInnerObj(src), srcState, srcSubresource, srcOffset, extent);
+ getInnerObj(dst),
+ dstOffset,
+ dstSize,
+ dstRowStride,
+ getInnerObj(src),
+ srcState,
+ srcSubresource,
+ srcOffset,
+ extent);
}
void DebugResourceCommandEncoderImpl::textureSubresourceBarrier(
@@ -378,8 +422,8 @@ void DebugResourceCommandEncoderImpl::textureSubresourceBarrier(
ResourceState dst)
{
SLANG_GFX_API_FUNC;
- getBaseResourceEncoder()->textureSubresourceBarrier(
- getInnerObj(texture), subresourceRange, src, dst);
+ getBaseResourceEncoder()
+ ->textureSubresourceBarrier(getInnerObj(texture), subresourceRange, src, dst);
}
void DebugResourceCommandEncoderImpl::beginDebugEvent(const char* name, float rgbColor[3])
@@ -418,7 +462,9 @@ void DebugRayTracingCommandEncoder::buildAccelerationStructure(
}
validateAccelerationStructureBuildInputs(desc.inputs);
baseObject->buildAccelerationStructure(
- innerDesc, propertyQueryCount, innerQueryDescs.getBuffer());
+ innerDesc,
+ propertyQueryCount,
+ innerQueryDescs.getBuffer());
}
void DebugRayTracingCommandEncoder::copyAccelerationStructure(
@@ -451,7 +497,10 @@ void DebugRayTracingCommandEncoder::queryAccelerationStructureProperties(
innerQueryDesc.queryPool = getInnerObj(innerQueryDesc.queryPool);
}
baseObject->queryAccelerationStructureProperties(
- accelerationStructureCount, innerAS.getBuffer(), queryCount, innerQueryDescs.getBuffer());
+ accelerationStructureCount,
+ innerAS.getBuffer(),
+ queryCount,
+ innerQueryDescs.getBuffer());
}
void DebugRayTracingCommandEncoder::serializeAccelerationStructure(
@@ -471,7 +520,8 @@ void DebugRayTracingCommandEncoder::deserializeAccelerationStructure(
}
Result DebugRayTracingCommandEncoder::bindPipeline(
- IPipelineState* state, IShaderObject** outRootObject)
+ IPipelineState* state,
+ IShaderObject** outRootObject)
{
SLANG_GFX_API_FUNC;
auto innerPipeline = getInnerObj(state);
@@ -484,7 +534,8 @@ Result DebugRayTracingCommandEncoder::bindPipeline(
}
Result DebugRayTracingCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* state, IShaderObject* rootObject)
+ IPipelineState* state,
+ IShaderObject* rootObject)
{
SLANG_GFX_API_FUNC;
return baseObject->bindPipelineWithRootObject(getInnerObj(state), getInnerObj(rootObject));
@@ -498,7 +549,8 @@ Result DebugRayTracingCommandEncoder::dispatchRays(
GfxCount depth)
{
SLANG_GFX_API_FUNC;
- return baseObject->dispatchRays(rayGenShaderIndex, getInnerObj(shaderTable), width, height, depth);
+ return baseObject
+ ->dispatchRays(rayGenShaderIndex, getInnerObj(shaderTable), width, height, depth);
}
} // namespace debug
diff --git a/tools/gfx/debug-layer/debug-command-encoder.h b/tools/gfx/debug-layer/debug-command-encoder.h
index 152a1a733..467c52828 100644
--- a/tools/gfx/debug-layer/debug-command-encoder.h
+++ b/tools/gfx/debug-layer/debug-command-encoder.h
@@ -27,6 +27,7 @@ public:
}
uint32_t addRef() { return 1; }
uint32_t release() { return 1; }
+
public:
virtual SLANG_NO_THROW void SLANG_MCALL copyBuffer(
IBufferResource* dst,
@@ -35,9 +36,8 @@ public:
Offset srcOffset,
Size size);
virtual SLANG_NO_THROW void SLANG_MCALL
- uploadBufferData(IBufferResource* dst, Offset offset, Size size, void* data);
- virtual SLANG_NO_THROW void SLANG_MCALL
- writeTimestamp(IQueryPool* pool, GfxIndex index);
+ uploadBufferData(IBufferResource* dst, Offset offset, Size size, void* data);
+ virtual SLANG_NO_THROW void SLANG_MCALL writeTimestamp(IQueryPool* pool, GfxIndex index);
virtual SLANG_NO_THROW void SLANG_MCALL textureBarrier(
GfxCount count,
ITextureResource* const* textures,
@@ -66,7 +66,9 @@ public:
ITextureResource::SubresourceData* subResourceData,
GfxCount subResourceDataCount);
virtual SLANG_NO_THROW void SLANG_MCALL clearResourceView(
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags);
+ IResourceView* view,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags);
virtual SLANG_NO_THROW void SLANG_MCALL resolveResource(
ITextureResource* source,
ResourceState sourceState,
@@ -99,9 +101,8 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent();
};
-class DebugComputeCommandEncoder
- : public UnownedDebugObject<IComputeCommandEncoder>
- , public DebugResourceCommandEncoderImpl
+class DebugComputeCommandEncoder : public UnownedDebugObject<IComputeCommandEncoder>,
+ public DebugResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(DebugResourceCommandEncoderImpl)
@@ -110,7 +111,8 @@ public:
virtual IResourceCommandEncoder* getBaseResourceEncoder() override { return baseObject; }
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
@@ -120,21 +122,20 @@ public:
public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootShaderObject) override;
+ bindPipeline(IPipelineState* state, IShaderObject** outRootShaderObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL dispatchCompute(int x, int y, int z) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- dispatchComputeIndirect(IBufferResource* cmdBuffer, Offset offset) override;
+ dispatchComputeIndirect(IBufferResource* cmdBuffer, Offset offset) override;
public:
DebugCommandBuffer* commandBuffer;
bool isOpen = false;
};
-class DebugResourceCommandEncoder
- : public UnownedDebugObject<IResourceCommandEncoder>
- , public DebugResourceCommandEncoderImpl
+class DebugResourceCommandEncoder : public UnownedDebugObject<IResourceCommandEncoder>,
+ public DebugResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(DebugResourceCommandEncoderImpl)
@@ -158,49 +159,47 @@ public:
bool isOpen = false;
};
-class DebugRenderCommandEncoder
- : public UnownedDebugObject<IRenderCommandEncoder>
- , public DebugResourceCommandEncoderImpl
+class DebugRenderCommandEncoder : public UnownedDebugObject<IRenderCommandEncoder>,
+ public DebugResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(DebugResourceCommandEncoderImpl)
- virtual DebugCommandBuffer* getCommandBuffer() override
- {
- return commandBuffer;
- }
+ virtual DebugCommandBuffer* getCommandBuffer() override { return commandBuffer; }
virtual bool getIsOpen() override { return isOpen; }
virtual IResourceCommandEncoder* getBaseResourceEncoder() override { return baseObject; }
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
return nullptr;
}
+
public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootShaderObject) override;
+ bindPipeline(IPipelineState* state, IShaderObject** outRootShaderObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setViewports(GfxCount count, const Viewport* viewports) override;
+ setViewports(GfxCount count, const Viewport* viewports) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setScissorRects(GfxCount count, const ScissorRect* scissors) override;
+ setScissorRects(GfxCount count, const ScissorRect* scissors) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setPrimitiveTopology(PrimitiveTopology topology) override;
+ setPrimitiveTopology(PrimitiveTopology topology) override;
virtual SLANG_NO_THROW void SLANG_MCALL setVertexBuffers(
GfxIndex startSlot,
GfxCount slotCount,
IBufferResource* const* buffers,
const Offset* offsets) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) override;
+ setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- draw(GfxCount vertexCount, GfxIndex startVertex = 0) override;
+ draw(GfxCount vertexCount, GfxIndex startVertex = 0) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override;
+ drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override;
virtual SLANG_NO_THROW Result SLANG_MCALL drawIndirect(
GfxCount maxDrawCount,
IBufferResource* argBuffer,
@@ -231,17 +230,15 @@ public:
GfxIndex baseVertexLocation,
GfxIndex startInstanceLocation) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL
- drawMeshTasks(int x, int y, int z) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL drawMeshTasks(int x, int y, int z) override;
public:
DebugCommandBuffer* commandBuffer;
bool isOpen = false;
};
-class DebugRayTracingCommandEncoder
- : public UnownedDebugObject<IRayTracingCommandEncoder>
- , public DebugResourceCommandEncoderImpl
+class DebugRayTracingCommandEncoder : public UnownedDebugObject<IRayTracingCommandEncoder>,
+ public DebugResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(DebugResourceCommandEncoderImpl)
@@ -250,12 +247,14 @@ public:
virtual IResourceCommandEncoder* getBaseResourceEncoder() override { return baseObject; }
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IRayTracingCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IRayTracingCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
return nullptr;
}
+
public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW void SLANG_MCALL buildAccelerationStructure(
@@ -272,14 +271,13 @@ public:
GfxCount queryCount,
AccelerationStructureQueryDesc* queryDescs) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure* source) override;
- virtual SLANG_NO_THROW void SLANG_MCALL deserializeAccelerationStructure(
- IAccelerationStructure* dest,
- DeviceAddress source) override;
+ serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure* source) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ deserializeAccelerationStructure(IAccelerationStructure* dest, DeviceAddress source) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL dispatchRays(
GfxIndex rayGenShaderIndex,
IShaderTable* shaderTable,
diff --git a/tools/gfx/debug-layer/debug-command-queue.cpp b/tools/gfx/debug-layer/debug-command-queue.cpp
index d094f3438..3759b07b8 100644
--- a/tools/gfx/debug-layer/debug-command-queue.cpp
+++ b/tools/gfx/debug-layer/debug-command-queue.cpp
@@ -3,9 +3,8 @@
#include "debug-command-buffer.h"
#include "debug-fence.h"
-#include "debug-transient-heap.h"
-
#include "debug-helper-functions.h"
+#include "debug-transient-heap.h"
namespace gfx
{
@@ -20,7 +19,11 @@ const ICommandQueue::Desc& DebugCommandQueue::getDesc()
return baseObject->getDesc();
}
-void DebugCommandQueue::executeCommandBuffers(GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal)
+void DebugCommandQueue::executeCommandBuffers(
+ GfxCount count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal)
{
SLANG_GFX_API_FUNC;
List<ICommandBuffer*> innerCommandBuffers;
@@ -46,10 +49,15 @@ void DebugCommandQueue::executeCommandBuffers(GfxCount count, ICommandBuffer* co
}
}
}
- baseObject->executeCommandBuffers(count, innerCommandBuffers.getBuffer(), getInnerObj(fence), valueToSignal);
+ baseObject->executeCommandBuffers(
+ count,
+ innerCommandBuffers.getBuffer(),
+ getInnerObj(fence),
+ valueToSignal);
if (fence)
{
- getDebugObj(fence)->maxValueToSignal = Math::Max(getDebugObj(fence)->maxValueToSignal, valueToSignal);
+ getDebugObj(fence)->maxValueToSignal =
+ Math::Max(getDebugObj(fence)->maxValueToSignal, valueToSignal);
}
}
@@ -60,7 +68,9 @@ void DebugCommandQueue::waitOnHost()
}
Result DebugCommandQueue::waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* waitValues)
{
SLANG_GFX_API_FUNC;
List<IFence*> innerFences;
diff --git a/tools/gfx/debug-layer/debug-command-queue.h b/tools/gfx/debug-layer/debug-command-queue.h
index 3c9afa98b..417e9888a 100644
--- a/tools/gfx/debug-layer/debug-command-queue.h
+++ b/tools/gfx/debug-layer/debug-command-queue.h
@@ -17,11 +17,14 @@ public:
public:
ICommandQueue* getInterface(const Slang::Guid& guid);
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override;
- virtual SLANG_NO_THROW void SLANG_MCALL
- executeCommandBuffers(GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL executeCommandBuffers(
+ GfxCount count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal) override;
virtual SLANG_NO_THROW void SLANG_MCALL waitOnHost() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ waitForFenceValuesOnDevice(GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outHandle) override;
};
diff --git a/tools/gfx/debug-layer/debug-device.cpp b/tools/gfx/debug-layer/debug-device.cpp
index 44ca1de7a..c5798710a 100644
--- a/tools/gfx/debug-layer/debug-device.cpp
+++ b/tools/gfx/debug-layer/debug-device.cpp
@@ -45,7 +45,10 @@ Result DebugDevice::getNativeDeviceHandles(InteropHandles* outHandles)
return baseObject->getNativeDeviceHandles(outHandles);
}
-Result DebugDevice::getFeatures(const char** outFeatures, Size bufferSize, GfxCount* outFeatureCount)
+Result DebugDevice::getFeatures(
+ const char** outFeatures,
+ Size bufferSize,
+ GfxCount* outFeatureCount)
{
SLANG_GFX_API_FUNC;
@@ -116,7 +119,10 @@ Result DebugDevice::createTextureFromNativeHandle(
SLANG_GFX_API_FUNC;
RefPtr<DebugTextureResource> outObject = new DebugTextureResource();
- auto result = baseObject->createTextureFromNativeHandle(handle, srcDesc, outObject->baseObject.writeRef());
+ auto result = baseObject->createTextureFromNativeHandle(
+ handle,
+ srcDesc,
+ outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
returnComPtr(outResource, outObject);
@@ -132,7 +138,11 @@ Result DebugDevice::createTextureFromSharedHandle(
SLANG_GFX_API_FUNC;
RefPtr<DebugTextureResource> outObject = new DebugTextureResource();
- auto result = baseObject->createTextureFromSharedHandle(handle, srcDesc, size, outObject->baseObject.writeRef());
+ auto result = baseObject->createTextureFromSharedHandle(
+ handle,
+ srcDesc,
+ size,
+ outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
returnComPtr(outResource, outObject);
@@ -147,7 +157,8 @@ Result DebugDevice::createBufferResource(
SLANG_GFX_API_FUNC;
RefPtr<DebugBufferResource> outObject = new DebugBufferResource();
- auto result = baseObject->createBufferResource(desc, initData, outObject->baseObject.writeRef());
+ auto result =
+ baseObject->createBufferResource(desc, initData, outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
returnComPtr(outResource, outObject);
@@ -162,7 +173,8 @@ Result DebugDevice::createBufferFromNativeHandle(
SLANG_GFX_API_FUNC;
RefPtr<DebugBufferResource> outObject = new DebugBufferResource();
- auto result = baseObject->createBufferFromNativeHandle(handle, srcDesc, outObject->baseObject.writeRef());
+ auto result =
+ baseObject->createBufferFromNativeHandle(handle, srcDesc, outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
returnComPtr(outResource, outObject);
@@ -177,7 +189,8 @@ Result DebugDevice::createBufferFromSharedHandle(
SLANG_GFX_API_FUNC;
RefPtr<DebugBufferResource> outObject = new DebugBufferResource();
- auto result = baseObject->createBufferFromSharedHandle(handle, srcDesc, outObject->baseObject.writeRef());
+ auto result =
+ baseObject->createBufferFromSharedHandle(handle, srcDesc, outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
returnComPtr(outResource, outObject);
@@ -204,10 +217,8 @@ Result DebugDevice::createTextureView(
SLANG_GFX_API_FUNC;
RefPtr<DebugResourceView> outObject = new DebugResourceView();
- auto result = baseObject->createTextureView(
- getInnerObj(texture),
- desc,
- outObject->baseObject.writeRef());
+ auto result =
+ baseObject->createTextureView(getInnerObj(texture), desc, outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
returnComPtr(outView, outObject);
@@ -251,7 +262,8 @@ Result DebugDevice::createAccelerationStructure(
auto innerDesc = desc;
innerDesc.buffer = getInnerObj(innerDesc.buffer);
RefPtr<DebugAccelerationStructure> outObject = new DebugAccelerationStructure();
- auto result = baseObject->createAccelerationStructure(innerDesc, outObject->baseObject.writeRef());
+ auto result =
+ baseObject->createAccelerationStructure(innerDesc, outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
returnComPtr(outAS, outObject);
@@ -329,15 +341,12 @@ Result DebugDevice::createSwapchain(
return Result();
}
-Result DebugDevice::createInputLayout(
- IInputLayout::Desc const& desc,
- IInputLayout** outLayout)
+Result DebugDevice::createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout)
{
SLANG_GFX_API_FUNC;
RefPtr<DebugInputLayout> outObject = new DebugInputLayout();
- auto result = baseObject->createInputLayout(
- desc, outObject->baseObject.writeRef());
+ auto result = baseObject->createInputLayout(desc, outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
returnComPtr(outLayout, outObject);
@@ -386,8 +395,11 @@ Result DebugDevice::createShaderObject2(
RefPtr<DebugShaderObject> outObject = new DebugShaderObject();
auto typeName = type->getName();
- auto result =
- baseObject->createShaderObject2(session, type, containerType, outObject->baseObject.writeRef());
+ auto result = baseObject->createShaderObject2(
+ session,
+ type,
+ containerType,
+ outObject->baseObject.writeRef());
outObject->m_typeName = typeName;
outObject->m_device = this;
outObject->m_slangType = type;
@@ -406,8 +418,10 @@ Result DebugDevice::createMutableShaderObject(
RefPtr<DebugShaderObject> outObject = new DebugShaderObject();
auto typeName = type->getName();
- auto result =
- baseObject->createMutableShaderObject(type, containerType, outObject->baseObject.writeRef());
+ auto result = baseObject->createMutableShaderObject(
+ type,
+ containerType,
+ outObject->baseObject.writeRef());
outObject->m_typeName = typeName;
outObject->m_device = this;
outObject->m_slangType = type;
@@ -427,8 +441,11 @@ Result DebugDevice::createMutableShaderObject2(
RefPtr<DebugShaderObject> outObject = new DebugShaderObject();
auto typeName = type->getName();
- auto result =
- baseObject->createMutableShaderObject2(session, type, containerType, outObject->baseObject.writeRef());
+ auto result = baseObject->createMutableShaderObject2(
+ session,
+ type,
+ containerType,
+ outObject->baseObject.writeRef());
outObject->m_typeName = typeName;
outObject->m_device = this;
outObject->m_slangType = type;
@@ -439,12 +456,14 @@ Result DebugDevice::createMutableShaderObject2(
}
Result DebugDevice::createMutableRootShaderObject(
- IShaderProgram* program, IShaderObject** outRootObject)
+ IShaderProgram* program,
+ IShaderObject** outRootObject)
{
SLANG_GFX_API_FUNC;
RefPtr<DebugShaderObject> outObject = new DebugShaderObject();
auto result = baseObject->createMutableRootShaderObject(
- getInnerObj(program), outObject->baseObject.writeRef());
+ getInnerObj(program),
+ outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
outObject->m_device = this;
@@ -455,12 +474,14 @@ Result DebugDevice::createMutableRootShaderObject(
}
Result DebugDevice::createShaderObjectFromTypeLayout(
- slang::TypeLayoutReflection* typeLayout, IShaderObject** outShaderObject)
+ slang::TypeLayoutReflection* typeLayout,
+ IShaderObject** outShaderObject)
{
SLANG_GFX_API_FUNC;
RefPtr<DebugShaderObject> outObject = new DebugShaderObject();
- auto result = baseObject->createShaderObjectFromTypeLayout(typeLayout, outObject->baseObject.writeRef());
+ auto result =
+ baseObject->createShaderObjectFromTypeLayout(typeLayout, outObject->baseObject.writeRef());
auto type = typeLayout->getType();
auto typeName = type->getName();
outObject->m_typeName = typeName;
@@ -473,12 +494,14 @@ Result DebugDevice::createShaderObjectFromTypeLayout(
}
Result DebugDevice::createMutableShaderObjectFromTypeLayout(
- slang::TypeLayoutReflection* typeLayout, IShaderObject** outShaderObject)
+ slang::TypeLayoutReflection* typeLayout,
+ IShaderObject** outShaderObject)
{
SLANG_GFX_API_FUNC;
RefPtr<DebugShaderObject> outObject = new DebugShaderObject();
auto result = baseObject->createMutableShaderObjectFromTypeLayout(
- typeLayout, outObject->baseObject.writeRef());
+ typeLayout,
+ outObject->baseObject.writeRef());
if (SLANG_FAILED(result))
return result;
auto type = typeLayout->getType();
@@ -491,7 +514,9 @@ Result DebugDevice::createMutableShaderObjectFromTypeLayout(
}
Result DebugDevice::createProgram(
- const IShaderProgram::Desc& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnostics)
+ const IShaderProgram::Desc& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnostics)
{
SLANG_GFX_API_FUNC;
@@ -505,12 +530,15 @@ Result DebugDevice::createProgram(
}
Result DebugDevice::createProgram2(
- const IShaderProgram::CreateDesc2& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnostics)
+ const IShaderProgram::CreateDesc2& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnostics)
{
SLANG_GFX_API_FUNC;
IShaderProgram::Desc desc1 = {};
RefPtr<DebugShaderProgram> outObject = new DebugShaderProgram();
- auto result = baseObject->createProgram2(desc, outObject->baseObject.writeRef(), outDiagnostics);
+ auto result =
+ baseObject->createProgram2(desc, outObject->baseObject.writeRef(), outDiagnostics);
if (SLANG_FAILED(result))
return result;
auto base = static_cast<ShaderProgramBase*>(outObject->baseObject.get());
@@ -582,8 +610,8 @@ SlangResult DebugDevice::readTextureResource(
size_t* outPixelSize)
{
SLANG_GFX_API_FUNC;
- return baseObject->readTextureResource(
- getInnerObj(resource), state, outBlob, outRowPitch, outPixelSize);
+ return baseObject
+ ->readTextureResource(getInnerObj(resource), state, outBlob, outRowPitch, outPixelSize);
}
SlangResult DebugDevice::readBufferResource(
@@ -622,7 +650,11 @@ Result DebugDevice::createFence(const IFence::Desc& desc, IFence** outFence)
}
Result DebugDevice::waitForFences(
- GfxCount fenceCount, IFence** fences, uint64_t* values , bool waitForAll, uint64_t timeout)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* values,
+ bool waitForAll,
+ uint64_t timeout)
{
SLANG_GFX_API_FUNC;
ShortList<IFence*> innerFences;
@@ -630,11 +662,18 @@ Result DebugDevice::waitForFences(
{
innerFences.add(getInnerObj(fences[i]));
}
- return baseObject->waitForFences(fenceCount, innerFences.getArrayView().getBuffer(), values, waitForAll, timeout);
+ return baseObject->waitForFences(
+ fenceCount,
+ innerFences.getArrayView().getBuffer(),
+ values,
+ waitForAll,
+ timeout);
}
Result DebugDevice::getTextureAllocationInfo(
- const ITextureResource::Desc& desc, size_t* outSize, size_t* outAlignment)
+ const ITextureResource::Desc& desc,
+ size_t* outSize,
+ size_t* outAlignment)
{
SLANG_GFX_API_FUNC;
return baseObject->getTextureAllocationInfo(desc, outSize, outAlignment);
diff --git a/tools/gfx/debug-layer/debug-device.h b/tools/gfx/debug-layer/debug-device.h
index 90feaa37e..a4debd2e7 100644
--- a/tools/gfx/debug-layer/debug-device.h
+++ b/tools/gfx/debug-layer/debug-device.h
@@ -12,22 +12,24 @@ namespace debug
class DebugDevice : public DebugObject<IDevice>
{
public:
- SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) noexcept override;
+ SlangResult SLANG_MCALL
+ queryInterface(SlangUUID const& uuid, void** outObject) noexcept override;
SLANG_COM_OBJECT_IUNKNOWN_ADD_REF;
SLANG_COM_OBJECT_IUNKNOWN_RELEASE;
public:
DebugDevice();
IDevice* getInterface(const Slang::Guid& guid);
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeDeviceHandles(InteropHandles* outHandles) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeDeviceHandles(InteropHandles* outHandles) override;
virtual SLANG_NO_THROW bool SLANG_MCALL hasFeature(const char* feature) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getFeatures(const char** outFeatures, Size bufferSize, GfxCount* outFeatureCount) override;
+ getFeatures(const char** outFeatures, Size bufferSize, GfxCount* outFeatureCount) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
+ getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getSlangSession(slang::ISession** outSlangSession) override;
+ getSlangSession(slang::ISession** outSlangSession) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTransientResourceHeap(
const ITransientResourceHeap::Desc& desc,
ITransientResourceHeap** outHeap) override;
@@ -57,7 +59,7 @@ public:
const IBufferResource::Desc& srcDesc,
IBufferResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
+ createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
ITextureResource* texture,
IResourceView::Desc const& desc,
@@ -77,7 +79,7 @@ public:
IFramebufferLayout::Desc const& desc,
IFramebufferLayout** outFrameBuffer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffer** outFrameBuffer) override;
+ createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffer** outFrameBuffer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createRenderPassLayout(
const IRenderPassLayout::Desc& desc,
IRenderPassLayout** outRenderPassLayout) override;
@@ -85,11 +87,10 @@ public:
ISwapchain::Desc const& desc,
WindowHandle window,
ISwapchain** outSwapchain) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL createInputLayout(
- IInputLayout::Desc const& desc,
- IInputLayout** outLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
+ createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createShaderObject(
slang::TypeReflection* type,
ShaderObjectContainerType container,
@@ -109,15 +110,21 @@ public:
ShaderObjectContainerType container,
IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createShaderObjectFromTypeLayout(
- slang::TypeLayoutReflection* typeLayout, IShaderObject** outObject) override;
+ slang::TypeLayoutReflection* typeLayout,
+ IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createMutableShaderObjectFromTypeLayout(
- slang::TypeLayoutReflection* typeLayout, IShaderObject** outObject) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL
- createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL
- createProgram(const IShaderProgram::Desc& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnostics) override;
+ slang::TypeLayoutReflection* typeLayout,
+ IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createProgram2(const IShaderProgram::CreateDesc2& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnostics) override;
+ createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL createProgram(
+ const IShaderProgram::Desc& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnostics) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL createProgram2(
+ const IShaderProgram::CreateDesc2& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnostics) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
const GraphicsPipelineStateDesc& desc,
IPipelineState** outState) override;
@@ -139,11 +146,10 @@ public:
Size size,
ISlangBlob** outBlob) override;
virtual SLANG_NO_THROW const DeviceInfo& SLANG_MCALL getDeviceInfo() const override;
- virtual SLANG_NO_THROW Result SLANG_MCALL createQueryPool(
- const IQueryPool::Desc& desc,
- IQueryPool** outPool) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFence(const IFence::Desc& desc, IFence** outFence) override;
+ createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createFence(const IFence::Desc& desc, IFence** outFence) override;
virtual SLANG_NO_THROW Result SLANG_MCALL waitForFences(
GfxCount fenceCount,
IFence** fences,
@@ -151,10 +157,12 @@ public:
bool waitForAll,
uint64_t timeout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureAllocationInfo(
- const ITextureResource::Desc& desc, size_t* outSize, size_t* outAlignment) override;
+ const ITextureResource::Desc& desc,
+ size_t* outSize,
+ size_t* outAlignment) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureRowAlignment(size_t* outAlignment) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outTable) override;
+ createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outTable) override;
};
} // namespace debug
diff --git a/tools/gfx/debug-layer/debug-fence.cpp b/tools/gfx/debug-layer/debug-fence.cpp
index 66c541618..4e8673578 100644
--- a/tools/gfx/debug-layer/debug-fence.cpp
+++ b/tools/gfx/debug-layer/debug-fence.cpp
@@ -33,7 +33,10 @@ Result DebugFence::setCurrentValue(uint64_t value)
SLANG_GFX_API_FUNC;
if (value < maxValueToSignal)
{
- GFX_DIAGNOSE_ERROR_FORMAT("Cannot set fence value (%d) to lower than pending signal value (%d) on the fence.", value, maxValueToSignal);
+ GFX_DIAGNOSE_ERROR_FORMAT(
+ "Cannot set fence value (%d) to lower than pending signal value (%d) on the fence.",
+ value,
+ maxValueToSignal);
}
return baseObject->setCurrentValue(value);
}
diff --git a/tools/gfx/debug-layer/debug-fence.h b/tools/gfx/debug-layer/debug-fence.h
index 1f61fac33..de61e5838 100644
--- a/tools/gfx/debug-layer/debug-fence.h
+++ b/tools/gfx/debug-layer/debug-fence.h
@@ -17,7 +17,9 @@ public:
virtual SLANG_NO_THROW Result SLANG_MCALL getCurrentValue(uint64_t* outValue) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setCurrentValue(uint64_t value) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outNativeHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeHandle(InteropHandle* outNativeHandle) override;
+
public:
uint64_t maxValueToSignal = 0;
};
diff --git a/tools/gfx/debug-layer/debug-framebuffer.h b/tools/gfx/debug-layer/debug-framebuffer.h
index 76e05040c..a7ab637de 100644
--- a/tools/gfx/debug-layer/debug-framebuffer.h
+++ b/tools/gfx/debug-layer/debug-framebuffer.h
@@ -9,8 +9,7 @@ using namespace Slang;
namespace debug
{
-class DebugFramebuffer
- : public DebugObject<IFramebuffer>
+class DebugFramebuffer : public DebugObject<IFramebuffer>
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL;
diff --git a/tools/gfx/debug-layer/debug-helper-functions.cpp b/tools/gfx/debug-layer/debug-helper-functions.cpp
index e75d0a3c3..adeff9d2e 100644
--- a/tools/gfx/debug-layer/debug-helper-functions.cpp
+++ b/tools/gfx/debug-layer/debug-helper-functions.cpp
@@ -54,14 +54,14 @@ void validateAccelerationStructureBuildInputs(
if (!buildInputs.instanceDescs)
{
GFX_DIAGNOSE_WARNING("IAccelerationStructure::BuildInputs::instanceDescs is null "
- "when creating a top-level acceleration structure.");
+ "when creating a top-level acceleration structure.");
}
break;
case IAccelerationStructure::Kind::BottomLevel:
if (!buildInputs.geometryDescs)
{
GFX_DIAGNOSE_WARNING("IAccelerationStructure::BuildInputs::geometryDescs is null "
- "when creating a bottom-level acceleration structure.");
+ "when creating a bottom-level acceleration structure.");
}
for (int i = 0; i < buildInputs.descCount; i++)
{
@@ -75,12 +75,13 @@ void validateAccelerationStructureBuildInputs(
case Format::R16G16B16A16_FLOAT:
case Format::R16G16_FLOAT:
case Format::R16G16B16A16_SNORM:
- case Format::R16G16_SNORM:
- break;
+ case Format::R16G16_SNORM: break;
default:
GFX_DIAGNOSE_ERROR(
- "Unsupported IAccelerationStructure::TriangleDesc::vertexFormat. Valid "
- "values are R32G32B32_FLOAT, R32G32_FLOAT, R16G16B16A16_FLOAT, R16G16_FLOAT, "
+ "Unsupported "
+ "IAccelerationStructure::TriangleDesc::vertexFormat. Valid "
+ "values are R32G32B32_FLOAT, R32G32_FLOAT, R16G16B16A16_FLOAT, "
+ "R16G16_FLOAT, "
"R16G16B16A16_SNORM or R16G16_SNORM.");
}
if (buildInputs.geometryDescs[i].content.triangles.indexCount)
@@ -88,17 +89,18 @@ void validateAccelerationStructureBuildInputs(
switch (buildInputs.geometryDescs[i].content.triangles.indexFormat)
{
case Format::R32_UINT:
- case Format::R16_UINT:
- break;
+ case Format::R16_UINT: break;
default:
GFX_DIAGNOSE_ERROR(
- "Unsupported IAccelerationStructure::TriangleDesc::indexFormat. Valid "
+ "Unsupported "
+ "IAccelerationStructure::TriangleDesc::indexFormat. Valid "
"values are Unknown, R32_UINT or R16_UINT.");
}
if (!buildInputs.geometryDescs[i].content.triangles.indexData)
{
GFX_DIAGNOSE_ERROR(
- "IAccelerationStructure::TriangleDesc::indexData cannot be null if "
+ "IAccelerationStructure::TriangleDesc::indexData cannot be "
+ "null if "
"IAccelerationStructure::TriangleDesc::indexCount is not 0");
}
}
@@ -106,14 +108,16 @@ void validateAccelerationStructureBuildInputs(
{
if (buildInputs.geometryDescs[i].content.triangles.indexCount == 0)
{
- GFX_DIAGNOSE_ERROR(
- "IAccelerationStructure::TriangleDesc::indexCount cannot be 0 if "
- "IAccelerationStructure::TriangleDesc::indexFormat is not Format::Unknown");
+ GFX_DIAGNOSE_ERROR("IAccelerationStructure::TriangleDesc::"
+ "indexCount cannot be 0 if "
+ "IAccelerationStructure::TriangleDesc::"
+ "indexFormat is not Format::Unknown");
}
if (buildInputs.geometryDescs[i].content.triangles.indexData == 0)
{
GFX_DIAGNOSE_ERROR(
- "IAccelerationStructure::TriangleDesc::indexData cannot be null if "
+ "IAccelerationStructure::TriangleDesc::indexData cannot be "
+ "null if "
"IAccelerationStructure::TriangleDesc::indexFormat is not "
"Format::Unknown");
}
@@ -130,7 +134,8 @@ void validateAccelerationStructureBuildInputs(
if (buildInputs.geometryDescs[i].content.triangles.indexData != 0)
{
GFX_DIAGNOSE_ERROR(
- "IAccelerationStructure::TriangleDesc::indexData must be null if "
+ "IAccelerationStructure::TriangleDesc::indexData must be null "
+ "if "
"IAccelerationStructure::TriangleDesc::indexFormat is "
"Format::Unknown");
}
@@ -144,9 +149,7 @@ void validateAccelerationStructureBuildInputs(
}
}
break;
- default:
- GFX_DIAGNOSE_ERROR("Invalid value of IAccelerationStructure::Kind.");
- break;
+ default: GFX_DIAGNOSE_ERROR("Invalid value of IAccelerationStructure::Kind."); break;
}
}
diff --git a/tools/gfx/debug-layer/debug-helper-functions.h b/tools/gfx/debug-layer/debug-helper-functions.h
index f2edd0d84..8fad98f8a 100644
--- a/tools/gfx/debug-layer/debug-helper-functions.h
+++ b/tools/gfx/debug-layer/debug-helper-functions.h
@@ -1,7 +1,6 @@
// debug-helper-functions.h
#pragma once
#include "debug-base.h"
-
#include "debug-buffer.h"
#include "debug-command-buffer.h"
#include "debug-command-queue.h"
@@ -29,13 +28,13 @@ namespace debug
{
#ifdef __FUNCSIG__
-# define SLANG_FUNC_SIG __FUNCSIG__
+#define SLANG_FUNC_SIG __FUNCSIG__
#elif defined(__PRETTY_FUNCTION__)
-# define SLANG_FUNC_SIG __FUNCSIG__
+#define SLANG_FUNC_SIG __FUNCSIG__
#elif defined(__FUNCTION__)
-# define SLANG_FUNC_SIG __FUNCTION__
+#define SLANG_FUNC_SIG __FUNCTION__
#else
-# define SLANG_FUNC_SIG "UnknownFunction"
+#define SLANG_FUNC_SIG "UnknownFunction"
#endif
extern thread_local const char* _currentFunctionName;
@@ -50,12 +49,12 @@ struct SetCurrentFuncRAII
/// Returns the public API function name from a `SLANG_FUNC_SIG` string.
String _gfxGetFuncName(const char* input);
-template <typename... TArgs>
+template<typename... TArgs>
char* _gfxDiagnoseFormat(
- char* buffer, // Initial buffer to output formatted string.
- size_t shortBufferSize, // Size of the initial buffer.
+ char* buffer, // Initial buffer to output formatted string.
+ size_t shortBufferSize, // Size of the initial buffer.
List<char>& bufferArray, // A list for allocating a large buffer if needed.
- const char* format, // The format string.
+ const char* format, // The format string.
TArgs... args)
{
int length = sprintf_s(buffer, shortBufferSize, format, args...);
@@ -70,7 +69,7 @@ char* _gfxDiagnoseFormat(
return buffer;
}
-template <typename... TArgs>
+template<typename... TArgs>
void _gfxDiagnoseImpl(DebugMessageType type, const char* format, TArgs... args)
{
char shortBuffer[256];
@@ -103,7 +102,11 @@ void _gfxDiagnoseImpl(DebugMessageType type, const char* format, TArgs... args)
char shortBuffer[256]; \
List<char> bufferArray; \
auto message = _gfxDiagnoseFormat( \
- shortBuffer, sizeof(shortBuffer), bufferArray, format, __VA_ARGS__); \
+ shortBuffer, \
+ sizeof(shortBuffer), \
+ bufferArray, \
+ format, \
+ __VA_ARGS__); \
_gfxDiagnoseImpl( \
type, \
"%s: %s", \
@@ -117,16 +120,16 @@ void _gfxDiagnoseImpl(DebugMessageType type, const char* format, TArgs... args)
I##typeName* Debug##typeName::getInterface(const Slang::Guid& guid) \
{ \
return (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_I##typeName) \
- ? static_cast<I##typeName*>(this) \
- : nullptr; \
+ ? static_cast<I##typeName*>(this) \
+ : nullptr; \
}
#define SLANG_GFX_DEBUG_GET_INTERFACE_IMPL_PARENT(typeName, parentType) \
I##typeName* Debug##typeName::getInterface(const Slang::Guid& guid) \
{ \
return (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_I##typeName || \
guid == GfxGUID::IID_I##parentType) \
- ? static_cast<I##typeName*>(this) \
- : nullptr; \
+ ? static_cast<I##typeName*>(this) \
+ : nullptr; \
}
// Utility conversion functions to get Debug* object or the inner object from a user provided
diff --git a/tools/gfx/debug-layer/debug-query.h b/tools/gfx/debug-layer/debug-query.h
index 890745387..a1faa966b 100644
--- a/tools/gfx/debug-layer/debug-query.h
+++ b/tools/gfx/debug-layer/debug-query.h
@@ -15,10 +15,11 @@ public:
SLANG_COM_OBJECT_IUNKNOWN_ALL;
IQueryPool::Desc desc;
+
public:
IQueryPool* getInterface(const Slang::Guid& guid);
virtual SLANG_NO_THROW Result SLANG_MCALL
- getResult(GfxIndex index, GfxCount count, uint64_t* data) override;
+ getResult(GfxIndex index, GfxCount count, uint64_t* data) override;
virtual SLANG_NO_THROW Result SLANG_MCALL reset() override;
};
diff --git a/tools/gfx/debug-layer/debug-resource-views.h b/tools/gfx/debug-layer/debug-resource-views.h
index b9a9b4539..625860a08 100644
--- a/tools/gfx/debug-layer/debug-resource-views.h
+++ b/tools/gfx/debug-layer/debug-resource-views.h
@@ -17,7 +17,8 @@ public:
public:
IResourceView* getInterface(const Slang::Guid& guid);
virtual SLANG_NO_THROW Desc* SLANG_MCALL getViewDesc() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outNativeHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeHandle(InteropHandle* outNativeHandle) override;
};
class DebugAccelerationStructure : public DebugObject<IAccelerationStructure>
@@ -29,7 +30,7 @@ public:
IAccelerationStructure* getInterface(const Slang::Guid& guid);
virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeHandle(InteropHandle* outNativeHandle) override;
+ getNativeHandle(InteropHandle* outNativeHandle) override;
virtual SLANG_NO_THROW Desc* SLANG_MCALL getViewDesc() override;
};
diff --git a/tools/gfx/debug-layer/debug-sampler-state.h b/tools/gfx/debug-layer/debug-sampler-state.h
index d0b082ec5..0cabd8da7 100644
--- a/tools/gfx/debug-layer/debug-sampler-state.h
+++ b/tools/gfx/debug-layer/debug-sampler-state.h
@@ -17,7 +17,7 @@ public:
public:
ISamplerState* getInterface(const Slang::Guid& guid);
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeHandle(InteropHandle* outNativeHandle) override;
+ getNativeHandle(InteropHandle* outNativeHandle) override;
};
} // namespace debug
diff --git a/tools/gfx/debug-layer/debug-shader-object.cpp b/tools/gfx/debug-layer/debug-shader-object.cpp
index eb67c46ab..c262320f5 100644
--- a/tools/gfx/debug-layer/debug-shader-object.cpp
+++ b/tools/gfx/debug-layer/debug-shader-object.cpp
@@ -1,11 +1,10 @@
// debug-shader-object.cpp
#include "debug-shader-object.h"
+#include "debug-helper-functions.h"
#include "debug-resource-views.h"
#include "debug-sampler-state.h"
-#include "debug-helper-functions.h"
-
namespace gfx
{
using namespace Slang;
@@ -142,7 +141,9 @@ Result DebugShaderObject::setCombinedTextureSampler(
m_resources[ShaderOffsetKey{offset}] = viewImpl;
m_initializedBindingRanges.add(offset.bindingRangeIndex);
return baseObject->setCombinedTextureSampler(
- offset, getInnerObj(viewImpl), getInnerObj(sampler));
+ offset,
+ getInnerObj(viewImpl),
+ getInnerObj(sampler));
}
Result DebugShaderObject::setSpecializationArgs(
@@ -155,11 +156,13 @@ Result DebugShaderObject::setSpecializationArgs(
}
Result DebugShaderObject::getCurrentVersion(
- ITransientResourceHeap* transientHeap, IShaderObject** outObject)
+ ITransientResourceHeap* transientHeap,
+ IShaderObject** outObject)
{
SLANG_GFX_API_FUNC;
ComPtr<IShaderObject> innerObject;
- SLANG_RETURN_ON_FAIL(baseObject->getCurrentVersion(getInnerObj(transientHeap), innerObject.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ baseObject->getCurrentVersion(getInnerObj(transientHeap), innerObject.writeRef()));
RefPtr<DebugShaderObject> debugShaderObject = new DebugShaderObject();
debugShaderObject->baseObject = innerObject;
debugShaderObject->m_typeName = innerObject->getElementTypeLayout()->getName();
diff --git a/tools/gfx/debug-layer/debug-shader-object.h b/tools/gfx/debug-layer/debug-shader-object.h
index b5a268892..56fda0622 100644
--- a/tools/gfx/debug-layer/debug-shader-object.h
+++ b/tools/gfx/debug-layer/debug-shader-object.h
@@ -15,8 +15,8 @@ struct ShaderOffsetKey
bool operator==(ShaderOffsetKey other) const
{
return offset.bindingArrayIndex == other.offset.bindingArrayIndex &&
- offset.bindingRangeIndex == other.offset.bindingRangeIndex &&
- offset.uniformOffset == other.offset.uniformOffset;
+ offset.bindingRangeIndex == other.offset.bindingRangeIndex &&
+ offset.uniformOffset == other.offset.uniformOffset;
}
Slang::HashCode getHashCode() const
{
@@ -40,17 +40,17 @@ public:
virtual SLANG_NO_THROW ShaderObjectContainerType SLANG_MCALL getContainerType() override;
virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** entryPoint) override;
+ getEntryPoint(GfxIndex index, IShaderObject** entryPoint) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& offset, void const* data, size_t size) override;
+ setData(ShaderOffset const& offset, void const* data, size_t size) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getObject(ShaderOffset const& offset, IShaderObject** object) override;
+ getObject(ShaderOffset const& offset, IShaderObject** object) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setObject(ShaderOffset const& offset, IShaderObject* object) override;
+ setObject(ShaderOffset const& offset, IShaderObject* object) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* resourceView) override;
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
+ setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
ShaderOffset const& offset,
IResourceView* textureView,
@@ -60,12 +60,12 @@ public:
const slang::SpecializationArg* args,
GfxCount count) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getCurrentVersion(
- ITransientResourceHeap* transientHeap, IShaderObject** outObject) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getCurrentVersion(ITransientResourceHeap* transientHeap, IShaderObject** outObject) override;
virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override;
virtual SLANG_NO_THROW size_t SLANG_MCALL getSize() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setConstantBufferOverride(IBufferResource* constantBuffer) override;
+ setConstantBufferOverride(IBufferResource* constantBuffer) override;
public:
// Type name of an ordinary shader object.
diff --git a/tools/gfx/debug-layer/debug-shader-program.h b/tools/gfx/debug-layer/debug-shader-program.h
index 0f154f2a3..a98a40ded 100644
--- a/tools/gfx/debug-layer/debug-shader-program.h
+++ b/tools/gfx/debug-layer/debug-shader-program.h
@@ -16,7 +16,9 @@ public:
public:
IShaderProgram* getInterface(const Slang::Guid& guid);
- virtual SLANG_NO_THROW slang::TypeReflection* SLANG_MCALL findTypeByName(const char* name) override;
+ virtual SLANG_NO_THROW slang::TypeReflection* SLANG_MCALL
+ findTypeByName(const char* name) override;
+
public:
Slang::ComPtr<slang::IComponentType> m_slangProgram;
};
diff --git a/tools/gfx/debug-layer/debug-swap-chain.cpp b/tools/gfx/debug-layer/debug-swap-chain.cpp
index b1d3bc201..904d8d0c6 100644
--- a/tools/gfx/debug-layer/debug-swap-chain.cpp
+++ b/tools/gfx/debug-layer/debug-swap-chain.cpp
@@ -2,9 +2,8 @@
#include "debug-swap-chain.h"
#include "debug-command-queue.h"
-#include "debug-texture.h"
-
#include "debug-helper-functions.h"
+#include "debug-texture.h"
namespace gfx
{
diff --git a/tools/gfx/debug-layer/debug-swap-chain.h b/tools/gfx/debug-layer/debug-swap-chain.h
index 83a467d65..92accb4fd 100644
--- a/tools/gfx/debug-layer/debug-swap-chain.h
+++ b/tools/gfx/debug-layer/debug-swap-chain.h
@@ -18,7 +18,7 @@ public:
ISwapchain* getInterface(const Slang::Guid& guid);
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getImage(GfxIndex index, ITextureResource** outResource) override;
+ getImage(GfxIndex index, ITextureResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL present() override;
virtual SLANG_NO_THROW int SLANG_MCALL acquireNextImage() override;
virtual SLANG_NO_THROW Result SLANG_MCALL resize(GfxCount width, GfxCount height) override;
diff --git a/tools/gfx/debug-layer/debug-texture.cpp b/tools/gfx/debug-layer/debug-texture.cpp
index ad3dce4fe..87ca019b0 100644
--- a/tools/gfx/debug-layer/debug-texture.cpp
+++ b/tools/gfx/debug-layer/debug-texture.cpp
@@ -39,7 +39,10 @@ Result DebugTextureResource::setDebugName(const char* name)
return baseObject->setDebugName(name);
}
-const char* DebugTextureResource::getDebugName() { return baseObject->getDebugName(); }
+const char* DebugTextureResource::getDebugName()
+{
+ return baseObject->getDebugName();
+}
} // namespace debug
} // namespace gfx
diff --git a/tools/gfx/debug-layer/debug-texture.h b/tools/gfx/debug-layer/debug-texture.h
index 79e3aa3cf..a560f6a56 100644
--- a/tools/gfx/debug-layer/debug-texture.h
+++ b/tools/gfx/debug-layer/debug-texture.h
@@ -18,7 +18,8 @@ public:
ITextureResource* getInterface(const Slang::Guid& guid);
virtual SLANG_NO_THROW Type SLANG_MCALL getType() override;
virtual SLANG_NO_THROW Desc* SLANG_MCALL getDesc() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setDebugName(const char* name) override;
diff --git a/tools/gfx/debug-layer/debug-transient-heap.cpp b/tools/gfx/debug-layer/debug-transient-heap.cpp
index 84861297a..424a8feb1 100644
--- a/tools/gfx/debug-layer/debug-transient-heap.cpp
+++ b/tools/gfx/debug-layer/debug-transient-heap.cpp
@@ -2,7 +2,6 @@
#include "debug-transient-heap.h"
#include "debug-command-buffer.h"
-
#include "debug-helper-functions.h"
namespace gfx
@@ -79,7 +78,10 @@ Result DebugTransientResourceHeapD3D12::allocateTransientDescriptorTable(
SLANG_GFX_API_FUNC;
return baseObject->allocateTransientDescriptorTable(
- type, count, outDescriptorOffset, outD3DDescriptorHeapHandle);
+ type,
+ count,
+ outDescriptorOffset,
+ outD3DDescriptorHeapHandle);
}
} // namespace debug
diff --git a/tools/gfx/debug-layer/debug-transient-heap.h b/tools/gfx/debug-layer/debug-transient-heap.h
index 60430228d..4b4b4e227 100644
--- a/tools/gfx/debug-layer/debug-transient-heap.h
+++ b/tools/gfx/debug-layer/debug-transient-heap.h
@@ -16,12 +16,13 @@ public:
SLANG_COM_OBJECT_IUNKNOWN_RELEASE;
public:
- virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) override;
+ virtual SLANG_NO_THROW SlangResult SLANG_MCALL
+ queryInterface(SlangUUID const& uuid, void** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL synchronizeAndReset() override;
virtual SLANG_NO_THROW Result SLANG_MCALL finish() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandBuffer(ICommandBuffer** outCommandBuffer) override;
+ createCommandBuffer(ICommandBuffer** outCommandBuffer) override;
};
class DebugTransientResourceHeapD3D12 : public DebugObject<ITransientResourceHeapD3D12>
@@ -29,8 +30,10 @@ class DebugTransientResourceHeapD3D12 : public DebugObject<ITransientResourceHea
public:
SLANG_COM_OBJECT_IUNKNOWN_ADD_REF;
SLANG_COM_OBJECT_IUNKNOWN_RELEASE;
+
public:
- virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) override;
+ virtual SLANG_NO_THROW SlangResult SLANG_MCALL
+ queryInterface(SlangUUID const& uuid, void** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL allocateTransientDescriptorTable(
DescriptorType type,
GfxCount count,
diff --git a/tools/gfx/flag-combiner.cpp b/tools/gfx/flag-combiner.cpp
index f67f869ce..4a3332f98 100644
--- a/tools/gfx/flag-combiner.cpp
+++ b/tools/gfx/flag-combiner.cpp
@@ -1,6 +1,7 @@
#include "flag-combiner.h"
-namespace gfx {
+namespace gfx
+{
using namespace Slang;
void FlagCombiner::add(uint32_t flags, ChangeType type)
diff --git a/tools/gfx/flag-combiner.h b/tools/gfx/flag-combiner.h
index db8c6863b..2b14be277 100644
--- a/tools/gfx/flag-combiner.h
+++ b/tools/gfx/flag-combiner.h
@@ -3,7 +3,8 @@
#include "../../source/core/slang-list.h"
-namespace gfx {
+namespace gfx
+{
/* A default set of flags that can be used for checking devices */
typedef uint32_t DeviceCheckFlags;
@@ -11,19 +12,20 @@ struct DeviceCheckFlag
{
enum Enum : DeviceCheckFlags
{
- UseFullFeatureLevel = 0x1, //< If set will use full feature level (on dx this is D3D_FEATURE_LEVEL_11_1 else will try D3D_FEATURE_LEVEL_11_0)
- UseHardwareDevice = 0x2, //< If set will try a hardware device
- UseDebug = 0x4, //< If set will enable use of debug
+ UseFullFeatureLevel = 0x1, //< If set will use full feature level (on dx this is
+ // D3D_FEATURE_LEVEL_11_1 else will try D3D_FEATURE_LEVEL_11_0)
+ UseHardwareDevice = 0x2, //< If set will try a hardware device
+ UseDebug = 0x4, //< If set will enable use of debug
};
};
/* Controls how and the order flags are changed, on the FlagCombiner */
enum class ChangeType
{
- On, ///< Always on
- Off, ///< Always off
- OnOff, ///< Initially on then off
- OffOn, ///< Initially off then on
+ On, ///< Always on
+ Off, ///< Always off
+ OnOff, ///< Initially on then off
+ OffOn, ///< Initially off then on
};
/* Calculates all the combinations of flags as controlled by the change types.
@@ -36,32 +38,32 @@ for (first added) {
}
}
-So the last added flags will have the highest frequency.
+So the last added flags will have the highest frequency.
*/
class FlagCombiner
{
public:
- /// Add a flag and how it changes over the combinations
- /// NOTE! That the order flags are added controls the order they change when combinations are calculated - earlier added
- /// flags will change with the highest frequency
+ /// Add a flag and how it changes over the combinations
+ /// NOTE! That the order flags are added controls the order they change when combinations are
+ /// calculated - earlier added flags will change with the highest frequency
void add(uint32_t flags, ChangeType changeType);
- /// Calculate all of the combinations and place in an array
+ /// Calculate all of the combinations and place in an array
void calcCombinations(Slang::List<uint32_t>& outCombinations) const;
- /// Reset back to initial state
- void reset();
+ /// Reset back to initial state
+ void reset();
- /// Get the total amount of combinations
+ /// Get the total amount of combinations
int getNumCombinations() const { return 1 << m_numChangingBits; }
- /// Get the combination at i
+ /// Get the combination at i
uint32_t getCombination(int i) const;
protected:
uint32_t m_changingBits[32];
int m_numChangingBits = 0;
- uint32_t m_usedFlags = 0;
+ uint32_t m_usedFlags = 0;
uint32_t m_invertBits = 0;
};
diff --git a/tools/gfx/immediate-renderer-base.cpp b/tools/gfx/immediate-renderer-base.cpp
index 4043512c6..e993ce319 100644
--- a/tools/gfx/immediate-renderer-base.cpp
+++ b/tools/gfx/immediate-renderer-base.cpp
@@ -1,10 +1,11 @@
#include "immediate-renderer-base.h"
-#include "simple-render-pass-layout.h"
-#include "simple-transient-resource-heap.h"
+
+#include "command-encoder-com-forward.h"
#include "command-writer.h"
#include "core/slang-basic.h"
#include "core/slang-blob.h"
-#include "command-encoder-com-forward.h"
+#include "simple-render-pass-layout.h"
+#include "simple-transient-resource-heap.h"
namespace gfx
{
@@ -44,10 +45,7 @@ public:
m_transientHeap = transientHeap;
}
- void reset()
- {
- m_writer.clear();
- }
+ void reset() { m_writer.clear(); }
class ResourceCommandEncoderImpl : public IResourceCommandEncoder
{
@@ -62,14 +60,15 @@ public:
virtual void* getInterface(SlangUUID const& uuid)
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
return nullptr;
}
virtual SLANG_NO_THROW SlangResult SLANG_MCALL
- queryInterface(SlangUUID const& uuid, void** outObject) override
+ queryInterface(SlangUUID const& uuid, void** outObject) override
{
if (auto ptr = getInterface(uuid))
{
@@ -93,13 +92,13 @@ public:
}
virtual SLANG_NO_THROW void SLANG_MCALL
- uploadBufferData(IBufferResource* dst, size_t offset, size_t size, void* data) override
+ uploadBufferData(IBufferResource* dst, size_t offset, size_t size, void* data) override
{
m_writer->uploadBufferData(dst, offset, size, data);
}
virtual SLANG_NO_THROW void SLANG_MCALL
- writeTimestamp(IQueryPool* pool, GfxIndex index) override
+ writeTimestamp(IQueryPool* pool, GfxIndex index) override
{
m_writer->writeTimestamp(pool, index);
}
@@ -109,14 +108,16 @@ public:
ITextureResource* const* textures,
ResourceState src,
ResourceState dst) override
- {}
+ {
+ }
virtual SLANG_NO_THROW void SLANG_MCALL bufferBarrier(
GfxCount count,
IBufferResource* const* buffers,
ResourceState src,
ResourceState dst) override
- {}
+ {
+ }
virtual SLANG_NO_THROW void SLANG_MCALL copyTexture(
ITextureResource* dst,
@@ -238,43 +239,44 @@ public:
}
virtual SLANG_NO_THROW void SLANG_MCALL
- beginDebugEvent(const char* name, float rgbColor[3]) override
+ beginDebugEvent(const char* name, float rgbColor[3]) override
{
SLANG_UNUSED(name);
SLANG_UNUSED(rgbColor);
}
- virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent() override
- {
- }
+ virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent() override {}
};
ResourceCommandEncoderImpl m_resourceCommandEncoder;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeResourceCommands(IResourceCommandEncoder** outEncoder) override
+ encodeResourceCommands(IResourceCommandEncoder** outEncoder) override
{
m_resourceCommandEncoder.init(this);
*outEncoder = &m_resourceCommandEncoder;
}
- class RenderCommandEncoderImpl
- : public IRenderCommandEncoder
- , public ResourceCommandEncoderImpl
+ class RenderCommandEncoderImpl : public IRenderCommandEncoder, public ResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoderImpl)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
return nullptr;
}
+
public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override {}
- void init(CommandBufferImpl* cmdBuffer, SimpleRenderPassLayout* renderPass, IFramebuffer* framebuffer)
+ void init(
+ CommandBufferImpl* cmdBuffer,
+ SimpleRenderPassLayout* renderPass,
+ IFramebuffer* framebuffer)
{
ResourceCommandEncoderImpl::init(cmdBuffer);
@@ -310,38 +312,43 @@ public:
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override
+ bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override
{
m_writer->setPipelineState(state);
auto stateImpl = static_cast<PipelineStateBase*>(state);
SLANG_RETURN_ON_FAIL(m_commandBuffer->m_renderer->createRootShaderObject(
- stateImpl->m_program, m_commandBuffer->m_rootShaderObject.writeRef()));
+ stateImpl->m_program,
+ m_commandBuffer->m_rootShaderObject.writeRef()));
*outRootObject = m_commandBuffer->m_rootShaderObject.Ptr();
return SLANG_OK;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override
{
m_writer->setPipelineState(state);
auto stateImpl = static_cast<PipelineStateBase*>(state);
SLANG_RETURN_ON_FAIL(m_commandBuffer->m_renderer->createRootShaderObject(
- stateImpl->m_program, m_commandBuffer->m_rootShaderObject.writeRef()));
- m_commandBuffer->m_rootShaderObject->copyFrom(rootObject, m_commandBuffer->m_transientHeap);
+ stateImpl->m_program,
+ m_commandBuffer->m_rootShaderObject.writeRef()));
+ m_commandBuffer->m_rootShaderObject->copyFrom(
+ rootObject,
+ m_commandBuffer->m_transientHeap);
return SLANG_OK;
}
virtual SLANG_NO_THROW void SLANG_MCALL
- setViewports(GfxCount count, const Viewport* viewports) override
+ setViewports(GfxCount count, const Viewport* viewports) override
{
m_writer->setViewports(count, viewports);
}
virtual SLANG_NO_THROW void SLANG_MCALL
- setScissorRects(GfxCount count, const ScissorRect* scissors) override
+ setScissorRects(GfxCount count, const ScissorRect* scissors) override
{
m_writer->setScissorRects(count, scissors);
}
- virtual SLANG_NO_THROW void SLANG_MCALL setPrimitiveTopology(PrimitiveTopology topology) override
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ setPrimitiveTopology(PrimitiveTopology topology) override
{
m_writer->setPrimitiveTopology(topology);
}
@@ -355,13 +362,13 @@ public:
}
virtual SLANG_NO_THROW void SLANG_MCALL
- setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset) override
+ setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset) override
{
m_writer->setIndexBuffer(buffer, indexFormat, offset);
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- draw(GfxCount vertexCount, GfxIndex startVertex) override
+ draw(GfxCount vertexCount, GfxIndex startVertex) override
{
m_writer->bindRootShaderObject(m_commandBuffer->m_rootShaderObject);
m_writer->draw(vertexCount, startVertex);
@@ -369,14 +376,15 @@ public:
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- drawIndexed(GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex) override
+ drawIndexed(GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex) override
{
m_writer->bindRootShaderObject(m_commandBuffer->m_rootShaderObject);
m_writer->drawIndexed(indexCount, startIndex, baseVertex);
return SLANG_OK;
}
- virtual SLANG_NO_THROW void SLANG_MCALL setStencilReference(uint32_t referenceValue) override
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ setStencilReference(uint32_t referenceValue) override
{
m_writer->setStencilReference(referenceValue);
}
@@ -448,7 +456,12 @@ public:
GfxIndex startInstanceLocation) override
{
m_writer->bindRootShaderObject(m_commandBuffer->m_rootShaderObject);
- m_writer->drawIndexedInstanced(indexCount, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation);
+ m_writer->drawIndexedInstanced(
+ indexCount,
+ instanceCount,
+ startIndexLocation,
+ baseVertexLocation,
+ startInstanceLocation);
return SLANG_OK;
}
};
@@ -466,45 +479,47 @@ public:
*outEncoder = &m_renderCommandEncoder;
}
- class ComputeCommandEncoderImpl
- : public IComputeCommandEncoder
- , public ResourceCommandEncoderImpl
+ class ComputeCommandEncoderImpl : public IComputeCommandEncoder,
+ public ResourceCommandEncoderImpl
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoderImpl)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
return nullptr;
}
+
public:
- virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override
- {
- }
+ virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override {}
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override
+ bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override
{
m_writer->setPipelineState(state);
auto stateImpl = static_cast<PipelineStateBase*>(state);
SLANG_RETURN_ON_FAIL(m_commandBuffer->m_renderer->createRootShaderObject(
- stateImpl->m_program, m_commandBuffer->m_rootShaderObject.writeRef()));
+ stateImpl->m_program,
+ m_commandBuffer->m_rootShaderObject.writeRef()));
*outRootObject = m_commandBuffer->m_rootShaderObject.Ptr();
return SLANG_OK;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override
+ bindPipelineWithRootObject(IPipelineState* state, IShaderObject* rootObject) override
{
m_writer->setPipelineState(state);
auto stateImpl = static_cast<PipelineStateBase*>(state);
SLANG_RETURN_ON_FAIL(m_commandBuffer->m_renderer->createRootShaderObject(
- stateImpl->m_program, m_commandBuffer->m_rootShaderObject.writeRef()));
+ stateImpl->m_program,
+ m_commandBuffer->m_rootShaderObject.writeRef()));
m_commandBuffer->m_rootShaderObject->copyFrom(
- rootObject, m_commandBuffer->m_transientHeap);
+ rootObject,
+ m_commandBuffer->m_transientHeap);
return SLANG_OK;
}
@@ -515,7 +530,8 @@ public:
return SLANG_OK;
}
- virtual SLANG_NO_THROW Result SLANG_MCALL dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override
{
SLANG_UNIMPLEMENTED_X("ImmediateRenderBase::dispatchComputeIndirect");
}
@@ -523,19 +539,19 @@ public:
ComputeCommandEncoderImpl m_computeCommandEncoder;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeComputeCommands(IComputeCommandEncoder** outEncoder) override
+ encodeComputeCommands(IComputeCommandEncoder** outEncoder) override
{
m_computeCommandEncoder.init(this);
*outEncoder = &m_computeCommandEncoder;
}
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override
+ encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override
{
*outEncoder = nullptr;
}
- virtual SLANG_NO_THROW void SLANG_MCALL close() override { }
+ virtual SLANG_NO_THROW void SLANG_MCALL close() override {}
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outHandle) override
{
@@ -550,25 +566,31 @@ public:
switch (name)
{
case CommandName::SetPipelineState:
- m_renderer->setPipelineState(m_writer.getObject<PipelineStateBase>(cmd.operands[0]));
+ m_renderer->setPipelineState(
+ m_writer.getObject<PipelineStateBase>(cmd.operands[0]));
break;
case CommandName::BindRootShaderObject:
- m_renderer->bindRootShaderObject(m_writer.getObject<ShaderObjectBase>(cmd.operands[0]));
+ m_renderer->bindRootShaderObject(
+ m_writer.getObject<ShaderObjectBase>(cmd.operands[0]));
break;
case CommandName::SetFramebuffer:
m_renderer->setFramebuffer(m_writer.getObject<FramebufferBase>(cmd.operands[0]));
break;
case CommandName::ClearFrame:
m_renderer->clearFrame(
- cmd.operands[0], (cmd.operands[1] != 0), (cmd.operands[2] != 0));
+ cmd.operands[0],
+ (cmd.operands[1] != 0),
+ (cmd.operands[2] != 0));
break;
case CommandName::SetViewports:
m_renderer->setViewports(
- (UInt)cmd.operands[0], m_writer.getData<Viewport>(cmd.operands[1]));
+ (UInt)cmd.operands[0],
+ m_writer.getData<Viewport>(cmd.operands[1]));
break;
case CommandName::SetScissorRects:
m_renderer->setScissorRects(
- (UInt)cmd.operands[0], m_writer.getData<ScissorRect>(cmd.operands[1]));
+ (UInt)cmd.operands[0],
+ m_writer.getData<ScissorRect>(cmd.operands[1]));
break;
case CommandName::SetPrimitiveTopology:
m_renderer->setPrimitiveTopology((PrimitiveTopology)cmd.operands[0]);
@@ -594,27 +616,33 @@ public:
(Format)cmd.operands[1],
(UInt)cmd.operands[2]);
break;
- case CommandName::Draw:
- m_renderer->draw(cmd.operands[0], cmd.operands[1]);
- break;
+ case CommandName::Draw: m_renderer->draw(cmd.operands[0], cmd.operands[1]); break;
case CommandName::DrawIndexed:
- m_renderer->drawIndexed(
- cmd.operands[0], cmd.operands[1], cmd.operands[2]);
+ m_renderer->drawIndexed(cmd.operands[0], cmd.operands[1], cmd.operands[2]);
break;
case CommandName::DrawInstanced:
m_renderer->drawInstanced(
- cmd.operands[0], cmd.operands[1], cmd.operands[2], cmd.operands[3]);
+ cmd.operands[0],
+ cmd.operands[1],
+ cmd.operands[2],
+ cmd.operands[3]);
break;
case CommandName::DrawIndexedInstanced:
m_renderer->drawIndexedInstanced(
- cmd.operands[0], cmd.operands[1], cmd.operands[2], cmd.operands[3], cmd.operands[4]);
+ cmd.operands[0],
+ cmd.operands[1],
+ cmd.operands[2],
+ cmd.operands[3],
+ cmd.operands[4]);
break;
case CommandName::SetStencilReference:
m_renderer->setStencilReference(cmd.operands[0]);
break;
case CommandName::DispatchCompute:
m_renderer->dispatchCompute(
- int(cmd.operands[0]), int(cmd.operands[1]), int(cmd.operands[2]));
+ int(cmd.operands[0]),
+ int(cmd.operands[1]),
+ int(cmd.operands[2]));
break;
case CommandName::UploadBufferData:
m_renderer->uploadBufferData(
@@ -632,11 +660,11 @@ public:
cmd.operands[4]);
break;
case CommandName::WriteTimestamp:
- m_renderer->writeTimestamp(m_writer.getObject<QueryPoolBase>(cmd.operands[0]), (GfxIndex)cmd.operands[1]);
- break;
- default:
- assert(!"unknown command");
+ m_renderer->writeTimestamp(
+ m_writer.getObject<QueryPoolBase>(cmd.operands[0]),
+ (GfxIndex)cmd.operands[1]);
break;
+ default: assert(!"unknown command"); break;
}
}
m_writer.clear();
@@ -668,7 +696,10 @@ public:
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override { return m_desc; }
virtual SLANG_NO_THROW void SLANG_MCALL executeCommandBuffers(
- GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal) override
+ GfxCount count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal) override
{
// TODO: implement fence signal.
assert(fence == nullptr);
@@ -676,7 +707,8 @@ public:
CommandBufferInfo info = {};
for (GfxIndex i = 0; i < count; i++)
{
- info.hasWriteTimestamps |= static_cast<CommandBufferImpl*>(commandBuffers[i])->m_writer.m_hasWriteTimestamps;
+ info.hasWriteTimestamps |=
+ static_cast<CommandBufferImpl*>(commandBuffers[i])->m_writer.m_hasWriteTimestamps;
}
static_cast<ImmediateRendererBase*>(m_renderer.get())->beginCommandBuffer(info);
for (GfxIndex i = 0; i < count; i++)
@@ -688,8 +720,8 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL waitOnHost() override { getRenderer()->waitForGpu(); }
- virtual SLANG_NO_THROW Result SLANG_MCALL waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ waitForFenceValuesOnDevice(GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override
{
return SLANG_FAIL;
}
@@ -703,7 +735,7 @@ public:
using TransientResourceHeapImpl =
SimpleTransientResourceHeap<ImmediateRendererBase, CommandBufferImpl>;
-}
+} // namespace
ImmediateRendererBase::ImmediateRendererBase()
{
@@ -720,9 +752,8 @@ SLANG_NO_THROW Result SLANG_MCALL ImmediateRendererBase::createTransientResource
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL ImmediateRendererBase::createCommandQueue(
- const ICommandQueue::Desc& desc,
- ICommandQueue** outQueue)
+SLANG_NO_THROW Result SLANG_MCALL
+ImmediateRendererBase::createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue)
{
SLANG_UNUSED(desc);
// Only one queue is supported.
@@ -775,4 +806,4 @@ SLANG_NO_THROW SlangResult SLANG_MCALL ImmediateRendererBase::readBufferResource
return SLANG_OK;
}
-}
+} // namespace gfx
diff --git a/tools/gfx/immediate-renderer-base.h b/tools/gfx/immediate-renderer-base.h
index 894d00bf7..28aa52a70 100644
--- a/tools/gfx/immediate-renderer-base.h
+++ b/tools/gfx/immediate-renderer-base.h
@@ -17,9 +17,7 @@ enum class MapFlavor
WriteDiscard,
};
-class ImmediateCommandQueueBase
- : public ICommandQueue
- , public Slang::ComObject
+class ImmediateCommandQueueBase : public ICommandQueue, public Slang::ComObject
{
public:
// Immediate device also holds a strong reference to an instance of `ImmediateCommandQueue`,
@@ -64,11 +62,12 @@ public:
GfxCount slotCount,
IBufferResource* const* buffers,
const Offset* offsets) = 0;
- virtual void setIndexBuffer(
- IBufferResource* buffer, Format indexFormat, Offset offset = 0) = 0;
+ virtual void setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) = 0;
virtual void draw(GfxCount vertexCount, GfxIndex startVertex = 0) = 0;
virtual void drawIndexed(
- GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) = 0;
+ GfxCount indexCount,
+ GfxIndex startIndex = 0,
+ GfxIndex baseVertex = 0) = 0;
virtual void drawInstanced(
GfxCount vertexCount,
GfxCount instanceCount,
@@ -103,7 +102,7 @@ public:
ImmediateRendererBase();
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
+ createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTransientResourceHeap(
const ITransientResourceHeap::Desc& desc,
ITransientResourceHeap** outHeap) override;
@@ -111,10 +110,7 @@ public:
const IRenderPassLayout::Desc& desc,
IRenderPassLayout** outRenderPassLayout) override;
- void uploadBufferData(
- IBufferResource* dst,
- Offset offset,
- Size size, void* data);
+ void uploadBufferData(IBufferResource* dst, Offset offset, Size size, void* data);
virtual SLANG_NO_THROW SlangResult SLANG_MCALL readBufferResource(
IBufferResource* buffer,
@@ -159,8 +155,7 @@ public:
SLANG_UNUSED(buffers);
SLANG_UNUSED(offsets);
}
- virtual void setIndexBuffer(
- IBufferResource* buffer, Format indexFormat, Offset offset = 0)
+ virtual void setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0)
override
{
SLANG_UNUSED(buffer);
@@ -172,8 +167,8 @@ public:
SLANG_UNUSED(vertexCount);
SLANG_UNUSED(startVertex);
}
- virtual void drawIndexed(
- GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override
+ virtual void drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0)
+ override
{
SLANG_UNUSED(indexCount);
SLANG_UNUSED(startIndex);
@@ -228,7 +223,7 @@ public:
return SLANG_FAIL;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override
+ createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outFramebuffer);
@@ -243,9 +238,8 @@ public:
return SLANG_FAIL;
}
- virtual SLANG_NO_THROW Result SLANG_MCALL createInputLayout(
- IInputLayout::Desc const& desc,
- IInputLayout** outLayout) override
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outLayout);
@@ -274,4 +268,4 @@ public:
return SLANG_E_NOT_AVAILABLE;
}
};
-}
+} // namespace gfx
diff --git a/tools/gfx/metal/metal-api.cpp b/tools/gfx/metal/metal-api.cpp
index aa13a605f..8537cc630 100644
--- a/tools/gfx/metal/metal-api.cpp
+++ b/tools/gfx/metal/metal-api.cpp
@@ -4,5 +4,5 @@
#define CA_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
#include <Foundation/Foundation.hpp>
-#include <QuartzCore/QuartzCore.hpp>
#include <Metal/Metal.hpp>
+#include <QuartzCore/QuartzCore.hpp>
diff --git a/tools/gfx/metal/metal-base.h b/tools/gfx/metal/metal-base.h
index b1650a655..1a7a9eaff 100644
--- a/tools/gfx/metal/metal-base.h
+++ b/tools/gfx/metal/metal-base.h
@@ -14,41 +14,41 @@ namespace gfx
namespace metal
{
- class DeviceImpl;
- class InputLayoutImpl;
- class BufferResourceImpl;
- class FenceImpl;
- class TextureResourceImpl;
- class SamplerStateImpl;
- class ResourceViewImpl;
- class BufferResourceViewImpl;
- class TextureResourceViewImpl;
- class TexelBufferResourceViewImpl;
- class PlainBufferResourceViewImpl;
- class AccelerationStructureImpl;
- class FramebufferLayoutImpl;
- class RenderPassLayoutImpl;
- class FramebufferImpl;
- class PipelineStateImpl;
- class RayTracingPipelineStateImpl;
- class ShaderObjectLayoutImpl;
- class EntryPointLayout;
- class RootShaderObjectLayoutImpl;
- class ShaderProgramImpl;
- class PipelineCommandEncoder;
- class ShaderObjectImpl;
- class MutableShaderObjectImpl;
- class RootShaderObjectImpl;
- class ShaderTableImpl;
- class ResourceCommandEncoder;
- class RenderCommandEncoder;
- class ComputeCommandEncoder;
- class RayTracingCommandEncoder;
- class CommandBufferImpl;
- class CommandQueueImpl;
- class TransientResourceHeapImpl;
- class QueryPoolImpl;
- class SwapchainImpl;
+class DeviceImpl;
+class InputLayoutImpl;
+class BufferResourceImpl;
+class FenceImpl;
+class TextureResourceImpl;
+class SamplerStateImpl;
+class ResourceViewImpl;
+class BufferResourceViewImpl;
+class TextureResourceViewImpl;
+class TexelBufferResourceViewImpl;
+class PlainBufferResourceViewImpl;
+class AccelerationStructureImpl;
+class FramebufferLayoutImpl;
+class RenderPassLayoutImpl;
+class FramebufferImpl;
+class PipelineStateImpl;
+class RayTracingPipelineStateImpl;
+class ShaderObjectLayoutImpl;
+class EntryPointLayout;
+class RootShaderObjectLayoutImpl;
+class ShaderProgramImpl;
+class PipelineCommandEncoder;
+class ShaderObjectImpl;
+class MutableShaderObjectImpl;
+class RootShaderObjectImpl;
+class ShaderTableImpl;
+class ResourceCommandEncoder;
+class RenderCommandEncoder;
+class ComputeCommandEncoder;
+class RayTracingCommandEncoder;
+class CommandBufferImpl;
+class CommandQueueImpl;
+class TransientResourceHeapImpl;
+class QueryPoolImpl;
+class SwapchainImpl;
} // namespace metal
} // namespace gfx
diff --git a/tools/gfx/metal/metal-buffer.cpp b/tools/gfx/metal/metal-buffer.cpp
index 4f2964c5b..ebb48382e 100644
--- a/tools/gfx/metal/metal-buffer.cpp
+++ b/tools/gfx/metal/metal-buffer.cpp
@@ -1,5 +1,6 @@
// metal-buffer.cpp
#include "metal-buffer.h"
+
#include "metal-util.h"
namespace gfx
@@ -11,14 +12,11 @@ namespace metal
{
BufferResourceImpl::BufferResourceImpl(const IBufferResource::Desc& desc, DeviceImpl* device)
- : Parent(desc)
- , m_device(device)
+ : Parent(desc), m_device(device)
{
}
-BufferResourceImpl::~BufferResourceImpl()
-{
-}
+BufferResourceImpl::~BufferResourceImpl() {}
DeviceAddress BufferResourceImpl::getDeviceAddress()
{
diff --git a/tools/gfx/metal/metal-buffer.h b/tools/gfx/metal/metal-buffer.h
index 3f8f60d0e..d8e95c1f1 100644
--- a/tools/gfx/metal/metal-buffer.h
+++ b/tools/gfx/metal/metal-buffer.h
@@ -25,11 +25,13 @@ public:
virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL map(MemoryRange* rangeToRead, void** outPointer) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ map(MemoryRange* rangeToRead, void** outPointer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL unmap(MemoryRange* writtenRange) override;
diff --git a/tools/gfx/metal/metal-command-buffer.cpp b/tools/gfx/metal/metal-command-buffer.cpp
index 3f9923bf8..19708cfb6 100644
--- a/tools/gfx/metal/metal-command-buffer.cpp
+++ b/tools/gfx/metal/metal-command-buffer.cpp
@@ -1,10 +1,10 @@
// metal-command-buffer.cpp
#include "metal-command-buffer.h"
-#include "metal-device.h"
#include "metal-command-encoder.h"
-#include "metal-shader-object.h"
#include "metal-command-queue.h"
+#include "metal-device.h"
+#include "metal-shader-object.h"
namespace gfx
{
@@ -29,7 +29,9 @@ Result CommandBufferImpl::init(DeviceImpl* device, TransientResourceHeapImpl* tr
}
void CommandBufferImpl::encodeRenderCommands(
- IRenderPassLayout* renderPass, IFramebuffer* framebuffer, IRenderCommandEncoder** outEncoder)
+ IRenderPassLayout* renderPass,
+ IFramebuffer* framebuffer,
+ IRenderCommandEncoder** outEncoder)
{
if (!m_renderCommandEncoder)
{
@@ -72,7 +74,7 @@ void CommandBufferImpl::encodeRayTracingCommands(IRayTracingCommandEncoder** out
void CommandBufferImpl::close()
{
- //m_commandBuffer->commit();
+ // m_commandBuffer->commit();
}
Result CommandBufferImpl::getNativeHandle(InteropHandle* outHandle)
@@ -82,12 +84,14 @@ Result CommandBufferImpl::getNativeHandle(InteropHandle* outHandle)
return SLANG_OK;
}
-MTL::RenderCommandEncoder* CommandBufferImpl::getMetalRenderCommandEncoder(MTL::RenderPassDescriptor* renderPassDesc)
+MTL::RenderCommandEncoder* CommandBufferImpl::getMetalRenderCommandEncoder(
+ MTL::RenderPassDescriptor* renderPassDesc)
{
if (!m_metalRenderCommandEncoder)
{
endMetalCommandEncoder();
- m_metalRenderCommandEncoder = NS::RetainPtr(m_commandBuffer->renderCommandEncoder(renderPassDesc));
+ m_metalRenderCommandEncoder =
+ NS::RetainPtr(m_commandBuffer->renderCommandEncoder(renderPassDesc));
}
return m_metalRenderCommandEncoder.get();
}
diff --git a/tools/gfx/metal/metal-command-buffer.h b/tools/gfx/metal/metal-command-buffer.h
index f0b36898d..1f791d174 100644
--- a/tools/gfx/metal/metal-command-buffer.h
+++ b/tools/gfx/metal/metal-command-buffer.h
@@ -1,10 +1,10 @@
// metal-command-buffer.h
#pragma once
+#include "../simple-transient-resource-heap.h"
#include "metal-base.h"
-#include "metal-shader-object.h"
#include "metal-command-encoder.h"
-#include "../simple-transient-resource-heap.h"
+#include "metal-shader-object.h"
namespace gfx
{
@@ -14,9 +14,7 @@ using namespace Slang;
namespace metal
{
-class CommandBufferImpl
- : public ICommandBuffer
- , public ComObject
+class CommandBufferImpl : public ICommandBuffer, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -45,7 +43,8 @@ public:
void beginCommandBuffer();
- MTL::RenderCommandEncoder* getMetalRenderCommandEncoder(MTL::RenderPassDescriptor* renderPassDesc);
+ MTL::RenderCommandEncoder* getMetalRenderCommandEncoder(
+ MTL::RenderPassDescriptor* renderPassDesc);
MTL::ComputeCommandEncoder* getMetalComputeCommandEncoder();
MTL::BlitCommandEncoder* getMetalBlitCommandEncoder();
void endMetalCommandEncoder();
@@ -56,11 +55,11 @@ public:
IFramebuffer* framebuffer,
IRenderCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
+ encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
+ encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
+ encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL close() override;
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outHandle) override;
};
diff --git a/tools/gfx/metal/metal-command-encoder.cpp b/tools/gfx/metal/metal-command-encoder.cpp
index 442c216aa..f4c393193 100644
--- a/tools/gfx/metal/metal-command-encoder.cpp
+++ b/tools/gfx/metal/metal-command-encoder.cpp
@@ -3,6 +3,7 @@
#include "metal-buffer.h"
#include "metal-command-buffer.h"
+#include "metal-helper-functions.h"
#include "metal-query.h"
#include "metal-render-pass.h"
#include "metal-resource-views.h"
@@ -12,8 +13,6 @@
#include "metal-texture.h"
#include "metal-util.h"
-#include "metal-helper-functions.h"
-
namespace gfx
{
@@ -33,7 +32,9 @@ void PipelineCommandEncoder::endEncodingImpl()
m_commandBuffer->endMetalCommandEncoder();
}
-Result PipelineCommandEncoder::setPipelineStateImpl(IPipelineState* state, IShaderObject** outRootObject)
+Result PipelineCommandEncoder::setPipelineStateImpl(
+ IPipelineState* state,
+ IShaderObject** outRootObject)
{
m_currentPipeline = static_cast<PipelineStateImpl*>(state);
// m_commandBuffer->m_mutableRootShaderObject = nullptr;
@@ -52,11 +53,18 @@ void ResourceCommandEncoder::endEncoding()
void ResourceCommandEncoder::writeTimestamp(IQueryPool* queryPool, GfxIndex index)
{
auto encoder = m_commandBuffer->getMetalBlitCommandEncoder();
- encoder->sampleCountersInBuffer(static_cast<QueryPoolImpl*>(queryPool)->m_counterSampleBuffer.get(), index, true);
+ encoder->sampleCountersInBuffer(
+ static_cast<QueryPoolImpl*>(queryPool)->m_counterSampleBuffer.get(),
+ index,
+ true);
}
void ResourceCommandEncoder::copyBuffer(
- IBufferResource* dst, Offset dstOffset, IBufferResource* src, Offset srcOffset, Size size)
+ IBufferResource* dst,
+ Offset dstOffset,
+ IBufferResource* src,
+ Offset srcOffset,
+ Size size)
{
auto encoder = m_commandBuffer->getMetalBlitCommandEncoder();
encoder->copyFromBuffer(
@@ -80,7 +88,8 @@ void ResourceCommandEncoder::copyTexture(
{
auto encoder = m_commandBuffer->getMetalBlitCommandEncoder();
- if (dstSubresource.layerCount == 0 && dstSubresource.mipLevelCount == 0 && srcSubresource.layerCount == 0 && srcSubresource.mipLevelCount == 0)
+ if (dstSubresource.layerCount == 0 && dstSubresource.mipLevelCount == 0 &&
+ srcSubresource.layerCount == 0 && srcSubresource.mipLevelCount == 0)
{
encoder->copyFromTexture(
static_cast<TextureResourceImpl*>(src)->m_texture.get(),
@@ -131,7 +140,10 @@ void ResourceCommandEncoder::copyTextureToBuffer(
}
void ResourceCommandEncoder::uploadBufferData(
- IBufferResource* buffer, Offset offset, Size size, void* data)
+ IBufferResource* buffer,
+ Offset offset,
+ Size size,
+ void* data)
{
SLANG_UNIMPLEMENTED_X("uploadBufferData");
}
@@ -148,13 +160,19 @@ void ResourceCommandEncoder::uploadTextureData(
}
void ResourceCommandEncoder::bufferBarrier(
- GfxCount count, IBufferResource* const* buffers, ResourceState src, ResourceState dst)
+ GfxCount count,
+ IBufferResource* const* buffers,
+ ResourceState src,
+ ResourceState dst)
{
// We use automatic hazard tracking for now, no need for barriers.
}
void ResourceCommandEncoder::textureBarrier(
- GfxCount count, ITextureResource* const* textures, ResourceState src, ResourceState dst)
+ GfxCount count,
+ ITextureResource* const* textures,
+ ResourceState src,
+ ResourceState dst)
{
// We use automatic hazard tracking for now, no need for barriers.
}
@@ -169,7 +187,9 @@ void ResourceCommandEncoder::textureSubresourceBarrier(
}
void ResourceCommandEncoder::clearResourceView(
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags)
+ IResourceView* view,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags)
{
SLANG_UNIMPLEMENTED_X("clearResourceView");
}
@@ -186,7 +206,11 @@ void ResourceCommandEncoder::resolveResource(
}
void ResourceCommandEncoder::resolveQuery(
- IQueryPool* queryPool, GfxIndex index, GfxCount count, IBufferResource* buffer, Offset offset)
+ IQueryPool* queryPool,
+ GfxIndex index,
+ GfxCount count,
+ IBufferResource* buffer,
+ Offset offset)
{
auto encoder = m_commandBuffer->getMetalBlitCommandEncoder();
encoder->resolveCounters(
@@ -226,7 +250,8 @@ void RenderCommandEncoder::beginPass(IRenderPassLayout* renderPass, IFramebuffer
for (Index i = 0; i < m_framebuffer->m_renderTargetViews.getCount(); ++i)
{
TextureResourceViewImpl* renderTargetView = m_framebuffer->m_renderTargetViews[i];
- MTL::RenderPassColorAttachmentDescriptor* colorAttachment = m_renderPassDesc->colorAttachments()->object(i);
+ MTL::RenderPassColorAttachmentDescriptor* colorAttachment =
+ m_renderPassDesc->colorAttachments()->object(i);
colorAttachment->setTexture(renderTargetView->m_textureView.get());
colorAttachment->setLevel(renderTargetView->m_desc.subresourceRange.mipLevel);
colorAttachment->setSlice(renderTargetView->m_desc.subresourceRange.baseArrayLayer);
@@ -235,17 +260,20 @@ void RenderCommandEncoder::beginPass(IRenderPassLayout* renderPass, IFramebuffer
if (m_framebuffer->m_depthStencilView)
{
TextureResourceViewImpl* depthStencilView = m_framebuffer->m_depthStencilView.get();
- MTL::PixelFormat pixelFormat = MetalUtil::translatePixelFormat(depthStencilView->m_desc.format);
+ MTL::PixelFormat pixelFormat =
+ MetalUtil::translatePixelFormat(depthStencilView->m_desc.format);
if (MetalUtil::isDepthFormat(pixelFormat))
{
- MTL::RenderPassDepthAttachmentDescriptor* depthAttachment = m_renderPassDesc->depthAttachment();
+ MTL::RenderPassDepthAttachmentDescriptor* depthAttachment =
+ m_renderPassDesc->depthAttachment();
depthAttachment->setTexture(depthStencilView->m_textureView.get());
depthAttachment->setLevel(depthStencilView->m_desc.subresourceRange.mipLevel);
depthAttachment->setSlice(depthStencilView->m_desc.subresourceRange.baseArrayLayer);
}
if (MetalUtil::isStencilFormat(pixelFormat))
{
- MTL::RenderPassStencilAttachmentDescriptor* stencilAttachment = m_renderPassDesc->stencilAttachment();
+ MTL::RenderPassStencilAttachmentDescriptor* stencilAttachment =
+ m_renderPassDesc->stencilAttachment();
stencilAttachment->setTexture(depthStencilView->m_textureView.get());
stencilAttachment->setLevel(depthStencilView->m_desc.subresourceRange.mipLevel);
stencilAttachment->setSlice(depthStencilView->m_desc.subresourceRange.baseArrayLayer);
@@ -259,13 +287,15 @@ void RenderCommandEncoder::endEncoding()
}
Result RenderCommandEncoder::bindPipeline(
- IPipelineState* pipelineState, IShaderObject** outRootObject)
+ IPipelineState* pipelineState,
+ IShaderObject** outRootObject)
{
return setPipelineStateImpl(pipelineState, outRootObject);
}
Result RenderCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject)
+ IPipelineState* pipelineState,
+ IShaderObject* rootObject)
{
return SLANG_E_NOT_IMPLEMENTED;
}
@@ -324,21 +354,18 @@ void RenderCommandEncoder::setVertexBuffers(
}
void RenderCommandEncoder::setIndexBuffer(
- IBufferResource* buffer, Format indexFormat, Offset offset)
+ IBufferResource* buffer,
+ Format indexFormat,
+ Offset offset)
{
m_indexBuffer = static_cast<BufferResourceImpl*>(buffer)->m_buffer.get();
m_indexBufferOffset = offset;
switch (indexFormat)
{
- case Format::R16_UINT:
- m_indexBufferType = MTL::IndexTypeUInt16;
- break;
- case Format::R32_UINT:
- m_indexBufferType = MTL::IndexTypeUInt32;
- break;
- default:
- assert(!"unsupported index format");
+ case Format::R16_UINT: m_indexBufferType = MTL::IndexTypeUInt16; break;
+ case Format::R32_UINT: m_indexBufferType = MTL::IndexTypeUInt32; break;
+ default: assert(!"unsupported index format");
}
}
@@ -348,7 +375,9 @@ void RenderCommandEncoder::setStencilReference(uint32_t referenceValue)
}
Result RenderCommandEncoder::setSamplePositions(
- GfxCount samplesPerPixel, GfxCount pixelCount, const SamplePosition* samplePositions)
+ GfxCount samplesPerPixel,
+ GfxCount pixelCount,
+ const SamplePosition* samplePositions)
{
return SLANG_E_NOT_AVAILABLE;
}
@@ -368,7 +397,10 @@ Result RenderCommandEncoder::prepareDraw(MTL::RenderCommandEncoder*& encoder)
for (Index i = 0; i < m_vertexBuffers.getCount(); ++i)
{
- encoder->setVertexBuffer(m_vertexBuffers[i], m_vertexBufferOffsets[i], m_currentPipeline->m_vertexBufferOffset + i);
+ encoder->setVertexBuffer(
+ m_vertexBuffers[i],
+ m_vertexBufferOffsets[i],
+ m_currentPipeline->m_vertexBufferOffset + i);
}
encoder->setViewports(m_viewports.getArrayView().getBuffer(), m_viewports.getCount());
@@ -378,8 +410,13 @@ Result RenderCommandEncoder::prepareDraw(MTL::RenderCommandEncoder*& encoder)
const DepthStencilDesc& depthStencilDesc = pipeline->desc.graphics.depthStencil;
encoder->setFrontFacingWinding(MetalUtil::translateWinding(rasterDesc.frontFace));
encoder->setCullMode(MetalUtil::translateCullMode(rasterDesc.cullMode));
- encoder->setDepthClipMode(rasterDesc.depthClipEnable ? MTL::DepthClipModeClip : MTL::DepthClipModeClamp); // TODO correct?
- encoder->setDepthBias(rasterDesc.depthBias, rasterDesc.slopeScaledDepthBias, rasterDesc.depthBiasClamp);
+ encoder->setDepthClipMode(
+ rasterDesc.depthClipEnable ? MTL::DepthClipModeClip
+ : MTL::DepthClipModeClamp); // TODO correct?
+ encoder->setDepthBias(
+ rasterDesc.depthBias,
+ rasterDesc.slopeScaledDepthBias,
+ rasterDesc.depthBiasClamp);
encoder->setTriangleFillMode(MetalUtil::translateTriangleFillMode(rasterDesc.fillMode));
// encoder->setBlendColor(); // not supported by gfx
if (m_framebuffer->m_depthStencilView)
@@ -400,12 +437,19 @@ Result RenderCommandEncoder::draw(GfxCount vertexCount, GfxIndex startVertex)
}
Result RenderCommandEncoder::drawIndexed(
- GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex)
+ GfxCount indexCount,
+ GfxIndex startIndex,
+ GfxIndex baseVertex)
{
MTL::RenderCommandEncoder* encoder;
SLANG_RETURN_ON_FAIL(prepareDraw(encoder));
// TODO baseVertex is not supported by Metal
- encoder->drawIndexedPrimitives(m_primitiveType, indexCount, m_indexBufferType, m_indexBuffer, m_indexBufferOffset);
+ encoder->drawIndexedPrimitives(
+ m_primitiveType,
+ indexCount,
+ m_indexBufferType,
+ m_indexBuffer,
+ m_indexBufferOffset);
return SLANG_OK;
}
@@ -437,7 +481,12 @@ Result RenderCommandEncoder::drawInstanced(
{
MTL::RenderCommandEncoder* encoder;
SLANG_RETURN_ON_FAIL(prepareDraw(encoder));
- encoder->drawPrimitives(m_primitiveType, startVertex, vertexCount, instanceCount, startInstanceLocation);
+ encoder->drawPrimitives(
+ m_primitiveType,
+ startVertex,
+ vertexCount,
+ instanceCount,
+ startInstanceLocation);
return SLANG_OK;
}
@@ -450,7 +499,15 @@ Result RenderCommandEncoder::drawIndexedInstanced(
{
MTL::RenderCommandEncoder* encoder;
SLANG_RETURN_ON_FAIL(prepareDraw(encoder));
- encoder->drawIndexedPrimitives(m_primitiveType, indexCount, m_indexBufferType, m_indexBuffer, startIndexLocation, instanceCount, baseVertexLocation, startIndexLocation);
+ encoder->drawIndexedPrimitives(
+ m_primitiveType,
+ indexCount,
+ m_indexBufferType,
+ m_indexBuffer,
+ startIndexLocation,
+ instanceCount,
+ baseVertexLocation,
+ startIndexLocation);
return SLANG_OK;
}
@@ -465,13 +522,15 @@ void ComputeCommandEncoder::endEncoding()
}
Result ComputeCommandEncoder::bindPipeline(
- IPipelineState* pipelineState, IShaderObject** outRootObject)
+ IPipelineState* pipelineState,
+ IShaderObject** outRootObject)
{
return setPipelineStateImpl(pipelineState, outRootObject);
}
Result ComputeCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject)
+ IPipelineState* pipelineState,
+ IShaderObject* rootObject)
{
return SLANG_E_NOT_IMPLEMENTED;
}
@@ -489,16 +548,18 @@ Result ComputeCommandEncoder::dispatchCompute(int x, int y, int z)
RootShaderObjectImpl* rootObjectImpl = &m_commandBuffer->m_rootObject;
RefPtr<PipelineStateBase> newPipeline;
SLANG_RETURN_ON_FAIL(m_commandBuffer->m_device->maybeSpecializePipeline(
- m_currentPipeline, rootObjectImpl, newPipeline));
+ m_currentPipeline,
+ rootObjectImpl,
+ newPipeline));
PipelineStateImpl* newPipelineImpl = static_cast<PipelineStateImpl*>(newPipeline.Ptr());
SLANG_RETURN_ON_FAIL(newPipelineImpl->ensureAPIPipelineStateCreated());
m_currentPipeline = newPipelineImpl;
-
+
m_currentPipeline->ensureAPIPipelineStateCreated();
encoder->setComputePipelineState(m_currentPipeline->m_computePipelineState.get());
-
+
encoder->dispatchThreadgroups(MTL::Size(x, y, z), m_currentPipeline->m_threadGroupSize);
return SLANG_OK;
@@ -533,7 +594,9 @@ void RayTracingCommandEncoder::buildAccelerationStructure(
}
void RayTracingCommandEncoder::copyAccelerationStructure(
- IAccelerationStructure* dest, IAccelerationStructure* src, AccelerationStructureCopyMode mode)
+ IAccelerationStructure* dest,
+ IAccelerationStructure* src,
+ AccelerationStructureCopyMode mode)
{
}
@@ -544,26 +607,34 @@ void RayTracingCommandEncoder::queryAccelerationStructureProperties(
AccelerationStructureQueryDesc* queryDescs)
{
_queryAccelerationStructureProperties(
- accelerationStructureCount, accelerationStructures, queryCount, queryDescs);
+ accelerationStructureCount,
+ accelerationStructures,
+ queryCount,
+ queryDescs);
}
void RayTracingCommandEncoder::serializeAccelerationStructure(
- DeviceAddress dest, IAccelerationStructure* source)
+ DeviceAddress dest,
+ IAccelerationStructure* source)
{
}
void RayTracingCommandEncoder::deserializeAccelerationStructure(
- IAccelerationStructure* dest, DeviceAddress source)
+ IAccelerationStructure* dest,
+ DeviceAddress source)
{
}
-Result RayTracingCommandEncoder::bindPipeline(IPipelineState* pipeline, IShaderObject** outRootObject)
+Result RayTracingCommandEncoder::bindPipeline(
+ IPipelineState* pipeline,
+ IShaderObject** outRootObject)
{
return SLANG_E_NOT_IMPLEMENTED;
}
Result RayTracingCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject)
+ IPipelineState* pipelineState,
+ IShaderObject* rootObject)
{
return SLANG_E_NOT_IMPLEMENTED;
}
@@ -578,7 +649,7 @@ Result RayTracingCommandEncoder::dispatchRays(
return SLANG_E_NOT_IMPLEMENTED;
}
-void RayTracingCommandEncoder::endEncoding() { }
+void RayTracingCommandEncoder::endEncoding() {}
} // namespace metal
} // namespace gfx
diff --git a/tools/gfx/metal/metal-command-encoder.h b/tools/gfx/metal/metal-command-encoder.h
index 8ef9e5fb5..9ca53f745 100644
--- a/tools/gfx/metal/metal-command-encoder.h
+++ b/tools/gfx/metal/metal-command-encoder.h
@@ -24,12 +24,9 @@ public:
void endEncodingImpl();
Result setPipelineStateImpl(IPipelineState* state, IShaderObject** outRootObject);
-
};
-class ResourceCommandEncoder
- : public IResourceCommandEncoder
- , public PipelineCommandEncoder
+class ResourceCommandEncoder : public IResourceCommandEncoder, public PipelineCommandEncoder
{
public:
virtual void* getInterface(SlangUUID const& guid)
@@ -39,7 +36,7 @@ public:
return nullptr;
}
virtual SLANG_NO_THROW SlangResult SLANG_MCALL
- queryInterface(SlangUUID const& uuid, void** outObject) override
+ queryInterface(SlangUUID const& uuid, void** outObject) override
{
if (auto ptr = getInterface(uuid))
{
@@ -54,7 +51,7 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW void SLANG_MCALL
- writeTimestamp(IQueryPool* queryPool, GfxIndex index) override;
+ writeTimestamp(IQueryPool* queryPool, GfxIndex index) override;
virtual SLANG_NO_THROW void SLANG_MCALL copyBuffer(
IBufferResource* dst,
@@ -86,7 +83,7 @@ public:
ITextureResource::Extents extent) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- uploadBufferData(IBufferResource* buffer, Offset offset, Size size, void* data) override;
+ uploadBufferData(IBufferResource* buffer, Offset offset, Size size, void* data) override;
virtual SLANG_NO_THROW void SLANG_MCALL uploadTextureData(
ITextureResource* dst,
@@ -122,7 +119,9 @@ public:
ClearResourceViewFlags::Enum flags);
virtual SLANG_NO_THROW void SLANG_MCALL clearResourceView(
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags) override;
+ IResourceView* view,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags) override;
virtual SLANG_NO_THROW void SLANG_MCALL resolveResource(
ITextureResource* source,
@@ -140,25 +139,24 @@ public:
Offset offset) override;
-
virtual SLANG_NO_THROW void SLANG_MCALL
- beginDebugEvent(const char* name, float rgbColor[3]) override;
+ beginDebugEvent(const char* name, float rgbColor[3]) override;
virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent() override;
};
-class RenderCommandEncoder
- : public IRenderCommandEncoder
- , public ResourceCommandEncoder
+class RenderCommandEncoder : public IRenderCommandEncoder, public ResourceCommandEncoder
{
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoder)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
return nullptr;
}
+
public:
RefPtr<RenderPassLayoutImpl> m_renderPassLayout;
RefPtr<FramebufferImpl> m_framebuffer;
@@ -183,19 +181,19 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* pipelineState, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* pipelineState, IShaderObject** outRootObject) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ bindPipelineWithRootObject(IPipelineState* pipelineState, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setViewports(GfxCount count, const Viewport* viewports) override;
+ setViewports(GfxCount count, const Viewport* viewports) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setScissorRects(GfxCount count, const ScissorRect* rects) override;
+ setScissorRects(GfxCount count, const ScissorRect* rects) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setPrimitiveTopology(PrimitiveTopology topology) override;
+ setPrimitiveTopology(PrimitiveTopology topology) override;
virtual SLANG_NO_THROW void SLANG_MCALL setVertexBuffers(
GfxIndex startSlot,
@@ -204,7 +202,7 @@ public:
const Offset* offsets) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) override;
+ setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) override;
virtual SLANG_NO_THROW void SLANG_MCALL setStencilReference(uint32_t referenceValue) override;
@@ -216,9 +214,9 @@ public:
Result prepareDraw(MTL::RenderCommandEncoder*& encoder);
virtual SLANG_NO_THROW Result SLANG_MCALL
- draw(GfxCount vertexCount, GfxIndex startVertex = 0) override;
+ draw(GfxCount vertexCount, GfxIndex startVertex = 0) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override;
+ drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override;
virtual SLANG_NO_THROW Result SLANG_MCALL drawIndirect(
GfxCount maxDrawCount,
@@ -247,19 +245,17 @@ public:
GfxIndex baseVertexLocation,
GfxIndex startInstanceLocation) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL
- drawMeshTasks(int x, int y, int z) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL drawMeshTasks(int x, int y, int z) override;
};
-class ComputeCommandEncoder
- : public IComputeCommandEncoder
- , public ResourceCommandEncoder
+class ComputeCommandEncoder : public IComputeCommandEncoder, public ResourceCommandEncoder
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoder)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
@@ -269,33 +265,32 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* pipelineState, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* pipelineState, IShaderObject** outRootObject) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ bindPipelineWithRootObject(IPipelineState* pipelineState, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL dispatchCompute(int x, int y, int z) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override;
+ dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override;
};
-class RayTracingCommandEncoder
- : public IRayTracingCommandEncoder
- , public ResourceCommandEncoder
+class RayTracingCommandEncoder : public IRayTracingCommandEncoder, public ResourceCommandEncoder
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoder)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IRayTracingCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IRayTracingCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
return nullptr;
}
-public:
+public:
void _memoryBarrier(
int count,
IAccelerationStructure* const* structures,
@@ -325,16 +320,16 @@ public:
AccelerationStructureQueryDesc* queryDescs) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure* source) override;
+ serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure* source) override;
- virtual SLANG_NO_THROW void SLANG_MCALL deserializeAccelerationStructure(
- IAccelerationStructure* dest, DeviceAddress source) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ deserializeAccelerationStructure(IAccelerationStructure* dest, DeviceAddress source) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* pipeline, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* pipeline, IShaderObject** outRootObject) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ bindPipelineWithRootObject(IPipelineState* pipelineState, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL dispatchRays(
GfxIndex raygenShaderIndex,
diff --git a/tools/gfx/metal/metal-command-queue.cpp b/tools/gfx/metal/metal-command-queue.cpp
index 920b6ef7e..4175076da 100644
--- a/tools/gfx/metal/metal-command-queue.cpp
+++ b/tools/gfx/metal/metal-command-queue.cpp
@@ -10,7 +10,7 @@ namespace gfx
using namespace Slang;
-namespace metal
+namespace metal
{
ICommandQueue* CommandQueueImpl::getInterface(const Guid& guid)
@@ -20,9 +20,7 @@ ICommandQueue* CommandQueueImpl::getInterface(const Guid& guid)
return nullptr;
}
-CommandQueueImpl::~CommandQueueImpl()
-{
-}
+CommandQueueImpl::~CommandQueueImpl() {}
void CommandQueueImpl::init(DeviceImpl* device, NS::SharedPtr<MTL::CommandQueue> commandQueue)
{
@@ -42,10 +40,15 @@ Result CommandQueueImpl::getNativeHandle(InteropHandle* outHandle)
return SLANG_OK;
}
-const CommandQueueImpl::Desc& CommandQueueImpl::getDesc() { return m_desc; }
+const CommandQueueImpl::Desc& CommandQueueImpl::getDesc()
+{
+ return m_desc;
+}
Result CommandQueueImpl::waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* waitValues)
{
for (GfxCount i = 0; i < fenceCount; ++i)
{
@@ -58,7 +61,10 @@ Result CommandQueueImpl::waitForFenceValuesOnDevice(
}
void CommandQueueImpl::queueSubmitImpl(
- uint32_t count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal)
+ uint32_t count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal)
{
// If there are any pending wait fences, encode them to a new command buffer.
// Metal ensures that command buffers are executed in the order they are committed.
@@ -79,7 +85,9 @@ void CommandQueueImpl::queueSubmitImpl(
// If this is the last command buffer and a fence is provided, signal the fence.
if (i == count - 1 && fence != nullptr)
{
- cmdBufImpl->m_commandBuffer->encodeSignalEvent(static_cast<FenceImpl*>(fence)->m_event.get(), valueToSignal);
+ cmdBufImpl->m_commandBuffer->encodeSignalEvent(
+ static_cast<FenceImpl*>(fence)->m_event.get(),
+ valueToSignal);
}
cmdBufImpl->m_commandBuffer->commit();
}
@@ -88,13 +96,18 @@ void CommandQueueImpl::queueSubmitImpl(
if (count == 0 && fence != nullptr)
{
MTL::CommandBuffer* commandBuffer = m_commandQueue->commandBuffer();
- commandBuffer->encodeSignalEvent(static_cast<FenceImpl*>(fence)->m_event.get(), valueToSignal);
+ commandBuffer->encodeSignalEvent(
+ static_cast<FenceImpl*>(fence)->m_event.get(),
+ valueToSignal);
commandBuffer->commit();
}
}
void CommandQueueImpl::executeCommandBuffers(
- GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal)
+ GfxCount count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal)
{
AUTORELEASEPOOL
diff --git a/tools/gfx/metal/metal-command-queue.h b/tools/gfx/metal/metal-command-queue.h
index 045f4ed73..1f825360b 100644
--- a/tools/gfx/metal/metal-command-queue.h
+++ b/tools/gfx/metal/metal-command-queue.h
@@ -9,12 +9,10 @@ namespace gfx
using namespace Slang;
-namespace metal
+namespace metal
{
-class CommandQueueImpl
- : public ICommandQueue
- , public ComObject
+class CommandQueueImpl : public ICommandQueue, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -42,8 +40,8 @@ public:
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ waitForFenceValuesOnDevice(GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
void queueSubmitImpl(
uint32_t count,
diff --git a/tools/gfx/metal/metal-device.cpp b/tools/gfx/metal/metal-device.cpp
index 609c1bf27..ff534a78c 100644
--- a/tools/gfx/metal/metal-device.cpp
+++ b/tools/gfx/metal/metal-device.cpp
@@ -1,25 +1,25 @@
// metal-device.cpp
#include "metal-device.h"
-#include "metal-swap-chain.h"
-#include "metal-util.h"
#include "../resource-desc-utils.h"
-#include "metal-texture.h"
+#include "metal-buffer.h"
#include "metal-render-pass.h"
-#include "metal-vertex-layout.h"
#include "metal-shader-program.h"
-#include "metal-buffer.h"
-//#include "metal-command-queue.h"
+#include "metal-swap-chain.h"
+#include "metal-texture.h"
+#include "metal-util.h"
+#include "metal-vertex-layout.h"
+// #include "metal-command-queue.h"
#include "metal-fence.h"
#include "metal-query.h"
-//#include "metal-resource-views.h"
+// #include "metal-resource-views.h"
#include "metal-sampler.h"
-#include "metal-shader-object.h"
#include "metal-shader-object-layout.h"
-//#include "metal-shader-table.h"
+#include "metal-shader-object.h"
+// #include "metal-shader-table.h"
#include "metal-transient-heap.h"
-//#include "metal-pipeline-dump-layer.h"
-//#include "metal-helper-functions.h"
+// #include "metal-pipeline-dump-layer.h"
+// #include "metal-helper-functions.h"
#include "source/core/slang-platform.h"
namespace gfx
@@ -37,9 +37,7 @@ static bool shouldDumpPipeline()
return dumpPipelineSettings.produceString() == "1";
}
-DeviceImpl::~DeviceImpl()
-{
-}
+DeviceImpl::~DeviceImpl() {}
Result DeviceImpl::getNativeDeviceHandles(InteropHandles* outHandles)
{
@@ -59,7 +57,7 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
m_info.projectionStyle = ProjectionStyle::Metal;
m_info.deviceType = DeviceType::Metal;
m_info.adapterName = "default";
- static const float kIdentity[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
+ static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
::memcpy(m_info.identityProjectionMatrix, kIdentity, sizeof(kIdentity));
}
@@ -83,23 +81,27 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
desc.extendedDescs,
SLANG_METAL_LIB,
"",
- makeArray(slang::PreprocessorMacroDesc{ "__METAL__", "1" }).getView()));
+ makeArray(slang::PreprocessorMacroDesc{"__METAL__", "1"}).getView()));
// TODO: expose via some other means
if (captureEnabled())
{
MTL::CaptureManager* captureManager = MTL::CaptureManager::sharedCaptureManager();
MTL::CaptureDescriptor* d = MTL::CaptureDescriptor::alloc()->init();
- MTL::CaptureDestination captureDest = MTL::CaptureDestination::CaptureDestinationGPUTraceDocument;
+ MTL::CaptureDestination captureDest =
+ MTL::CaptureDestination::CaptureDestinationGPUTraceDocument;
if (!captureManager->supportsDestination(MTL::CaptureDestinationGPUTraceDocument))
{
- std::cout << "Cannot capture MTL calls to document; ensure that Info.plist exists with 'MetalCaptureEnabled' set to 'true'." << std::endl;
+ std::cout << "Cannot capture MTL calls to document; ensure that Info.plist exists with "
+ "'MetalCaptureEnabled' set to 'true'."
+ << std::endl;
exit(1);
}
d->setDestination(MTL::CaptureDestinationGPUTraceDocument);
d->setCaptureObject(m_device.get());
NS::SharedPtr<NS::String> path = MetalUtil::createString("frame.gputrace");
- NS::SharedPtr<NS::URL> url = NS::TransferPtr(NS::URL::alloc()->initFileURLWithPath(path.get()));
+ NS::SharedPtr<NS::URL> url =
+ NS::TransferPtr(NS::URL::alloc()->initFileURLWithPath(path.get()));
d->setOutputURL(url.get());
NS::Error* errorCode = NS::Error::alloc();
if (!captureManager->startCapture(d, &errorCode))
@@ -113,7 +115,7 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
return SLANG_OK;
}
-//void DeviceImpl::waitForGpu() { m_deviceQueue.flushAndWait(); }
+// void DeviceImpl::waitForGpu() { m_deviceQueue.flushAndWait(); }
const DeviceInfo& DeviceImpl::getDeviceInfo() const
@@ -121,7 +123,9 @@ const DeviceInfo& DeviceImpl::getDeviceInfo() const
return m_info;
}
-Result DeviceImpl::createTransientResourceHeap(const ITransientResourceHeap::Desc& desc, ITransientResourceHeap** outHeap)
+Result DeviceImpl::createTransientResourceHeap(
+ const ITransientResourceHeap::Desc& desc,
+ ITransientResourceHeap** outHeap)
{
AUTORELEASEPOOL
@@ -146,7 +150,9 @@ Result DeviceImpl::createCommandQueue(const ICommandQueue::Desc& desc, ICommandQ
}
Result DeviceImpl::createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain)
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain)
{
AUTORELEASEPOOL
@@ -156,7 +162,9 @@ Result DeviceImpl::createSwapchain(
return SLANG_OK;
}
-Result DeviceImpl::createFramebufferLayout(const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout)
+Result DeviceImpl::createFramebufferLayout(
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout)
{
AUTORELEASEPOOL
@@ -166,7 +174,9 @@ Result DeviceImpl::createFramebufferLayout(const IFramebufferLayout::Desc& desc,
return SLANG_OK;
}
-Result DeviceImpl::createRenderPassLayout(const IRenderPassLayout::Desc& desc, IRenderPassLayout** outRenderPassLayout)
+Result DeviceImpl::createRenderPassLayout(
+ const IRenderPassLayout::Desc& desc,
+ IRenderPassLayout** outRenderPassLayout)
{
AUTORELEASEPOOL
@@ -199,7 +209,7 @@ SlangResult DeviceImpl::readTextureResource(
if (textureImpl->getDesc()->sampleDesc.numSamples > 1)
{
- return SLANG_E_NOT_IMPLEMENTED;
+ return SLANG_E_NOT_IMPLEMENTED;
}
NS::SharedPtr<MTL::Texture> srcTexture = textureImpl->m_texture;
@@ -220,7 +230,8 @@ SlangResult DeviceImpl::readTextureResource(
*outPixelSize = bytesPerPixel;
// create staging buffer
- NS::SharedPtr<MTL::Buffer> stagingBuffer = NS::TransferPtr(m_device->newBuffer(bufferSize, MTL::StorageModeShared));
+ NS::SharedPtr<MTL::Buffer> stagingBuffer =
+ NS::TransferPtr(m_device->newBuffer(bufferSize, MTL::StorageModeShared));
if (!stagingBuffer)
{
return SLANG_FAIL;
@@ -229,8 +240,15 @@ SlangResult DeviceImpl::readTextureResource(
MTL::CommandBuffer* commandBuffer = m_commandQueue->commandBuffer();
MTL::BlitCommandEncoder* encoder = commandBuffer->blitCommandEncoder();
encoder->copyFromTexture(
- srcTexture.get(), 0, 0, MTL::Origin(0, 0, 0), MTL::Size(width, height, depth),
- stagingBuffer.get(), 0, bytesPerRow, bytesPerSlice);
+ srcTexture.get(),
+ 0,
+ 0,
+ MTL::Origin(0, 0, 0),
+ MTL::Size(width, height, depth),
+ stagingBuffer.get(),
+ 0,
+ bytesPerRow,
+ bytesPerSlice);
encoder->endEncoding();
commandBuffer->commit();
commandBuffer->waitUntilCompleted();
@@ -245,12 +263,16 @@ SlangResult DeviceImpl::readTextureResource(
}
SlangResult DeviceImpl::readBufferResource(
- IBufferResource* buffer, Offset offset, Size size, ISlangBlob** outBlob)
+ IBufferResource* buffer,
+ Offset offset,
+ Size size,
+ ISlangBlob** outBlob)
{
AUTORELEASEPOOL
// create staging buffer
- NS::SharedPtr<MTL::Buffer> stagingBuffer = NS::TransferPtr(m_device->newBuffer(size, MTL::StorageModeShared));
+ NS::SharedPtr<MTL::Buffer> stagingBuffer =
+ NS::TransferPtr(m_device->newBuffer(size, MTL::StorageModeShared));
if (!stagingBuffer)
{
return SLANG_FAIL;
@@ -258,7 +280,12 @@ SlangResult DeviceImpl::readBufferResource(
MTL::CommandBuffer* commandBuffer = m_commandQueue->commandBuffer();
MTL::BlitCommandEncoder* blitEncoder = commandBuffer->blitCommandEncoder();
- blitEncoder->copyFromBuffer(static_cast<BufferResourceImpl*>(buffer)->m_buffer.get(), offset, stagingBuffer.get(), 0, size);
+ blitEncoder->copyFromBuffer(
+ static_cast<BufferResourceImpl*>(buffer)->m_buffer.get(),
+ offset,
+ stagingBuffer.get(),
+ 0,
+ size);
blitEncoder->endEncoding();
commandBuffer->commit();
commandBuffer->waitUntilCompleted();
@@ -282,7 +309,8 @@ Result DeviceImpl::getAccelerationStructurePrebuildInfo(
}
Result DeviceImpl::createAccelerationStructure(
- const IAccelerationStructure::CreateDesc& desc, IAccelerationStructure** outAS)
+ const IAccelerationStructure::CreateDesc& desc,
+ IAccelerationStructure** outAS)
{
AUTORELEASEPOOL
@@ -290,13 +318,14 @@ Result DeviceImpl::createAccelerationStructure(
}
Result DeviceImpl::getTextureAllocationInfo(
- const ITextureResource::Desc& descIn, Size* outSize, Size* outAlignment)
+ const ITextureResource::Desc& descIn,
+ Size* outSize,
+ Size* outAlignment)
{
AUTORELEASEPOOL
- auto alignTo = [&](Size size, Size alignment) -> Size {
- return ((size + alignment - 1) / alignment) * alignment;
- };
+ auto alignTo = [&](Size size, Size alignment) -> Size
+ { return ((size + alignment - 1) / alignment) * alignment; };
TextureResource::Desc desc = fixupTextureDesc(descIn);
FormatInfo formatInfo;
@@ -311,7 +340,8 @@ Result DeviceImpl::getTextureAllocationInfo(
for (Int i = 0; i < desc.numMipLevels; ++i)
{
- Size rowSize = ((extents.width + formatInfo.blockWidth - 1) / formatInfo.blockWidth) * formatInfo.blockSizeInBytes;
+ Size rowSize = ((extents.width + formatInfo.blockWidth - 1) / formatInfo.blockWidth) *
+ formatInfo.blockSizeInBytes;
rowSize = alignTo(rowSize, alignment);
Size sliceSize = rowSize * alignTo(extents.height, formatInfo.blockHeight);
size += sliceSize * extents.depth;
@@ -358,19 +388,16 @@ Result DeviceImpl::createTextureResource(
RefPtr<TextureResourceImpl> textureImpl(new TextureResourceImpl(desc, this));
- NS::SharedPtr<MTL::TextureDescriptor> textureDesc = NS::TransferPtr(MTL::TextureDescriptor::alloc()->init());
+ NS::SharedPtr<MTL::TextureDescriptor> textureDesc =
+ NS::TransferPtr(MTL::TextureDescriptor::alloc()->init());
switch (desc.memoryType)
{
- case MemoryType::DeviceLocal:
- textureDesc->setStorageMode(MTL::StorageModePrivate);
- break;
+ case MemoryType::DeviceLocal: textureDesc->setStorageMode(MTL::StorageModePrivate); break;
case MemoryType::Upload:
textureDesc->setStorageMode(MTL::StorageModeShared);
textureDesc->setCpuCacheMode(MTL::CPUCacheModeWriteCombined);
break;
- case MemoryType::ReadBack:
- textureDesc->setStorageMode(MTL::StorageModeShared);
- break;
+ case MemoryType::ReadBack: textureDesc->setStorageMode(MTL::StorageModeShared); break;
}
bool isArray = desc.arraySize > 0;
@@ -384,7 +411,8 @@ Result DeviceImpl::createTextureResource(
case IResource::Type::Texture2D:
if (desc.sampleDesc.numSamples > 1)
{
- textureDesc->setTextureType(isArray ? MTL::TextureType2DMultisampleArray : MTL::TextureType2DMultisample);
+ textureDesc->setTextureType(
+ isArray ? MTL::TextureType2DMultisampleArray : MTL::TextureType2DMultisample);
textureDesc->setSampleCount(desc.sampleDesc.numSamples);
}
else
@@ -405,9 +433,7 @@ Result DeviceImpl::createTextureResource(
textureDesc->setHeight(descIn.size.height);
textureDesc->setDepth(descIn.size.depth);
break;
- default:
- assert("!Unsupported texture type");
- return SLANG_FAIL;
+ default: assert("!Unsupported texture type"); return SLANG_FAIL;
}
MTL::TextureUsage textureUsage = MTL::TextureUsageUnknown;
@@ -430,9 +456,7 @@ Result DeviceImpl::createTextureResource(
case Format::R32_UINT:
case Format::R32_SINT:
case Format::R32G32_UINT:
- case Format::R32G32_SINT:
- textureUsage |= MTL::TextureUsageShaderAtomic;
- break;
+ case Format::R32G32_SINT: textureUsage |= MTL::TextureUsageShaderAtomic; break;
}
}
@@ -456,7 +480,8 @@ Result DeviceImpl::createTextureResource(
{
textureDesc->setStorageMode(MTL::StorageModeManaged);
textureDesc->setCpuCacheMode(MTL::CPUCacheModeDefaultCache);
- NS::SharedPtr<MTL::Texture> stagingTexture = NS::TransferPtr(m_device->newTexture(textureDesc.get()));
+ NS::SharedPtr<MTL::Texture> stagingTexture =
+ NS::TransferPtr(m_device->newTexture(textureDesc.get()));
MTL::CommandBuffer* commandBuffer = m_commandQueue->commandBuffer();
MTL::BlitCommandEncoder* encoder = commandBuffer->blitCommandEncoder();
@@ -480,12 +505,22 @@ Result DeviceImpl::createTextureResource(
{
if (level >= desc.numMipLevels)
continue;
- const ITextureResource::SubresourceData& subresourceData = initData[slice * initMipLevels + level];
- stagingTexture->replaceRegion(region, level, slice, subresourceData.data, subresourceData.strideY, subresourceData.strideZ);
+ const ITextureResource::SubresourceData& subresourceData =
+ initData[slice * initMipLevels + level];
+ stagingTexture->replaceRegion(
+ region,
+ level,
+ slice,
+ subresourceData.data,
+ subresourceData.strideY,
+ subresourceData.strideZ);
encoder->synchronizeTexture(stagingTexture.get(), slice, level);
- region.size.width = region.size.width > 0 ? Math::Max(1ul, region.size.width >> 1) : 0;
- region.size.height = region.size.height > 0 ? Math::Max(1ul, region.size.height >> 1) : 0;
- region.size.depth = region.size.depth > 0 ? Math::Max(1ul, region.size.depth >> 1) : 0;
+ region.size.width =
+ region.size.width > 0 ? Math::Max(1ul, region.size.width >> 1) : 0;
+ region.size.height =
+ region.size.height > 0 ? Math::Max(1ul, region.size.height >> 1) : 0;
+ region.size.depth =
+ region.size.depth > 0 ? Math::Max(1ul, region.size.depth >> 1) : 0;
}
}
@@ -500,7 +535,9 @@ Result DeviceImpl::createTextureResource(
}
Result DeviceImpl::createBufferResource(
- const IBufferResource::Desc& descIn, const void* initData, IBufferResource** outResource)
+ const IBufferResource::Desc& descIn,
+ const void* initData,
+ IBufferResource** outResource)
{
AUTORELEASEPOOL
@@ -511,17 +548,15 @@ Result DeviceImpl::createBufferResource(
MTL::ResourceOptions resourceOptions = MTL::ResourceOptions(0);
switch (desc.memoryType)
{
- case MemoryType::DeviceLocal:
- resourceOptions = MTL::ResourceStorageModePrivate;
- break;
+ case MemoryType::DeviceLocal: resourceOptions = MTL::ResourceStorageModePrivate; break;
case MemoryType::Upload:
resourceOptions = MTL::ResourceStorageModeShared | MTL::CPUCacheModeWriteCombined;
break;
- case MemoryType::ReadBack:
- resourceOptions = MTL::ResourceStorageModeShared;
- break;
+ case MemoryType::ReadBack: resourceOptions = MTL::ResourceStorageModeShared; break;
}
- resourceOptions |= (desc.memoryType == MemoryType::DeviceLocal) ? MTL::ResourceStorageModePrivate : MTL::ResourceStorageModeShared;
+ resourceOptions |= (desc.memoryType == MemoryType::DeviceLocal)
+ ? MTL::ResourceStorageModePrivate
+ : MTL::ResourceStorageModeShared;
RefPtr<BufferResourceImpl> bufferImpl(new BufferResourceImpl(desc, this));
bufferImpl->m_buffer = NS::TransferPtr(m_device->newBuffer(bufferSize, resourceOptions));
@@ -533,7 +568,9 @@ Result DeviceImpl::createBufferResource(
if (initData)
{
NS::SharedPtr<MTL::Buffer> stagingBuffer = NS::TransferPtr(m_device->newBuffer(
- initData, bufferSize, MTL::ResourceStorageModeShared | MTL::CPUCacheModeWriteCombined));
+ initData,
+ bufferSize,
+ MTL::ResourceStorageModeShared | MTL::CPUCacheModeWriteCombined));
MTL::CommandBuffer* commandBuffer = m_commandQueue->commandBuffer();
MTL::BlitCommandEncoder* encoder = commandBuffer->blitCommandEncoder();
if (!stagingBuffer || !commandBuffer || !encoder)
@@ -551,7 +588,9 @@ Result DeviceImpl::createBufferResource(
}
Result DeviceImpl::createBufferFromNativeHandle(
- InteropHandle handle, const IBufferResource::Desc& srcDesc, IBufferResource** outResource)
+ InteropHandle handle,
+ const IBufferResource::Desc& srcDesc,
+ IBufferResource** outResource)
{
AUTORELEASEPOOL
@@ -569,7 +608,9 @@ Result DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerS
}
Result DeviceImpl::createTextureView(
- ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView)
+ ITextureResource* texture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView)
{
AUTORELEASEPOOL
@@ -586,7 +627,8 @@ Result DeviceImpl::createTextureView(
const ITextureResource::Desc& textureDesc = *textureImpl->getDesc();
SubresourceRange sr = desc.subresourceRange;
- sr.mipLevelCount = sr.mipLevelCount == 0 ? textureDesc.numMipLevels - sr.mipLevel : sr.mipLevelCount;
+ sr.mipLevelCount =
+ sr.mipLevelCount == 0 ? textureDesc.numMipLevels - sr.mipLevel : sr.mipLevelCount;
sr.layerCount = sr.layerCount == 0 ? textureDesc.arraySize - sr.baseArrayLayer : sr.layerCount;
if (sr.mipLevel == 0 && sr.mipLevelCount == textureDesc.numMipLevels &&
sr.baseArrayLayer == 0 && sr.layerCount == textureDesc.arraySize)
@@ -596,11 +638,17 @@ Result DeviceImpl::createTextureView(
return SLANG_OK;
}
- MTL::PixelFormat pixelFormat = desc.format == Format::Unknown ? textureImpl->m_pixelFormat : MetalUtil::translatePixelFormat(desc.format);
+ MTL::PixelFormat pixelFormat = desc.format == Format::Unknown
+ ? textureImpl->m_pixelFormat
+ : MetalUtil::translatePixelFormat(desc.format);
NS::Range levelRange(sr.baseArrayLayer, sr.layerCount);
NS::Range sliceRange(sr.mipLevel, sr.mipLevelCount);
- viewImpl->m_textureView = NS::TransferPtr(textureImpl->m_texture->newTextureView(pixelFormat, textureImpl->m_textureType, levelRange, sliceRange));
+ viewImpl->m_textureView = NS::TransferPtr(textureImpl->m_texture->newTextureView(
+ pixelFormat,
+ textureImpl->m_textureType,
+ levelRange,
+ sliceRange));
if (!viewImpl->m_textureView)
{
return SLANG_FAIL;
@@ -651,7 +699,8 @@ Result DeviceImpl::createBufferView(
return SLANG_FAIL;
}
- if (desc.type != IResourceView::Type::UnorderedAccess && desc.type != IResourceView::Type::ShaderResource)
+ if (desc.type != IResourceView::Type::UnorderedAccess &&
+ desc.type != IResourceView::Type::ShaderResource)
{
return SLANG_FAIL;
}
@@ -662,7 +711,8 @@ Result DeviceImpl::createBufferView(
viewImpl->m_desc = desc;
viewImpl->m_buffer = bufferImpl;
viewImpl->m_offset = desc.bufferRange.offset;
- viewImpl->m_size = desc.bufferRange.size == 0 ? bufferImpl->getDesc()->sizeInBytes : desc.bufferRange.size;
+ viewImpl->m_size =
+ desc.bufferRange.size == 0 ? bufferImpl->getDesc()->sizeInBytes : desc.bufferRange.size;
returnComPtr(outView, viewImpl);
return SLANG_OK;
}
@@ -678,7 +728,9 @@ Result DeviceImpl::createInputLayout(IInputLayout::Desc const& desc, IInputLayou
}
Result DeviceImpl::createProgram(
- const IShaderProgram::Desc& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnosticBlob)
+ const IShaderProgram::Desc& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnosticBlob)
{
AUTORELEASEPOOL
@@ -708,8 +760,8 @@ Result DeviceImpl::createShaderObjectLayout(
AUTORELEASEPOOL
RefPtr<ShaderObjectLayoutImpl> layout;
- SLANG_RETURN_ON_FAIL(ShaderObjectLayoutImpl::createForElementType(
- this, session, typeLayout, layout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ ShaderObjectLayoutImpl::createForElementType(this, session, typeLayout, layout.writeRef()));
returnRefPtrMove(outLayout, layout);
return SLANG_OK;
}
@@ -719,14 +771,17 @@ Result DeviceImpl::createShaderObject(ShaderObjectLayoutBase* layout, IShaderObj
AUTORELEASEPOOL
RefPtr<ShaderObjectImpl> shaderObject;
- SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(this,
- static_cast<ShaderObjectLayoutImpl*>(layout), shaderObject.writeRef()));
+ SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(
+ this,
+ static_cast<ShaderObjectLayoutImpl*>(layout),
+ shaderObject.writeRef()));
returnComPtr(outObject, shaderObject);
return SLANG_OK;
}
Result DeviceImpl::createMutableShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject)
{
AUTORELEASEPOOL
@@ -747,7 +802,9 @@ Result DeviceImpl::createShaderTable(const IShaderTable::Desc& desc, IShaderTabl
return SLANG_E_NOT_IMPLEMENTED;
}
-Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc& desc, IPipelineState** outState)
+Result DeviceImpl::createGraphicsPipelineState(
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState)
{
AUTORELEASEPOOL
@@ -757,7 +814,9 @@ Result DeviceImpl::createGraphicsPipelineState(const GraphicsPipelineStateDesc&
return SLANG_OK;
}
-Result DeviceImpl::createComputePipelineState(const ComputePipelineStateDesc& desc, IPipelineState** outState)
+Result DeviceImpl::createComputePipelineState(
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState)
{
AUTORELEASEPOOL
@@ -768,7 +827,9 @@ Result DeviceImpl::createComputePipelineState(const ComputePipelineStateDesc& de
return SLANG_OK;
}
-Result DeviceImpl::createRayTracingPipelineState(const RayTracingPipelineStateDesc& desc, IPipelineState** outState)
+Result DeviceImpl::createRayTracingPipelineState(
+ const RayTracingPipelineStateDesc& desc,
+ IPipelineState** outState)
{
AUTORELEASEPOOL
@@ -796,7 +857,11 @@ Result DeviceImpl::createFence(const IFence::Desc& desc, IFence** outFence)
}
Result DeviceImpl::waitForFences(
- GfxCount fenceCount, IFence** fences, uint64_t* fenceValues, bool waitForAll, uint64_t timeout)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* fenceValues,
+ bool waitForAll,
+ uint64_t timeout)
{
return SLANG_E_NOT_IMPLEMENTED;
}
diff --git a/tools/gfx/metal/metal-device.h b/tools/gfx/metal/metal-device.h
index 50eb0e88d..b22066f61 100644
--- a/tools/gfx/metal/metal-device.h
+++ b/tools/gfx/metal/metal-device.h
@@ -1,9 +1,9 @@
// metal-device.h
#pragma once
+#include "../simple-transient-resource-heap.h"
#include "metal-base.h"
#include "metal-device.h"
-#include "../simple-transient-resource-heap.h"
#include "metal-framebuffer.h"
namespace gfx
@@ -11,7 +11,7 @@ namespace gfx
using namespace Slang;
-namespace metal
+namespace metal
{
class DeviceImpl : public RendererBase
@@ -20,19 +20,24 @@ public:
// Renderer implementation
virtual SLANG_NO_THROW Result SLANG_MCALL initialize(const Desc& desc) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
+ getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTransientResourceHeap(
- const ITransientResourceHeap::Desc& desc, ITransientResourceHeap** outHeap) override;
+ const ITransientResourceHeap::Desc& desc,
+ ITransientResourceHeap** outHeap) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
+ createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain) override;
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout) override;
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
+ createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createRenderPassLayout(
- const IRenderPassLayout::Desc& desc, IRenderPassLayout** outRenderPassLayout) override;
+ const IRenderPassLayout::Desc& desc,
+ IRenderPassLayout** outRenderPassLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureResource(
const ITextureResource::Desc& desc,
const ITextureResource::SubresourceData* initData,
@@ -46,7 +51,7 @@ public:
const IBufferResource::Desc& srcDesc,
IBufferResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
+ createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
ITextureResource* texture,
@@ -59,33 +64,37 @@ public:
IResourceView** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
+ createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
virtual Result createShaderObjectLayout(
slang::ISession* session,
slang::TypeLayoutReflection* typeLayout,
ShaderObjectLayoutBase** outLayout) override;
- virtual Result createShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
+ virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ override;
virtual Result createMutableShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
+ createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outShaderTable) override;
+ createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outShaderTable) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createProgram(
const IShaderProgram::Desc& desc,
IShaderProgram** outProgram,
ISlangBlob** outDiagnosticBlob) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& desc, IPipelineState** outState) override;
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState) override;
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createRayTracingPipelineState(
- const RayTracingPipelineStateDesc& desc, IPipelineState** outState) override;
+ const RayTracingPipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool) override;
+ createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool) override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL readTextureResource(
ITextureResource* texture,
@@ -95,22 +104,28 @@ public:
Size* outPixelSize) override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL readBufferResource(
- IBufferResource* buffer, Offset offset, Size size, ISlangBlob** outBlob) override;
+ IBufferResource* buffer,
+ Offset offset,
+ Size size,
+ ISlangBlob** outBlob) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getAccelerationStructurePrebuildInfo(
const IAccelerationStructure::BuildInputs& buildInputs,
IAccelerationStructure::PrebuildInfo* outPrebuildInfo) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createAccelerationStructure(
- const IAccelerationStructure::CreateDesc& desc, IAccelerationStructure** outView) override;
+ const IAccelerationStructure::CreateDesc& desc,
+ IAccelerationStructure** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureAllocationInfo(
- const ITextureResource::Desc& desc, Size* outSize, Size* outAlignment) override;
+ const ITextureResource::Desc& desc,
+ Size* outSize,
+ Size* outAlignment) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureRowAlignment(Size* outAlignment) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFence(const IFence::Desc& desc, IFence** outFence) override;
+ createFence(const IFence::Desc& desc, IFence** outFence) override;
virtual SLANG_NO_THROW Result SLANG_MCALL waitForFences(
GfxCount fenceCount,
@@ -119,10 +134,10 @@ public:
bool waitForAll,
uint64_t timeout) override;
- //void waitForGpu();
+ // void waitForGpu();
virtual SLANG_NO_THROW const DeviceInfo& SLANG_MCALL getDeviceInfo() const override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeDeviceHandles(InteropHandles* outHandles) override;
+ getNativeDeviceHandles(InteropHandles* outHandles) override;
~DeviceImpl();
public:
diff --git a/tools/gfx/metal/metal-fence.cpp b/tools/gfx/metal/metal-fence.cpp
index a908a8493..0de7d8ffb 100644
--- a/tools/gfx/metal/metal-fence.cpp
+++ b/tools/gfx/metal/metal-fence.cpp
@@ -1,5 +1,6 @@
// metal-fence.cpp
#include "metal-fence.h"
+
#include "metal-device.h"
namespace gfx
@@ -10,9 +11,7 @@ using namespace Slang;
namespace metal
{
-FenceImpl::~FenceImpl()
-{
-}
+FenceImpl::~FenceImpl() {}
Result FenceImpl::init(DeviceImpl* device, const IFence::Desc& desc)
{
diff --git a/tools/gfx/metal/metal-fence.h b/tools/gfx/metal/metal-fence.h
index d8aed7dfe..434f2f65d 100644
--- a/tools/gfx/metal/metal-fence.h
+++ b/tools/gfx/metal/metal-fence.h
@@ -24,11 +24,12 @@ public:
virtual SLANG_NO_THROW Result SLANG_MCALL getCurrentValue(uint64_t* outValue) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setCurrentValue(uint64_t value) override;
-
+
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outNativeHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeHandle(InteropHandle* outNativeHandle) override;
};
-} // namespace metal
+} // namespace metal
} // namespace gfx
diff --git a/tools/gfx/metal/metal-framebuffer.cpp b/tools/gfx/metal/metal-framebuffer.cpp
index 76e944b4a..e7d04a63a 100644
--- a/tools/gfx/metal/metal-framebuffer.cpp
+++ b/tools/gfx/metal/metal-framebuffer.cpp
@@ -1,8 +1,9 @@
// metal-framebuffer.cpp
#include "metal-framebuffer.h"
+
#include "metal-device.h"
-#include "metal-resource-views.h"
#include "metal-helper-functions.h"
+#include "metal-resource-views.h"
namespace gfx
{
@@ -39,7 +40,7 @@ Result FramebufferImpl::init(DeviceImpl* device, const IFramebuffer::Desc& desc)
m_renderTargetViews[i] = static_cast<TextureResourceViewImpl*>(desc.renderTargetViews[i]);
}
m_depthStencilView = static_cast<TextureResourceViewImpl*>(desc.depthStencilView);
-
+
// Determine framebuffer dimensions & sample count;
m_width = 1;
m_height = 1;
@@ -49,8 +50,11 @@ Result FramebufferImpl::init(DeviceImpl* device, const IFramebuffer::Desc& desc)
{
const ITextureResource::Desc* textureDesc = view->m_texture->getDesc();
const IResourceView::Desc* viewDesc = view->getViewDesc();
- m_width = Math::Max(1u, uint32_t(textureDesc->size.width >> viewDesc->subresourceRange.mipLevel));
- m_height = Math::Max(1u, uint32_t(textureDesc->size.height >> viewDesc->subresourceRange.mipLevel));
+ m_width =
+ Math::Max(1u, uint32_t(textureDesc->size.width >> viewDesc->subresourceRange.mipLevel));
+ m_height = Math::Max(
+ 1u,
+ uint32_t(textureDesc->size.height >> viewDesc->subresourceRange.mipLevel));
m_sampleCount = Math::Max(m_sampleCount, uint32_t(textureDesc->sampleDesc.numSamples));
return SLANG_OK;
};
diff --git a/tools/gfx/metal/metal-helper-functions.cpp b/tools/gfx/metal/metal-helper-functions.cpp
index 69c4327ad..dc528f8ce 100644
--- a/tools/gfx/metal/metal-helper-functions.cpp
+++ b/tools/gfx/metal/metal-helper-functions.cpp
@@ -1,5 +1,6 @@
// metal-helper-functions.cpp
#include "metal-helper-functions.h"
+
#include "metal-device.h"
#include "metal-util.h"
diff --git a/tools/gfx/metal/metal-pipeline-state.cpp b/tools/gfx/metal/metal-pipeline-state.cpp
index d8ca3f793..c2a9afaac 100644
--- a/tools/gfx/metal/metal-pipeline-state.cpp
+++ b/tools/gfx/metal/metal-pipeline-state.cpp
@@ -2,10 +2,10 @@
#include "metal-pipeline-state.h"
#include "metal-device.h"
-#include "metal-shader-program.h"
#include "metal-shader-object-layout.h"
-#include "metal-vertex-layout.h"
+#include "metal-shader-program.h"
#include "metal-util.h"
+#include "metal-vertex-layout.h"
namespace gfx
{
@@ -20,9 +20,7 @@ PipelineStateImpl::PipelineStateImpl(DeviceImpl* device)
{
}
-PipelineStateImpl::~PipelineStateImpl()
-{
-}
+PipelineStateImpl::~PipelineStateImpl() {}
void PipelineStateImpl::init(const GraphicsPipelineStateDesc& desc)
{
@@ -54,25 +52,22 @@ Result PipelineStateImpl::createMetalRenderPipelineState()
if (!programImpl)
return SLANG_FAIL;
- NS::SharedPtr<MTL::RenderPipelineDescriptor> pd = NS::TransferPtr(MTL::RenderPipelineDescriptor::alloc()->init());
+ NS::SharedPtr<MTL::RenderPipelineDescriptor> pd =
+ NS::TransferPtr(MTL::RenderPipelineDescriptor::alloc()->init());
for (const ShaderProgramImpl::Module& module : programImpl->m_modules)
{
auto functionName = MetalUtil::createString(module.entryPointName.getBuffer());
- NS::SharedPtr<MTL::Function> function = NS::TransferPtr(module.library->newFunction(functionName.get()));
+ NS::SharedPtr<MTL::Function> function =
+ NS::TransferPtr(module.library->newFunction(functionName.get()));
if (!function)
return SLANG_FAIL;
switch (module.stage)
{
- case SLANG_STAGE_VERTEX:
- pd->setVertexFunction(function.get());
- break;
- case SLANG_STAGE_FRAGMENT:
- pd->setFragmentFunction(function.get());
- break;
- default:
- return SLANG_FAIL;
+ case SLANG_STAGE_VERTEX: pd->setVertexFunction(function.get()); break;
+ case SLANG_STAGE_FRAGMENT: pd->setFragmentFunction(function.get()); break;
+ default: return SLANG_FAIL;
}
}
@@ -81,12 +76,15 @@ Result PipelineStateImpl::createMetalRenderPipelineState()
// The +1 is to account for a potential constant buffer at index 0.
m_vertexBufferOffset = programImpl->m_rootObjectLayout->getBufferCount() + 1;
auto inputLayoutImpl = static_cast<InputLayoutImpl*>(desc.graphics.inputLayout);
- NS::SharedPtr<MTL::VertexDescriptor> vertexDescriptor = inputLayoutImpl->createVertexDescriptor(m_vertexBufferOffset);
+ NS::SharedPtr<MTL::VertexDescriptor> vertexDescriptor =
+ inputLayoutImpl->createVertexDescriptor(m_vertexBufferOffset);
pd->setVertexDescriptor(vertexDescriptor.get());
- pd->setInputPrimitiveTopology(MetalUtil::translatePrimitiveTopologyClass(desc.graphics.primitiveType));
+ pd->setInputPrimitiveTopology(
+ MetalUtil::translatePrimitiveTopologyClass(desc.graphics.primitiveType));
// Set rasterization state
- auto framebufferLayoutImpl = static_cast<FramebufferLayoutImpl*>(desc.graphics.framebufferLayout);
+ auto framebufferLayoutImpl =
+ static_cast<FramebufferLayoutImpl*>(desc.graphics.framebufferLayout);
const auto& blend = desc.graphics.blend;
GfxCount sampleCount = 1;
@@ -96,26 +94,36 @@ Result PipelineStateImpl::createMetalRenderPipelineState()
for (Index i = 0; i < framebufferLayoutImpl->m_renderTargets.getCount(); ++i)
{
- const IFramebufferLayout::TargetLayout& targetLayout = framebufferLayoutImpl->m_renderTargets[i];
- MTL::RenderPipelineColorAttachmentDescriptor* colorAttachment = pd->colorAttachments()->object(i);
+ const IFramebufferLayout::TargetLayout& targetLayout =
+ framebufferLayoutImpl->m_renderTargets[i];
+ MTL::RenderPipelineColorAttachmentDescriptor* colorAttachment =
+ pd->colorAttachments()->object(i);
colorAttachment->setPixelFormat(MetalUtil::translatePixelFormat(targetLayout.format));
if (i < blend.targetCount)
{
const TargetBlendDesc& targetBlendDesc = blend.targets[i];
colorAttachment->setBlendingEnabled(targetBlendDesc.enableBlend);
- colorAttachment->setSourceRGBBlendFactor(MetalUtil::translateBlendFactor(targetBlendDesc.color.srcFactor));
- colorAttachment->setDestinationRGBBlendFactor(MetalUtil::translateBlendFactor(targetBlendDesc.color.dstFactor));
- colorAttachment->setRgbBlendOperation(MetalUtil::translateBlendOperation(targetBlendDesc.color.op));
- colorAttachment->setSourceAlphaBlendFactor(MetalUtil::translateBlendFactor(targetBlendDesc.alpha.srcFactor));
- colorAttachment->setDestinationAlphaBlendFactor(MetalUtil::translateBlendFactor(targetBlendDesc.alpha.dstFactor));
- colorAttachment->setAlphaBlendOperation(MetalUtil::translateBlendOperation(targetBlendDesc.alpha.op));
- colorAttachment->setWriteMask(MetalUtil::translateColorWriteMask(targetBlendDesc.writeMask));
+ colorAttachment->setSourceRGBBlendFactor(
+ MetalUtil::translateBlendFactor(targetBlendDesc.color.srcFactor));
+ colorAttachment->setDestinationRGBBlendFactor(
+ MetalUtil::translateBlendFactor(targetBlendDesc.color.dstFactor));
+ colorAttachment->setRgbBlendOperation(
+ MetalUtil::translateBlendOperation(targetBlendDesc.color.op));
+ colorAttachment->setSourceAlphaBlendFactor(
+ MetalUtil::translateBlendFactor(targetBlendDesc.alpha.srcFactor));
+ colorAttachment->setDestinationAlphaBlendFactor(
+ MetalUtil::translateBlendFactor(targetBlendDesc.alpha.dstFactor));
+ colorAttachment->setAlphaBlendOperation(
+ MetalUtil::translateBlendOperation(targetBlendDesc.alpha.op));
+ colorAttachment->setWriteMask(
+ MetalUtil::translateColorWriteMask(targetBlendDesc.writeMask));
}
sampleCount = Math::Max(sampleCount, targetLayout.sampleCount);
}
if (framebufferLayoutImpl->m_depthStencil.format != Format::Unknown)
{
- const IFramebufferLayout::TargetLayout& depthStencil = framebufferLayoutImpl->m_depthStencil;
+ const IFramebufferLayout::TargetLayout& depthStencil =
+ framebufferLayoutImpl->m_depthStencil;
MTL::PixelFormat pixelFormat = MetalUtil::translatePixelFormat(depthStencil.format);
if (MetalUtil::isDepthFormat(pixelFormat))
{
@@ -123,14 +131,16 @@ Result PipelineStateImpl::createMetalRenderPipelineState()
}
if (MetalUtil::isStencilFormat(pixelFormat))
{
- pd->setStencilAttachmentPixelFormat(MetalUtil::translatePixelFormat(depthStencil.format));
+ pd->setStencilAttachmentPixelFormat(
+ MetalUtil::translatePixelFormat(depthStencil.format));
}
}
pd->setRasterSampleCount(sampleCount);
-
+
NS::Error* error;
- m_renderPipelineState = NS::TransferPtr(m_device->m_device->newRenderPipelineState(pd.get(), &error));
+ m_renderPipelineState =
+ NS::TransferPtr(m_device->m_device->newRenderPipelineState(pd.get(), &error));
if (!m_renderPipelineState)
{
std::cout << error->localizedDescription()->utf8String() << std::endl;
@@ -138,34 +148,52 @@ Result PipelineStateImpl::createMetalRenderPipelineState()
}
// Create depth stencil state
- auto createStencilDesc = [](const DepthStencilOpDesc& desc, uint32_t readMask, uint32_t writeMask) -> NS::SharedPtr<MTL::StencilDescriptor>
+ auto createStencilDesc = [](const DepthStencilOpDesc& desc,
+ uint32_t readMask,
+ uint32_t writeMask) -> NS::SharedPtr<MTL::StencilDescriptor>
{
- NS::SharedPtr<MTL::StencilDescriptor> stencilDesc = NS::TransferPtr(MTL::StencilDescriptor::alloc()->init());
- stencilDesc->setStencilCompareFunction(MetalUtil::translateCompareFunction(desc.stencilFunc));
- stencilDesc->setStencilFailureOperation(MetalUtil::translateStencilOperation(desc.stencilFailOp));
- stencilDesc->setDepthFailureOperation(MetalUtil::translateStencilOperation(desc.stencilDepthFailOp));
- stencilDesc->setDepthStencilPassOperation(MetalUtil::translateStencilOperation(desc.stencilPassOp));
+ NS::SharedPtr<MTL::StencilDescriptor> stencilDesc =
+ NS::TransferPtr(MTL::StencilDescriptor::alloc()->init());
+ stencilDesc->setStencilCompareFunction(
+ MetalUtil::translateCompareFunction(desc.stencilFunc));
+ stencilDesc->setStencilFailureOperation(
+ MetalUtil::translateStencilOperation(desc.stencilFailOp));
+ stencilDesc->setDepthFailureOperation(
+ MetalUtil::translateStencilOperation(desc.stencilDepthFailOp));
+ stencilDesc->setDepthStencilPassOperation(
+ MetalUtil::translateStencilOperation(desc.stencilPassOp));
stencilDesc->setReadMask(readMask);
stencilDesc->setWriteMask(writeMask);
return stencilDesc;
};
const auto& depthStencil = desc.graphics.depthStencil;
- NS::SharedPtr<MTL::DepthStencilDescriptor> depthStencilDesc = NS::TransferPtr(MTL::DepthStencilDescriptor::alloc()->init());
- m_depthStencilState = NS::TransferPtr(m_device->m_device->newDepthStencilState(depthStencilDesc.get()));
+ NS::SharedPtr<MTL::DepthStencilDescriptor> depthStencilDesc =
+ NS::TransferPtr(MTL::DepthStencilDescriptor::alloc()->init());
+ m_depthStencilState =
+ NS::TransferPtr(m_device->m_device->newDepthStencilState(depthStencilDesc.get()));
if (!m_depthStencilState)
{
return SLANG_FAIL;
}
if (depthStencil.depthTestEnable)
{
- depthStencilDesc->setDepthCompareFunction(MetalUtil::translateCompareFunction(depthStencil.depthFunc));
+ depthStencilDesc->setDepthCompareFunction(
+ MetalUtil::translateCompareFunction(depthStencil.depthFunc));
}
depthStencilDesc->setDepthWriteEnabled(depthStencil.depthWriteEnable);
if (depthStencil.stencilEnable)
{
- depthStencilDesc->setFrontFaceStencil(createStencilDesc(depthStencil.frontFace, depthStencil.stencilReadMask, depthStencil.stencilWriteMask).get());
- depthStencilDesc->setBackFaceStencil(createStencilDesc(depthStencil.backFace, depthStencil.stencilReadMask, depthStencil.stencilWriteMask).get());
+ depthStencilDesc->setFrontFaceStencil(createStencilDesc(
+ depthStencil.frontFace,
+ depthStencil.stencilReadMask,
+ depthStencil.stencilWriteMask)
+ .get());
+ depthStencilDesc->setBackFaceStencil(createStencilDesc(
+ depthStencil.backFace,
+ depthStencil.stencilReadMask,
+ depthStencil.stencilWriteMask)
+ .get());
}
return SLANG_OK;
@@ -179,16 +207,20 @@ Result PipelineStateImpl::createMetalComputePipelineState()
const ShaderProgramImpl::Module& module = programImpl->m_modules[0];
auto functionName = MetalUtil::createString(module.entryPointName.getBuffer());
- NS::SharedPtr<MTL::Function> function = NS::TransferPtr(module.library->newFunction(functionName.get()));
+ NS::SharedPtr<MTL::Function> function =
+ NS::TransferPtr(module.library->newFunction(functionName.get()));
if (!function)
return SLANG_FAIL;
- NS::Error *error;
- m_computePipelineState = NS::TransferPtr(m_device->m_device->newComputePipelineState(function.get(), &error));
+ NS::Error* error;
+ m_computePipelineState =
+ NS::TransferPtr(m_device->m_device->newComputePipelineState(function.get(), &error));
// Query thread group size for use during dispatch.
SlangUInt threadGroupSize[3];
- programImpl->linkedProgram->getLayout()->getEntryPointByIndex(0)->getComputeThreadGroupSize(3, threadGroupSize);
+ programImpl->linkedProgram->getLayout()->getEntryPointByIndex(0)->getComputeThreadGroupSize(
+ 3,
+ threadGroupSize);
m_threadGroupSize = MTL::Size(threadGroupSize[0], threadGroupSize[1], threadGroupSize[2]);
return m_computePipelineState ? SLANG_OK : SLANG_FAIL;
@@ -197,16 +229,14 @@ Result PipelineStateImpl::createMetalComputePipelineState()
Result PipelineStateImpl::ensureAPIPipelineStateCreated()
{
AUTORELEASEPOOL
-
+
switch (desc.type)
{
case PipelineType::Compute:
return m_computePipelineState ? SLANG_OK : createMetalComputePipelineState();
case PipelineType::Graphics:
return m_renderPipelineState ? SLANG_OK : createMetalRenderPipelineState();
- default:
- SLANG_UNREACHABLE("Unknown pipeline type.");
- return SLANG_FAIL;
+ default: SLANG_UNREACHABLE("Unknown pipeline type."); return SLANG_FAIL;
}
return SLANG_OK;
}
@@ -229,7 +259,8 @@ SLANG_NO_THROW Result SLANG_MCALL PipelineStateImpl::getNativeHandle(InteropHand
RayTracingPipelineStateImpl::RayTracingPipelineStateImpl(DeviceImpl* device)
: PipelineStateImpl(device)
-{}
+{
+}
Result RayTracingPipelineStateImpl::ensureAPIPipelineStateCreated()
{
@@ -242,6 +273,5 @@ Result RayTracingPipelineStateImpl::getNativeHandle(InteropHandle* outHandle)
}
-
} // namespace metal
} // namespace gfx
diff --git a/tools/gfx/metal/metal-query.cpp b/tools/gfx/metal/metal-query.cpp
index 4e1d09d77..6075d5549 100644
--- a/tools/gfx/metal/metal-query.cpp
+++ b/tools/gfx/metal/metal-query.cpp
@@ -1,7 +1,7 @@
// metal-query.cpp
#include "metal-query.h"
-//#include "metal-util.h"
+// #include "metal-util.h"
namespace gfx
{
@@ -11,9 +11,7 @@ using namespace Slang;
namespace metal
{
-QueryPoolImpl::~QueryPoolImpl()
-{
-}
+QueryPoolImpl::~QueryPoolImpl() {}
static MTL::CounterSet* findCounterSet(MTL::Device* device, QueryType queryType)
{
@@ -26,7 +24,8 @@ static MTL::CounterSet* findCounterSet(MTL::Device* device, QueryType queryType)
for (int i = 0; i < device->counterSets()->count(); ++i)
{
- MTL::CounterSet* counterSet = static_cast<MTL::CounterSet*>(device->counterSets()->object(i));
+ MTL::CounterSet* counterSet =
+ static_cast<MTL::CounterSet*>(device->counterSets()->object(i));
for (int j = 0; j < counterSet->counters()->count(); ++j)
{
MTL::Counter* counter = static_cast<MTL::Counter*>(counterSet->counters()->object(j));
@@ -50,7 +49,8 @@ Result QueryPoolImpl::init(DeviceImpl* device, const IQueryPool::Desc& desc)
return SLANG_E_NOT_AVAILABLE;
}
- NS::SharedPtr<MTL::CounterSampleBufferDescriptor> counterSampleBufferDesc = NS::TransferPtr(MTL::CounterSampleBufferDescriptor::alloc()->init());
+ NS::SharedPtr<MTL::CounterSampleBufferDescriptor> counterSampleBufferDesc =
+ NS::TransferPtr(MTL::CounterSampleBufferDescriptor::alloc()->init());
counterSampleBufferDesc->setStorageMode(MTL::StorageModeShared);
counterSampleBufferDesc->setSampleCount(m_desc.count);
counterSampleBufferDesc->setCounterSet(counterSet);
@@ -58,7 +58,8 @@ Result QueryPoolImpl::init(DeviceImpl* device, const IQueryPool::Desc& desc)
m_device->m_device->counterSets();
NS::Error* error;
- m_counterSampleBuffer = NS::TransferPtr(m_device->m_device->newCounterSampleBuffer(counterSampleBufferDesc.get(), &error));
+ m_counterSampleBuffer = NS::TransferPtr(
+ m_device->m_device->newCounterSampleBuffer(counterSampleBufferDesc.get(), &error));
return m_counterSampleBuffer ? SLANG_OK : SLANG_FAIL;
}
diff --git a/tools/gfx/metal/metal-query.h b/tools/gfx/metal/metal-query.h
index 3b3e28489..55dc9ebbe 100644
--- a/tools/gfx/metal/metal-query.h
+++ b/tools/gfx/metal/metal-query.h
@@ -23,8 +23,7 @@ public:
Result init(DeviceImpl* device, const IQueryPool::Desc& desc);
virtual SLANG_NO_THROW Result SLANG_MCALL
- getResult(GfxIndex index, GfxCount count, uint64_t* data) override;
-
+ getResult(GfxIndex index, GfxCount count, uint64_t* data) override;
};
} // namespace metal
diff --git a/tools/gfx/metal/metal-render-pass.cpp b/tools/gfx/metal/metal-render-pass.cpp
index bc60cf746..49e470028 100644
--- a/tools/gfx/metal/metal-render-pass.cpp
+++ b/tools/gfx/metal/metal-render-pass.cpp
@@ -1,7 +1,7 @@
// metal-render-pass.cpp
#include "metal-render-pass.h"
-//#include "metal-helper-functions.h"
+// #include "metal-helper-functions.h"
namespace gfx
{
@@ -22,14 +22,10 @@ static inline MTL::LoadAction translateLoadOp(IRenderPassLayout::TargetLoadOp lo
{
switch (loadOp)
{
- case IRenderPassLayout::TargetLoadOp::Load:
- return MTL::LoadActionLoad;
- case IRenderPassLayout::TargetLoadOp::Clear:
- return MTL::LoadActionClear;
- case IRenderPassLayout::TargetLoadOp::DontCare:
- return MTL::LoadActionDontCare;
- default:
- return MTL::LoadAction(0);
+ case IRenderPassLayout::TargetLoadOp::Load: return MTL::LoadActionLoad;
+ case IRenderPassLayout::TargetLoadOp::Clear: return MTL::LoadActionClear;
+ case IRenderPassLayout::TargetLoadOp::DontCare: return MTL::LoadActionDontCare;
+ default: return MTL::LoadAction(0);
}
}
@@ -37,12 +33,9 @@ static inline MTL::StoreAction translateStoreOp(IRenderPassLayout::TargetStoreOp
{
switch (storeOp)
{
- case IRenderPassLayout::TargetStoreOp::Store:
- return MTL::StoreActionStore;
- case IRenderPassLayout::TargetStoreOp::DontCare:
- return MTL::StoreActionDontCare;
- default:
- return MTL::StoreAction(0);
+ case IRenderPassLayout::TargetStoreOp::Store: return MTL::StoreActionStore;
+ case IRenderPassLayout::TargetStoreOp::DontCare: return MTL::StoreActionDontCare;
+ default: return MTL::StoreAction(0);
}
}
@@ -50,25 +43,32 @@ Result RenderPassLayoutImpl::init(DeviceImpl* device, const IRenderPassLayout::D
{
m_device = device;
- FramebufferLayoutImpl* framebufferLayout = static_cast<FramebufferLayoutImpl*>(desc.framebufferLayout);
+ FramebufferLayoutImpl* framebufferLayout =
+ static_cast<FramebufferLayoutImpl*>(desc.framebufferLayout);
assert(framebufferLayout);
- // Initialize render pass descriptor, filling in attachment metadata, but leaving texture data unbound.
+ // Initialize render pass descriptor, filling in attachment metadata, but leaving texture data
+ // unbound.
m_renderPassDesc = NS::TransferPtr(MTL::RenderPassDescriptor::alloc()->init());
m_renderPassDesc->setRenderTargetArrayLength(desc.renderTargetCount);
for (GfxIndex i = 0; i < desc.renderTargetCount; ++i)
{
- MTL::RenderPassColorAttachmentDescriptor* colorAttachment = m_renderPassDesc->colorAttachments()->object(i);
+ MTL::RenderPassColorAttachmentDescriptor* colorAttachment =
+ m_renderPassDesc->colorAttachments()->object(i);
colorAttachment->setLoadAction(translateLoadOp(desc.renderTargetAccess[i].loadOp));
colorAttachment->setStoreAction(translateStoreOp(desc.renderTargetAccess[i].storeOp));
}
- m_renderPassDesc->depthAttachment()->setLoadAction(translateLoadOp(desc.depthStencilAccess->loadOp));
- m_renderPassDesc->depthAttachment()->setStoreAction(translateStoreOp(desc.depthStencilAccess->storeOp));
+ m_renderPassDesc->depthAttachment()->setLoadAction(
+ translateLoadOp(desc.depthStencilAccess->loadOp));
+ m_renderPassDesc->depthAttachment()->setStoreAction(
+ translateStoreOp(desc.depthStencilAccess->storeOp));
- m_renderPassDesc->stencilAttachment()->setLoadAction(translateLoadOp(desc.depthStencilAccess->loadOp));
- m_renderPassDesc->stencilAttachment()->setStoreAction(translateStoreOp(desc.depthStencilAccess->storeOp));
+ m_renderPassDesc->stencilAttachment()->setLoadAction(
+ translateLoadOp(desc.depthStencilAccess->loadOp));
+ m_renderPassDesc->stencilAttachment()->setStoreAction(
+ translateStoreOp(desc.depthStencilAccess->storeOp));
return SLANG_OK;
}
diff --git a/tools/gfx/metal/metal-render-pass.h b/tools/gfx/metal/metal-render-pass.h
index ee66b0c4d..94659a561 100644
--- a/tools/gfx/metal/metal-render-pass.h
+++ b/tools/gfx/metal/metal-render-pass.h
@@ -12,9 +12,7 @@ using namespace Slang;
namespace metal
{
-class RenderPassLayoutImpl
- : public IRenderPassLayout
- , public ComObject
+class RenderPassLayoutImpl : public IRenderPassLayout, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
diff --git a/tools/gfx/metal/metal-resource-views.cpp b/tools/gfx/metal/metal-resource-views.cpp
index ea5c23c10..2f8a4b16e 100644
--- a/tools/gfx/metal/metal-resource-views.cpp
+++ b/tools/gfx/metal/metal-resource-views.cpp
@@ -9,9 +9,7 @@ using namespace Slang;
namespace metal
{
-TextureResourceViewImpl::~TextureResourceViewImpl()
-{
-}
+TextureResourceViewImpl::~TextureResourceViewImpl() {}
Result TextureResourceViewImpl::getNativeHandle(InteropHandle* outHandle)
{
@@ -20,9 +18,7 @@ Result TextureResourceViewImpl::getNativeHandle(InteropHandle* outHandle)
return SLANG_OK;
}
-BufferResourceViewImpl::~BufferResourceViewImpl()
-{
-}
+BufferResourceViewImpl::~BufferResourceViewImpl() {}
Result BufferResourceViewImpl::getNativeHandle(InteropHandle* outHandle)
{
@@ -33,12 +29,11 @@ Result BufferResourceViewImpl::getNativeHandle(InteropHandle* outHandle)
TexelBufferResourceViewImpl::TexelBufferResourceViewImpl(DeviceImpl* device)
: ResourceViewImpl(ViewType::TexelBuffer, device)
-{}
-
-TexelBufferResourceViewImpl::~TexelBufferResourceViewImpl()
{
}
+TexelBufferResourceViewImpl::~TexelBufferResourceViewImpl() {}
+
Result TexelBufferResourceViewImpl::getNativeHandle(InteropHandle* outHandle)
{
return SLANG_E_NOT_IMPLEMENTED;
@@ -54,9 +49,7 @@ Result AccelerationStructureImpl::getNativeHandle(InteropHandle* outHandle)
return SLANG_E_NOT_IMPLEMENTED;
}
-AccelerationStructureImpl::~AccelerationStructureImpl()
-{
-}
+AccelerationStructureImpl::~AccelerationStructureImpl() {}
} // namespace metal
} // namespace gfx
diff --git a/tools/gfx/metal/metal-resource-views.h b/tools/gfx/metal/metal-resource-views.h
index 89986f19d..ae494c2fb 100644
--- a/tools/gfx/metal/metal-resource-views.h
+++ b/tools/gfx/metal/metal-resource-views.h
@@ -26,9 +26,9 @@ public:
public:
ResourceViewImpl(ViewType viewType, DeviceImpl* device)
- : m_type(viewType)
- , m_device(device)
- {}
+ : m_type(viewType), m_device(device)
+ {
+ }
ViewType m_type;
RefPtr<DeviceImpl> m_device;
};
@@ -38,7 +38,8 @@ class TextureResourceViewImpl : public ResourceViewImpl
public:
TextureResourceViewImpl(DeviceImpl* device)
: ResourceViewImpl(ViewType::Texture, device)
- {}
+ {
+ }
~TextureResourceViewImpl();
RefPtr<TextureResourceImpl> m_texture;
NS::SharedPtr<MTL::Texture> m_textureView;
@@ -51,7 +52,8 @@ class BufferResourceViewImpl : public ResourceViewImpl
public:
BufferResourceViewImpl(DeviceImpl* device)
: ResourceViewImpl(ViewType::Buffer, device)
- {}
+ {
+ }
~BufferResourceViewImpl();
RefPtr<BufferResourceImpl> m_buffer;
Offset m_offset;
diff --git a/tools/gfx/metal/metal-sampler.cpp b/tools/gfx/metal/metal-sampler.cpp
index 561b93ea2..6f0c0e36b 100644
--- a/tools/gfx/metal/metal-sampler.cpp
+++ b/tools/gfx/metal/metal-sampler.cpp
@@ -1,5 +1,6 @@
// metal-sampler.cpp
#include "metal-sampler.h"
+
#include "metal-util.h"
namespace gfx
@@ -10,15 +11,14 @@ using namespace Slang;
namespace metal
{
-SamplerStateImpl::~SamplerStateImpl()
-{
-}
+SamplerStateImpl::~SamplerStateImpl() {}
Result SamplerStateImpl::init(DeviceImpl* device, const ISamplerState::Desc& desc)
{
m_device = device;
- NS::SharedPtr<MTL::SamplerDescriptor> samplerDesc = NS::TransferPtr(MTL::SamplerDescriptor::alloc()->init());
+ NS::SharedPtr<MTL::SamplerDescriptor> samplerDesc =
+ NS::TransferPtr(MTL::SamplerDescriptor::alloc()->init());
samplerDesc->setMinFilter(MetalUtil::translateSamplerMinMagFilter(desc.minFilter));
samplerDesc->setMagFilter(MetalUtil::translateSamplerMinMagFilter(desc.magFilter));
@@ -45,7 +45,7 @@ Result SamplerStateImpl::init(DeviceImpl* device, const ISamplerState::Desc& des
// TODO: no support for reduction op
m_samplerState = NS::TransferPtr(m_device->m_device->newSamplerState(samplerDesc.get()));
-
+
return m_samplerState ? SLANG_OK : SLANG_FAIL;
}
diff --git a/tools/gfx/metal/metal-sampler.h b/tools/gfx/metal/metal-sampler.h
index c7156cb2e..0d94a6d2d 100644
--- a/tools/gfx/metal/metal-sampler.h
+++ b/tools/gfx/metal/metal-sampler.h
@@ -21,7 +21,7 @@ public:
~SamplerStateImpl();
Result init(DeviceImpl* device, const ISamplerState::Desc& desc);
-
+
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outHandle) override;
};
diff --git a/tools/gfx/metal/metal-shader-object-layout.cpp b/tools/gfx/metal/metal-shader-object-layout.cpp
index 94bcb6db6..e674b830a 100644
--- a/tools/gfx/metal/metal-shader-object-layout.cpp
+++ b/tools/gfx/metal/metal-shader-object-layout.cpp
@@ -29,7 +29,8 @@ ShaderObjectLayoutImpl::SubObjectRangeStride::SubObjectRangeStride(
}
}
-Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutReflection* typeLayout)
+Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(
+ slang::TypeLayoutReflection* typeLayout)
{
typeLayout = _unwrapParameterGroups(typeLayout, m_containerType);
@@ -94,8 +95,7 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
m_textureCount += count;
m_textureRanges.add(r);
break;
- default:
- break;
+ default: break;
}
// We'd like to extract the information on the Metal resource
@@ -125,7 +125,9 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
SLANG_ASSERT(descriptorSetIndex == 0);
SlangInt descriptorRangeIndex = typeLayout->getBindingRangeFirstDescriptorRangeIndex(r);
- auto registerOffset = typeLayout->getDescriptorSetDescriptorRangeIndexOffset(descriptorSetIndex, descriptorRangeIndex);
+ auto registerOffset = typeLayout->getDescriptorSetDescriptorRangeIndexOffset(
+ descriptorSetIndex,
+ descriptorRangeIndex);
bindingRangeInfo.registerOffset = (uint32_t)registerOffset;
}
@@ -160,18 +162,18 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
switch (slangBindingType)
{
default:
- {
- // In the case of `ConstantBuffer<X>` or `ParameterBlock<X>`
- // we can construct a layout from the element type directly.
- //
- auto elementTypeLayout = slangLeafTypeLayout->getElementTypeLayout();
- createForElementType(
- m_renderer,
- m_session,
- elementTypeLayout,
- subObjectLayout.writeRef());
- }
- break;
+ {
+ // In the case of `ConstantBuffer<X>` or `ParameterBlock<X>`
+ // we can construct a layout from the element type directly.
+ //
+ auto elementTypeLayout = slangLeafTypeLayout->getElementTypeLayout();
+ createForElementType(
+ m_renderer,
+ m_session,
+ elementTypeLayout,
+ subObjectLayout.writeRef());
+ }
+ break;
case slang::BindingType::ExistentialValue:
// In the case of an interface-type sub-object range, we can only
// construct a layout if we have static specialization information
@@ -193,8 +195,9 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
// increase the size of the ordinary data buffer we need to
// allocate for the parent object.
//
- uint32_t ordinaryDataEnd = subObjectRange.offset.pendingOrdinaryData
- + (uint32_t)bindingRange.count * subObjectRange.stride.pendingOrdinaryData;
+ uint32_t ordinaryDataEnd =
+ subObjectRange.offset.pendingOrdinaryData +
+ (uint32_t)bindingRange.count * subObjectRange.stride.pendingOrdinaryData;
if (ordinaryDataEnd > m_totalOrdinaryDataSize)
{
@@ -211,8 +214,7 @@ Result ShaderObjectLayoutImpl::Builder::setElementTypeLayout(slang::TypeLayoutRe
SlangResult ShaderObjectLayoutImpl::Builder::build(ShaderObjectLayoutImpl** outLayout)
{
- auto layout =
- RefPtr<ShaderObjectLayoutImpl>(new ShaderObjectLayoutImpl());
+ auto layout = RefPtr<ShaderObjectLayoutImpl>(new ShaderObjectLayoutImpl());
SLANG_RETURN_ON_FAIL(layout->_init(this));
returnRefPtrMove(outLayout, layout);
@@ -224,7 +226,9 @@ slang::TypeLayoutReflection* ShaderObjectLayoutImpl::getParameterBlockTypeLayout
if (!m_parameterBlockTypeLayout)
{
m_parameterBlockTypeLayout = m_slangSession->getTypeLayout(
- m_elementTypeLayout->getType(), 0, slang::LayoutRules::MetalArgumentBufferTier2);
+ m_elementTypeLayout->getType(),
+ 0,
+ slang::LayoutRules::MetalArgumentBufferTier2);
}
return m_parameterBlockTypeLayout;
}
@@ -272,13 +276,16 @@ Result RootShaderObjectLayoutImpl::Builder::build(RootShaderObjectLayoutImpl** o
return SLANG_OK;
}
-void RootShaderObjectLayoutImpl::Builder::addGlobalParams(slang::VariableLayoutReflection* globalsLayout)
+void RootShaderObjectLayoutImpl::Builder::addGlobalParams(
+ slang::VariableLayoutReflection* globalsLayout)
{
setElementTypeLayout(globalsLayout->getTypeLayout());
}
void RootShaderObjectLayoutImpl::Builder::addEntryPoint(
- SlangStage stage, ShaderObjectLayoutImpl* entryPointLayout, slang::EntryPointLayout* slangEntryPoint)
+ SlangStage stage,
+ ShaderObjectLayoutImpl* entryPointLayout,
+ slang::EntryPointLayout* slangEntryPoint)
{
EntryPointInfo info;
info.layout = entryPointLayout;
@@ -301,7 +308,10 @@ Result RootShaderObjectLayoutImpl::create(
auto slangEntryPoint = programLayout->getEntryPointByIndex(e);
RefPtr<ShaderObjectLayoutImpl> entryPointLayout;
SLANG_RETURN_ON_FAIL(ShaderObjectLayoutImpl::createForElementType(
- renderer, program->getSession(), slangEntryPoint->getTypeLayout(), entryPointLayout.writeRef()));
+ renderer,
+ program->getSession(),
+ slangEntryPoint->getTypeLayout(),
+ entryPointLayout.writeRef()));
builder.addEntryPoint(slangEntryPoint->getStage(), entryPointLayout, slangEntryPoint);
}
diff --git a/tools/gfx/metal/metal-shader-object-layout.h b/tools/gfx/metal/metal-shader-object-layout.h
index 24a969c89..02833e4ca 100644
--- a/tools/gfx/metal/metal-shader-object-layout.h
+++ b/tools/gfx/metal/metal-shader-object-layout.h
@@ -63,8 +63,7 @@ public:
/// Offset information for a sub-object range
struct SubObjectRangeOffset : BindingOffset
{
- SubObjectRangeOffset()
- {}
+ SubObjectRangeOffset() {}
SubObjectRangeOffset(slang::VariableLayoutReflection* varLayout);
@@ -75,8 +74,7 @@ public:
/// Stride information for a sub-object range
struct SubObjectRangeStride : BindingOffset
{
- SubObjectRangeStride()
- {}
+ SubObjectRangeStride() {}
SubObjectRangeStride(slang::TypeLayoutReflection* typeLayout);
@@ -105,7 +103,8 @@ public:
public:
Builder(RendererBase* renderer, slang::ISession* session)
: m_renderer(renderer), m_session(session)
- {}
+ {
+ }
RendererBase* m_renderer;
slang::ISession* m_session;
@@ -129,7 +128,7 @@ public:
Index m_subObjectCount = 0;
uint32_t m_totalOrdinaryDataSize = 0;
-
+
/// The container type of this shader object. When `m_containerType` is
/// `StructuredBuffer` or `Array`, this shader object represents a collection
/// instead of a single object.
@@ -161,10 +160,7 @@ public:
RendererBase* getRenderer() { return m_renderer; }
- slang::TypeReflection* getType()
- {
- return m_elementTypeLayout->getType();
- }
+ slang::TypeReflection* getType() { return m_elementTypeLayout->getType(); }
/// Get the indices that represent all the buffer ranges in this type
List<Index> const& getBufferRanges() const { return m_bufferRanges; }
@@ -178,6 +174,7 @@ public:
uint32_t getTotalOrdinaryDataSize() const { return m_totalOrdinaryDataSize; }
slang::TypeLayoutReflection* getParameterBlockTypeLayout();
+
protected:
Result _init(Builder const* builder);
@@ -204,7 +201,8 @@ public:
{
RefPtr<ShaderObjectLayoutImpl> layout;
- /// The offset for this entry point's parameters, relative to the starting offset for the program
+ /// The offset for this entry point's parameters, relative to the starting offset for the
+ /// program
BindingOffset offset;
};
@@ -217,11 +215,15 @@ public:
: Super::Builder(renderer, program->getSession())
, m_program(program)
, m_programLayout(programLayout)
- {}
+ {
+ }
Result build(RootShaderObjectLayoutImpl** outLayout);
void addGlobalParams(slang::VariableLayoutReflection* globalsLayout);
- void addEntryPoint(SlangStage stage, ShaderObjectLayoutImpl* entryPointLayout, slang::EntryPointLayout* slangEntryPoint);
+ void addEntryPoint(
+ SlangStage stage,
+ ShaderObjectLayoutImpl* entryPointLayout,
+ slang::EntryPointLayout* slangEntryPoint);
slang::IComponentType* m_program;
slang::ProgramLayout* m_programLayout;
@@ -244,7 +246,7 @@ public:
protected:
Result _init(Builder const* builder);
- ComPtr<slang::IComponentType> m_program;
+ ComPtr<slang::IComponentType> m_program;
slang::ProgramLayout* m_programLayout = nullptr;
List<EntryPointInfo> m_entryPoints;
diff --git a/tools/gfx/metal/metal-shader-object.cpp b/tools/gfx/metal/metal-shader-object.cpp
index 6d421e065..7ee7e8023 100644
--- a/tools/gfx/metal/metal-shader-object.cpp
+++ b/tools/gfx/metal/metal-shader-object.cpp
@@ -1,8 +1,8 @@
// metal-shader-object.cpp
#include "metal-shader-object.h"
-#include "metal-sampler.h"
#include "metal-device.h"
+#include "metal-sampler.h"
namespace gfx
{
@@ -24,12 +24,10 @@ Result ShaderObjectImpl::create(
return SLANG_OK;
}
-ShaderObjectImpl::~ShaderObjectImpl()
-{
-}
+ShaderObjectImpl::~ShaderObjectImpl() {}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setData(ShaderOffset const& inOffset, void const* data, size_t inSize)
+ShaderObjectImpl::setData(ShaderOffset const& inOffset, void const* data, size_t inSize)
{
Index offset = inOffset.uniformOffset;
Index size = inSize;
@@ -59,7 +57,7 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL
- ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView* resourceView)
+ShaderObjectImpl::setResource(ShaderOffset const& offset, IResourceView* resourceView)
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
@@ -74,26 +72,30 @@ SLANG_NO_THROW Result SLANG_MCALL
case slang::BindingType::Texture:
case slang::BindingType::MutableTexture:
SLANG_ASSERT(resourceViewImpl->m_type == ResourceViewImpl::ViewType::Texture);
- m_textures[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<TextureResourceViewImpl*>(resourceView);
+ m_textures[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<TextureResourceViewImpl*>(resourceView);
break;
case slang::BindingType::RawBuffer:
case slang::BindingType::ConstantBuffer:
case slang::BindingType::MutableRawBuffer:
SLANG_ASSERT(resourceViewImpl->m_type == ResourceViewImpl::ViewType::Buffer);
- m_buffers[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<BufferResourceViewImpl*>(resourceView);
+ m_buffers[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<BufferResourceViewImpl*>(resourceView);
break;
case slang::BindingType::TypedBuffer:
case slang::BindingType::MutableTypedBuffer:
SLANG_ASSERT(!"Not implemented");
// SLANG_ASSERT(resourceViewImpl->m_type == ResourceViewImpl::ViewType::TexelBuffer);
- // m_textures[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<TextureResourceViewImpl*>(resourceView);
+ // m_textures[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ // static_cast<TextureResourceViewImpl*>(resourceView);
break;
}
m_isArgumentBufferDirty = true;
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* sampler)
+SLANG_NO_THROW Result SLANG_MCALL
+ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* sampler)
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
@@ -102,7 +104,8 @@ SLANG_NO_THROW Result SLANG_MCALL ShaderObjectImpl::setSampler(ShaderOffset cons
return SLANG_E_INVALID_ARG;
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
- m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<SamplerStateImpl*>(sampler);
+ m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<SamplerStateImpl*>(sampler);
m_isArgumentBufferDirty = true;
return SLANG_OK;
}
@@ -169,7 +172,7 @@ Result ShaderObjectImpl::init(IDevice* device, ShaderObjectLayoutImpl* layout)
Result ShaderObjectImpl::_writeOrdinaryData(
void* dest,
- size_t destSize,
+ size_t destSize,
ShaderObjectLayoutImpl* layout)
{
// We start by simply writing in the ordinary data contained directly in this object.
@@ -197,7 +200,8 @@ Result ShaderObjectImpl::_writeOrdinaryData(
for (auto const& subObjectRangeInfo : layout->getSubObjectRanges())
{
Index subObjectRangeIndex = subObjectRangeCounter++;
- auto const& bindingRangeInfo = layout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
+ auto const& bindingRangeInfo =
+ layout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
// We only need to handle sub-object ranges for interface/existential-type fields,
// because fields of constant-buffer or parameter-block type are responsible for
@@ -250,11 +254,15 @@ Result ShaderObjectImpl::_writeOrdinaryData(
ShaderObjectLayoutImpl* subObjectLayout = subObject->getLayout();
- auto subObjectOffset = subObjectRangePendingDataOffset + i * subObjectRangePendingDataStride;
+ auto subObjectOffset =
+ subObjectRangePendingDataOffset + i * subObjectRangePendingDataStride;
auto subObjectDest = (char*)dest + subObjectOffset;
- subObject->_writeOrdinaryData(subObjectDest, destSize - subObjectOffset, subObjectLayout);
+ subObject->_writeOrdinaryData(
+ subObjectDest,
+ destSize - subObjectOffset,
+ subObjectLayout);
}
}
return SLANG_OK;
@@ -294,7 +302,7 @@ Result ShaderObjectImpl::_ensureOrdinaryDataBufferCreatedIfNeeded(
// don't need or want to inline it into this call site.
//
- MemoryRange range = { 0, ordinaryDataSize };
+ MemoryRange range = {0, ordinaryDataSize};
void* ordinaryData;
SLANG_RETURN_ON_FAIL(m_ordinaryDataBuffer->map(&range, &ordinaryData));
auto result = _writeOrdinaryData(ordinaryData, ordinaryDataSize, layout);
@@ -389,78 +397,98 @@ BufferResourceImpl* ShaderObjectImpl::_ensureArgumentBufferUpToDate(
// the offsets for each field.
//
auto dataSize = typeLayout->getSize();
- MemoryRange range = { 0, dataSize };
+ MemoryRange range = {0, dataSize};
void* argumentData;
SLANG_RETURN_NULL_ON_FAIL(m_argumentBuffer->map(&range, &argumentData));
// Now fill in argument values to `argumentData`.
int bindingRangeIndex = 0;
- SLANG_ASSERT(defaultTypeLayout->getBindingRangeCount() == typeLayout->getBindingRangeCount());
+ SLANG_ASSERT(
+ defaultTypeLayout->getBindingRangeCount() == typeLayout->getBindingRangeCount());
int bufferBindingIndexOffset = layout->getTotalOrdinaryDataSize() != 0 ? 1 : 0;
-
- for (unsigned int bindingRangeIndex = 0; bindingRangeIndex < defaultTypeLayout->getBindingRangeCount(); bindingRangeIndex++)
+
+ for (unsigned int bindingRangeIndex = 0;
+ bindingRangeIndex < defaultTypeLayout->getBindingRangeCount();
+ bindingRangeIndex++)
{
int bindingCount = defaultTypeLayout->getBindingRangeBindingCount(bindingRangeIndex);
int setIndex = defaultTypeLayout->getBindingRangeDescriptorSetIndex(bindingRangeIndex);
- int rangeIndex = defaultTypeLayout->getBindingRangeFirstDescriptorRangeIndex(bindingRangeIndex);
- int bindingOffset = defaultTypeLayout->getDescriptorSetDescriptorRangeIndexOffset(setIndex, rangeIndex);
+ int rangeIndex =
+ defaultTypeLayout->getBindingRangeFirstDescriptorRangeIndex(bindingRangeIndex);
+ int bindingOffset =
+ defaultTypeLayout->getDescriptorSetDescriptorRangeIndexOffset(setIndex, rangeIndex);
auto bindingType = defaultTypeLayout->getBindingRangeType(bindingRangeIndex);
for (int i = 0; i < bindingCount; i++)
{
- auto argumentDataOffset = typeLayout->getDescriptorSetDescriptorRangeIndexOffset(setIndex, rangeIndex) + i * sizeof(uint64_t);
+ auto argumentDataOffset =
+ typeLayout->getDescriptorSetDescriptorRangeIndexOffset(setIndex, rangeIndex) +
+ i * sizeof(uint64_t);
auto argumentPtr = (uint8_t*)argumentData + argumentDataOffset;
auto resourceIndex = bindingOffset + i;
switch (bindingType)
{
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ParameterBlock:
- {
- if (m_objects[resourceIndex])
{
- auto subArgumentBuffer = m_objects[resourceIndex]->_ensureArgumentBufferUpToDate(device, m_objects[resourceIndex]->getLayout());
- if (subArgumentBuffer)
+ if (m_objects[resourceIndex])
{
- gfx::DeviceAddress bufferPtr = subArgumentBuffer->m_buffer->gpuAddress();
- memcpy(argumentPtr, &bufferPtr, sizeof(bufferPtr));
+ auto subArgumentBuffer =
+ m_objects[resourceIndex]->_ensureArgumentBufferUpToDate(
+ device,
+ m_objects[resourceIndex]->getLayout());
+ if (subArgumentBuffer)
+ {
+ gfx::DeviceAddress bufferPtr =
+ subArgumentBuffer->m_buffer->gpuAddress();
+ memcpy(argumentPtr, &bufferPtr, sizeof(bufferPtr));
+ }
}
+ break;
}
- break;
- }
case slang::BindingType::RawBuffer:
case slang::BindingType::MutableRawBuffer:
- {
- auto bufferViewImpl = static_cast<BufferResourceViewImpl*>(m_buffers[resourceIndex + bufferBindingIndexOffset].get());
-
- if (bufferViewImpl)
{
- gfx::DeviceAddress bufferPtr = bufferViewImpl->m_buffer->getDeviceAddress() + bufferViewImpl->m_offset;
- memcpy(argumentPtr, &bufferPtr, sizeof(bufferPtr));
+ auto bufferViewImpl = static_cast<BufferResourceViewImpl*>(
+ m_buffers[resourceIndex + bufferBindingIndexOffset].get());
+
+ if (bufferViewImpl)
+ {
+ gfx::DeviceAddress bufferPtr =
+ bufferViewImpl->m_buffer->getDeviceAddress() +
+ bufferViewImpl->m_offset;
+ memcpy(argumentPtr, &bufferPtr, sizeof(bufferPtr));
+ }
+ break;
}
- break;
- }
case slang::BindingType::Texture:
case slang::BindingType::MutableTexture:
- {
- auto textureViewImpl = static_cast<TextureResourceViewImpl*>(m_textures[resourceIndex].get());
- if (textureViewImpl)
{
- auto resourceId = textureViewImpl->m_textureView->gpuResourceID();
- memcpy(argumentPtr, &resourceId, sizeof(resourceId));
+ auto textureViewImpl =
+ static_cast<TextureResourceViewImpl*>(m_textures[resourceIndex].get());
+ if (textureViewImpl)
+ {
+ auto resourceId = textureViewImpl->m_textureView->gpuResourceID();
+ memcpy(argumentPtr, &resourceId, sizeof(resourceId));
+ }
+ break;
}
- break;
- }
case slang::BindingType::Sampler:
- {
- auto samplerStateImpl = static_cast<SamplerStateImpl*>(m_samplers[resourceIndex].get());
- auto resourceId = samplerStateImpl->m_samplerState->gpuResourceID();
- memcpy(argumentPtr, &resourceId, sizeof(resourceId));
- break;
- }
+ {
+ auto samplerStateImpl =
+ static_cast<SamplerStateImpl*>(m_samplers[resourceIndex].get());
+ auto resourceId = samplerStateImpl->m_samplerState->gpuResourceID();
+ memcpy(argumentPtr, &resourceId, sizeof(resourceId));
+ break;
+ }
}
}
}
- writeOrdinaryDataIntoArgumentBuffer(typeLayout, defaultTypeLayout, (uint8_t*)argumentData, (uint8_t*)m_data.getBuffer());
+ writeOrdinaryDataIntoArgumentBuffer(
+ typeLayout,
+ defaultTypeLayout,
+ (uint8_t*)argumentData,
+ (uint8_t*)m_data.getBuffer());
m_argumentBuffer->unmap(&range);
m_isArgumentBufferDirty = false;
}
@@ -475,7 +503,7 @@ Result ShaderObjectImpl::bindAsParameterBlock(
{
if (!context->device->m_hasArgumentBufferTier2)
return SLANG_FAIL;
-
+
auto argumentBuffer = _ensureArgumentBufferUpToDate(context->device, layout);
if (m_argumentBuffer)
@@ -531,7 +559,9 @@ Result ShaderObjectImpl::bindAsValue(
for (uint32_t i = 0; i < count; ++i)
{
auto buffer = m_buffers[baseIndex + i];
- context->setBuffer(buffer ? buffer->m_buffer->m_buffer.get() : nullptr, registerOffset + i);
+ context->setBuffer(
+ buffer ? buffer->m_buffer->m_buffer.get() : nullptr,
+ registerOffset + i);
}
}
@@ -544,7 +574,9 @@ Result ShaderObjectImpl::bindAsValue(
for (uint32_t i = 0; i < count; ++i)
{
auto texture = m_textures[baseIndex + i];
- context->setTexture(texture ? texture->m_textureView.get() : nullptr, registerOffset + i);
+ context->setTexture(
+ texture ? texture->m_textureView.get() : nullptr,
+ registerOffset + i);
}
}
@@ -557,7 +589,9 @@ Result ShaderObjectImpl::bindAsValue(
for (uint32_t i = 0; i < count; ++i)
{
auto sampler = m_samplers[baseIndex + i];
- context->setSampler(sampler ? sampler->m_samplerState.get() : nullptr, registerOffset + i);
+ context->setSampler(
+ sampler ? sampler->m_samplerState.get() : nullptr,
+ registerOffset + i);
}
}
@@ -585,31 +619,33 @@ Result ShaderObjectImpl::bindAsValue(
switch (bindingRange.bindingType)
{
case slang::BindingType::ConstantBuffer:
- {
- BindingOffset objOffset = rangeOffset;
- for (Index i = 0; i < count; ++i)
{
- auto subObject = m_objects[subObjectIndex + i];
+ BindingOffset objOffset = rangeOffset;
+ for (Index i = 0; i < count; ++i)
+ {
+ auto subObject = m_objects[subObjectIndex + i];
- // Unsurprisingly, we bind each object in the range as
- // a constant buffer.
- //
- SLANG_RETURN_ON_FAIL(subObject->bindAsConstantBuffer(context, objOffset, subObjectLayout));
+ // Unsurprisingly, we bind each object in the range as
+ // a constant buffer.
+ //
+ SLANG_RETURN_ON_FAIL(
+ subObject->bindAsConstantBuffer(context, objOffset, subObjectLayout));
- objOffset += rangeStride;
+ objOffset += rangeStride;
+ }
+ break;
}
- break;
- }
case slang::BindingType::ParameterBlock:
- {
- BindingOffset objOffset = rangeOffset;
- for (Index i = 0; i < count; ++i)
{
- auto subObject = m_objects[subObjectIndex + i];
- SLANG_RETURN_ON_FAIL(subObject->bindAsParameterBlock(context, objOffset, subObjectLayout));
- objOffset += rangeStride;
+ BindingOffset objOffset = rangeOffset;
+ for (Index i = 0; i < count; ++i)
+ {
+ auto subObject = m_objects[subObjectIndex + i];
+ SLANG_RETURN_ON_FAIL(
+ subObject->bindAsParameterBlock(context, objOffset, subObjectLayout));
+ objOffset += rangeStride;
+ }
}
- }
break;
#if 0
@@ -638,8 +674,7 @@ Result ShaderObjectImpl::bindAsValue(
break;
#endif
- default:
- break;
+ default: break;
}
}
@@ -668,9 +703,7 @@ Result RootShaderObjectImpl::collectSpecializationArgs(ExtendedShaderObjectTypeL
return SLANG_OK;
}
-Result RootShaderObjectImpl::bindAsRoot(
- BindingContext* context,
- RootShaderObjectLayoutImpl* layout)
+Result RootShaderObjectImpl::bindAsRoot(BindingContext* context, RootShaderObjectLayoutImpl* layout)
{
// When binding an entire root shader object, we need to deal with
// the way that specialization might have allocated space for "pending"
@@ -724,7 +757,8 @@ Result RootShaderObjectImpl::bindAsRoot(
// the absolute offsets as are used for the global scope do not apply
// (because entry points don't need to deal with explicit bindings).
//
- SLANG_RETURN_ON_FAIL(entryPoint->bindAsConstantBuffer(context, entryPointOffset, entryPointInfo.layout));
+ SLANG_RETURN_ON_FAIL(
+ entryPoint->bindAsConstantBuffer(context, entryPointOffset, entryPointInfo.layout));
}
return SLANG_OK;
diff --git a/tools/gfx/metal/metal-shader-object.h b/tools/gfx/metal/metal-shader-object.h
index 8a3d5d392..256995fe4 100644
--- a/tools/gfx/metal/metal-shader-object.h
+++ b/tools/gfx/metal/metal-shader-object.h
@@ -1,12 +1,11 @@
// metal-shader-object.h
#pragma once
#include "metal-base.h"
+#include "metal-helper-functions.h"
#include "metal-resource-views.h"
#include "metal-sampler.h"
#include "metal-shader-object-layout.h"
-#include "metal-helper-functions.h"
-
namespace gfx
{
@@ -16,10 +15,7 @@ namespace metal
{
class ShaderObjectImpl
- : public ShaderObjectBaseImpl<
- ShaderObjectImpl,
- ShaderObjectLayoutImpl,
- SimpleShaderObjectData>
+ : public ShaderObjectBaseImpl<ShaderObjectImpl, ShaderObjectLayoutImpl, SimpleShaderObjectData>
{
public:
static Result create(
@@ -51,33 +47,31 @@ public:
}
SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& inOffset, void const* data, size_t inSize) SLANG_OVERRIDE;
+ setData(ShaderOffset const& inOffset, void const* data, size_t inSize) SLANG_OVERRIDE;
SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* resourceView) SLANG_OVERRIDE;
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) SLANG_OVERRIDE;
SLANG_NO_THROW Result SLANG_MCALL setSampler(ShaderOffset const& offset, ISamplerState* sampler)
SLANG_OVERRIDE;
SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) SLANG_OVERRIDE
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) SLANG_OVERRIDE
{
return SLANG_E_NOT_IMPLEMENTED;
}
public:
-
-
protected:
friend class ProgramVars;
Result init(IDevice* device, ShaderObjectLayoutImpl* layout);
- /// Write the uniform/ordinary data of this object into the given `dest` buffer at the given `offset`
- Result _writeOrdinaryData(
- void* dest,
- size_t destSize,
- ShaderObjectLayoutImpl* layout);
+ /// Write the uniform/ordinary data of this object into the given `dest` buffer at the given
+ /// `offset`
+ Result _writeOrdinaryData(void* dest, size_t destSize, ShaderObjectLayoutImpl* layout);
/// Ensure that the `m_ordinaryDataBuffer` has been created, if it is needed
///
@@ -162,10 +156,9 @@ public:
};
class MutableShaderObjectImpl
- : public MutableShaderObject<
- MutableShaderObjectImpl,
- ShaderObjectLayoutImpl>
-{};
+ : public MutableShaderObject<MutableShaderObjectImpl, ShaderObjectLayoutImpl>
+{
+};
class RootShaderObjectImpl : public ShaderObjectImpl
{
@@ -175,14 +168,24 @@ public:
virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() override { return 1; }
virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() override { return 1; }
- static Result create(IDevice* device, RootShaderObjectLayoutImpl* layout, RootShaderObjectImpl** outShaderObject);
+ static Result create(
+ IDevice* device,
+ RootShaderObjectLayoutImpl* layout,
+ RootShaderObjectImpl** outShaderObject);
Result init(IDevice* device, RootShaderObjectLayoutImpl* layout);
- RootShaderObjectLayoutImpl* getLayout() { return static_cast<RootShaderObjectLayoutImpl*>(m_layout.Ptr()); }
+ RootShaderObjectLayoutImpl* getLayout()
+ {
+ return static_cast<RootShaderObjectLayoutImpl*>(m_layout.Ptr());
+ }
- GfxCount SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE { return (GfxCount)m_entryPoints.getCount(); }
- SlangResult SLANG_MCALL getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) SLANG_OVERRIDE
+ GfxCount SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE
+ {
+ return (GfxCount)m_entryPoints.getCount();
+ }
+ SlangResult SLANG_MCALL getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
+ SLANG_OVERRIDE
{
returnComPtr(outEntryPoint, m_entryPoints[index]);
return SLANG_OK;
@@ -191,9 +194,7 @@ public:
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override;
/// Bind this object as a root shader object
- Result bindAsRoot(
- BindingContext* context,
- RootShaderObjectLayoutImpl* specializedLayout);
+ Result bindAsRoot(BindingContext* context, RootShaderObjectLayoutImpl* specializedLayout);
protected:
List<RefPtr<ShaderObjectImpl>> m_entryPoints;
diff --git a/tools/gfx/metal/metal-shader-program.cpp b/tools/gfx/metal/metal-shader-program.cpp
index e0f973eb6..c95e99d04 100644
--- a/tools/gfx/metal/metal-shader-program.cpp
+++ b/tools/gfx/metal/metal-shader-program.cpp
@@ -1,5 +1,6 @@
// metal-shader-program.cpp
#include "metal-shader-program.h"
+
#include "metal-device.h"
#include "metal-util.h"
@@ -16,18 +17,22 @@ ShaderProgramImpl::ShaderProgramImpl(DeviceImpl* device)
{
}
-ShaderProgramImpl::~ShaderProgramImpl()
-{
-}
+ShaderProgramImpl::~ShaderProgramImpl() {}
-Result ShaderProgramImpl::createShaderModule(slang::EntryPointReflection* entryPointInfo, ComPtr<ISlangBlob> kernelCode)
+Result ShaderProgramImpl::createShaderModule(
+ slang::EntryPointReflection* entryPointInfo,
+ ComPtr<ISlangBlob> kernelCode)
{
Module module;
module.stage = entryPointInfo->getStage();
module.entryPointName = entryPointInfo->getNameOverride();
module.code = kernelCode;
-
- dispatch_data_t data = dispatch_data_create(kernelCode->getBufferPointer(), kernelCode->getBufferSize(), dispatch_get_main_queue(), NULL);
+
+ dispatch_data_t data = dispatch_data_create(
+ kernelCode->getBufferPointer(),
+ kernelCode->getBufferSize(),
+ dispatch_get_main_queue(),
+ NULL);
NS::Error* error;
module.library = NS::TransferPtr(m_device->m_device->newLibrary(data, &error));
if (!module.library)
diff --git a/tools/gfx/metal/metal-shader-program.h b/tools/gfx/metal/metal-shader-program.h
index d6deb6574..691e12c9e 100644
--- a/tools/gfx/metal/metal-shader-program.h
+++ b/tools/gfx/metal/metal-shader-program.h
@@ -31,7 +31,9 @@ public:
ShaderProgramImpl(DeviceImpl* device);
~ShaderProgramImpl();
- virtual Result createShaderModule(slang::EntryPointReflection* entryPointInfo, ComPtr<ISlangBlob> kernelCode) override;
+ virtual Result createShaderModule(
+ slang::EntryPointReflection* entryPointInfo,
+ ComPtr<ISlangBlob> kernelCode) override;
};
diff --git a/tools/gfx/metal/metal-swap-chain.cpp b/tools/gfx/metal/metal-swap-chain.cpp
index 1478c8bf4..75bb5afa1 100644
--- a/tools/gfx/metal/metal-swap-chain.cpp
+++ b/tools/gfx/metal/metal-swap-chain.cpp
@@ -1,8 +1,8 @@
// metal-swap-chain.cpp
#include "metal-swap-chain.h"
-#include "metal-util.h"
#include "../apple/cocoa-util.h"
+#include "metal-util.h"
namespace gfx
{
@@ -31,7 +31,10 @@ void SwapchainImpl::createImages()
{
ITextureResource::Desc imageDesc = {};
imageDesc.allowedStates = ResourceStateSet(
- ResourceState::Present, ResourceState::RenderTarget, ResourceState::CopyDestination, ResourceState::CopySource);
+ ResourceState::Present,
+ ResourceState::RenderTarget,
+ ResourceState::CopyDestination,
+ ResourceState::CopySource);
imageDesc.type = IResource::Type::Texture2D;
imageDesc.arraySize = 0;
imageDesc.format = m_desc.format;
@@ -40,7 +43,10 @@ void SwapchainImpl::createImages()
imageDesc.size.depth = 1;
imageDesc.numMipLevels = 1;
imageDesc.defaultState = ResourceState::Present;
- m_device->createTextureResource(imageDesc, nullptr, (gfx::ITextureResource**)m_images[i].writeRef());
+ m_device->createTextureResource(
+ imageDesc,
+ nullptr,
+ (gfx::ITextureResource**)m_images[i].writeRef());
}
}
@@ -105,7 +111,9 @@ Result SwapchainImpl::present()
MTL::CommandBuffer* commandBuffer = m_device->m_commandQueue->commandBuffer();
MTL::BlitCommandEncoder* encoder = commandBuffer->blitCommandEncoder();
- encoder->copyFromTexture(m_images[m_currentImageIndex]->m_texture.get(), m_currentDrawable->texture());
+ encoder->copyFromTexture(
+ m_images[m_currentImageIndex]->m_texture.get(),
+ m_currentDrawable->texture());
encoder->endEncoding();
commandBuffer->presentDrawable(m_currentDrawable.get());
commandBuffer->commit();
@@ -146,5 +154,5 @@ Result SwapchainImpl::setFullScreenMode(bool mode)
return SLANG_E_NOT_AVAILABLE;
}
-} // namespace metal
+} // namespace metal
} // namespace gfx
diff --git a/tools/gfx/metal/metal-swap-chain.h b/tools/gfx/metal/metal-swap-chain.h
index b7d57e271..957db1ad9 100644
--- a/tools/gfx/metal/metal-swap-chain.h
+++ b/tools/gfx/metal/metal-swap-chain.h
@@ -14,9 +14,7 @@ using namespace Slang;
namespace metal
{
-class SwapchainImpl
- : public ISwapchain
- , public ComObject
+class SwapchainImpl : public ISwapchain, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -42,7 +40,7 @@ public:
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override { return m_desc; }
virtual SLANG_NO_THROW Result SLANG_MCALL
- getImage(GfxIndex index, ITextureResource** outResource) override;
+ getImage(GfxIndex index, ITextureResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL resize(GfxCount width, GfxCount height) override;
virtual SLANG_NO_THROW Result SLANG_MCALL present() override;
virtual SLANG_NO_THROW int SLANG_MCALL acquireNextImage() override;
diff --git a/tools/gfx/metal/metal-texture.cpp b/tools/gfx/metal/metal-texture.cpp
index 81625aa7e..996a0b333 100644
--- a/tools/gfx/metal/metal-texture.cpp
+++ b/tools/gfx/metal/metal-texture.cpp
@@ -1,5 +1,6 @@
// metal-texture.cpp
#include "metal-texture.h"
+
#include "metal-util.h"
namespace gfx
@@ -11,14 +12,12 @@ namespace metal
{
TextureResourceImpl::TextureResourceImpl(const Desc& desc, DeviceImpl* device)
- : Parent(desc)
- , m_device(device)
-{}
-
-TextureResourceImpl::~TextureResourceImpl()
+ : Parent(desc), m_device(device)
{
}
+TextureResourceImpl::~TextureResourceImpl() {}
+
Result TextureResourceImpl::getNativeResourceHandle(InteropHandle* outHandle)
{
outHandle->api = InteropHandleAPI::Metal;
diff --git a/tools/gfx/metal/metal-texture.h b/tools/gfx/metal/metal-texture.h
index aff49beb6..fe923e965 100644
--- a/tools/gfx/metal/metal-texture.h
+++ b/tools/gfx/metal/metal-texture.h
@@ -25,7 +25,8 @@ public:
MTL::TextureType m_textureType;
MTL::PixelFormat m_pixelFormat;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
diff --git a/tools/gfx/metal/metal-transient-heap.cpp b/tools/gfx/metal/metal-transient-heap.cpp
index 8810897dd..16c883f67 100644
--- a/tools/gfx/metal/metal-transient-heap.cpp
+++ b/tools/gfx/metal/metal-transient-heap.cpp
@@ -22,9 +22,7 @@ Result TransientResourceHeapImpl::init(const ITransientResourceHeap::Desc& desc,
return SLANG_OK;
}
-TransientResourceHeapImpl::~TransientResourceHeapImpl()
-{
-}
+TransientResourceHeapImpl::~TransientResourceHeapImpl() {}
Result TransientResourceHeapImpl::createCommandBuffer(ICommandBuffer** outCmdBuffer)
{
diff --git a/tools/gfx/metal/metal-transient-heap.h b/tools/gfx/metal/metal-transient-heap.h
index 4b3f6dee9..963b5bd1b 100644
--- a/tools/gfx/metal/metal-transient-heap.h
+++ b/tools/gfx/metal/metal-transient-heap.h
@@ -27,7 +27,7 @@ public:
public:
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandBuffer(ICommandBuffer** outCommandBuffer) override;
+ createCommandBuffer(ICommandBuffer** outCommandBuffer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL synchronizeAndReset() override;
};
diff --git a/tools/gfx/metal/metal-util.cpp b/tools/gfx/metal/metal-util.cpp
index ed96eb487..fd2e9e009 100644
--- a/tools/gfx/metal/metal-util.cpp
+++ b/tools/gfx/metal/metal-util.cpp
@@ -1,117 +1,119 @@
// metal-util.cpp
#include "metal-util.h"
+
#include "core/slang-math.h"
-#include <stdlib.h>
#include <stdio.h>
+#include <stdlib.h>
-namespace gfx {
+namespace gfx
+{
MTL::PixelFormat MetalUtil::translatePixelFormat(Format format)
{
switch (format)
{
- case Format::R32G32B32A32_TYPELESS: return MTL::PixelFormatRGBA32Float;
- case Format::R32G32B32_TYPELESS: return MTL::PixelFormatInvalid;
- case Format::R32G32_TYPELESS: return MTL::PixelFormatRG32Float;
- case Format::R32_TYPELESS: return MTL::PixelFormatR32Float;
-
- case Format::R16G16B16A16_TYPELESS: return MTL::PixelFormatRGBA16Float;
- case Format::R16G16_TYPELESS: return MTL::PixelFormatRG16Float;
- case Format::R16_TYPELESS: return MTL::PixelFormatR16Float;
-
- case Format::R8G8B8A8_TYPELESS: return MTL::PixelFormatRGBA8Unorm;
- case Format::R8G8_TYPELESS: return MTL::PixelFormatRG8Unorm;
- case Format::R8_TYPELESS: return MTL::PixelFormatR8Unorm;
- case Format::B8G8R8A8_TYPELESS: return MTL::PixelFormatBGRA8Unorm;
-
- case Format::R32G32B32A32_FLOAT: return MTL::PixelFormatRGBA32Float;
- case Format::R32G32B32_FLOAT: return MTL::PixelFormatInvalid;
- case Format::R32G32_FLOAT: return MTL::PixelFormatRG32Float;
- case Format::R32_FLOAT: return MTL::PixelFormatR32Float;
-
- case Format::R16G16B16A16_FLOAT: return MTL::PixelFormatRGBA16Float;
- case Format::R16G16_FLOAT: return MTL::PixelFormatRG16Float;
- case Format::R16_FLOAT: return MTL::PixelFormatR16Float;
-
- case Format::R32G32B32A32_UINT: return MTL::PixelFormatRGBA32Uint;
- case Format::R32G32B32_UINT: return MTL::PixelFormatInvalid;
- case Format::R32G32_UINT: return MTL::PixelFormatRG32Uint;
- case Format::R32_UINT: return MTL::PixelFormatR32Uint;
-
- case Format::R16G16B16A16_UINT: return MTL::PixelFormatRGBA16Uint;
- case Format::R16G16_UINT: return MTL::PixelFormatRG16Uint;
- case Format::R16_UINT: return MTL::PixelFormatR16Uint;
-
- case Format::R8G8B8A8_UINT: return MTL::PixelFormatRGBA8Uint;
- case Format::R8G8_UINT: return MTL::PixelFormatRG8Uint;
- case Format::R8_UINT: return MTL::PixelFormatR8Uint;
-
- case Format::R32G32B32A32_SINT: return MTL::PixelFormatRGBA32Sint;
- case Format::R32G32B32_SINT: return MTL::PixelFormatInvalid;
- case Format::R32G32_SINT: return MTL::PixelFormatRG32Sint;
- case Format::R32_SINT: return MTL::PixelFormatR32Sint;
-
- case Format::R16G16B16A16_SINT: return MTL::PixelFormatRGBA16Sint;
- case Format::R16G16_SINT: return MTL::PixelFormatRG16Sint;
- case Format::R16_SINT: return MTL::PixelFormatR16Sint;
-
- case Format::R8G8B8A8_SINT: return MTL::PixelFormatRGBA8Sint;
- case Format::R8G8_SINT: return MTL::PixelFormatRG8Sint;
- case Format::R8_SINT: return MTL::PixelFormatR8Sint;
-
- case Format::R16G16B16A16_UNORM: return MTL::PixelFormatRGBA16Unorm;
- case Format::R16G16_UNORM: return MTL::PixelFormatRG16Unorm;
- case Format::R16_UNORM: return MTL::PixelFormatR16Unorm;
-
- case Format::R8G8B8A8_UNORM: return MTL::PixelFormatRGBA8Unorm;
- case Format::R8G8B8A8_UNORM_SRGB: return MTL::PixelFormatRGBA8Unorm_sRGB;
- case Format::R8G8_UNORM: return MTL::PixelFormatRG8Unorm;
- case Format::R8_UNORM: return MTL::PixelFormatR8Unorm;
- case Format::B8G8R8A8_UNORM: return MTL::PixelFormatBGRA8Unorm;
- case Format::B8G8R8A8_UNORM_SRGB: return MTL::PixelFormatBGRA8Unorm_sRGB;
- case Format::B8G8R8X8_UNORM: return MTL::PixelFormatInvalid;
- case Format::B8G8R8X8_UNORM_SRGB: return MTL::PixelFormatInvalid;
-
- case Format::R16G16B16A16_SNORM: return MTL::PixelFormatRGBA16Snorm;
- case Format::R16G16_SNORM: return MTL::PixelFormatRG16Snorm;
- case Format::R16_SNORM: return MTL::PixelFormatR16Snorm;
-
- case Format::R8G8B8A8_SNORM: return MTL::PixelFormatRGBA8Snorm;
- case Format::R8G8_SNORM: return MTL::PixelFormatRG8Snorm;
- case Format::R8_SNORM: return MTL::PixelFormatR8Snorm;
-
- case Format::D32_FLOAT: return MTL::PixelFormatDepth32Float;
- case Format::D16_UNORM: return MTL::PixelFormatDepth16Unorm;
- case Format::D32_FLOAT_S8_UINT: return MTL::PixelFormatDepth32Float_Stencil8;
- case Format::R32_FLOAT_X32_TYPELESS: return MTL::PixelFormatInvalid;
-
- case Format::B4G4R4A4_UNORM: return MTL::PixelFormatABGR4Unorm;
- case Format::B5G6R5_UNORM: return MTL::PixelFormatB5G6R5Unorm;
- case Format::B5G5R5A1_UNORM: return MTL::PixelFormatA1BGR5Unorm;
-
- case Format::R9G9B9E5_SHAREDEXP: return MTL::PixelFormatRGB9E5Float;
- case Format::R10G10B10A2_TYPELESS: return MTL::PixelFormatInvalid;
- case Format::R10G10B10A2_UINT: return MTL::PixelFormatRGB10A2Uint;
- case Format::R10G10B10A2_UNORM: return MTL::PixelFormatRGB10A2Unorm;
- case Format::R11G11B10_FLOAT: return MTL::PixelFormatRG11B10Float;
-
- case Format::BC1_UNORM: return MTL::PixelFormatBC1_RGBA;
- case Format::BC1_UNORM_SRGB: return MTL::PixelFormatBC1_RGBA_sRGB;
- case Format::BC2_UNORM: return MTL::PixelFormatBC2_RGBA;
- case Format::BC2_UNORM_SRGB: return MTL::PixelFormatBC2_RGBA_sRGB;
- case Format::BC3_UNORM: return MTL::PixelFormatBC3_RGBA;
- case Format::BC3_UNORM_SRGB: return MTL::PixelFormatBC3_RGBA_sRGB;
- case Format::BC4_UNORM: return MTL::PixelFormatBC4_RUnorm;
- case Format::BC4_SNORM: return MTL::PixelFormatBC4_RSnorm;
- case Format::BC5_UNORM: return MTL::PixelFormatBC5_RGUnorm;
- case Format::BC5_SNORM: return MTL::PixelFormatBC5_RGSnorm;
- case Format::BC6H_UF16: return MTL::PixelFormatBC6H_RGBUfloat;
- case Format::BC6H_SF16: return MTL::PixelFormatBC6H_RGBFloat;
- case Format::BC7_UNORM: return MTL::PixelFormatBC7_RGBAUnorm;
- case Format::BC7_UNORM_SRGB: return MTL::PixelFormatBC7_RGBAUnorm_sRGB;
-
- default: return MTL::PixelFormatInvalid;
+ case Format::R32G32B32A32_TYPELESS: return MTL::PixelFormatRGBA32Float;
+ case Format::R32G32B32_TYPELESS: return MTL::PixelFormatInvalid;
+ case Format::R32G32_TYPELESS: return MTL::PixelFormatRG32Float;
+ case Format::R32_TYPELESS: return MTL::PixelFormatR32Float;
+
+ case Format::R16G16B16A16_TYPELESS: return MTL::PixelFormatRGBA16Float;
+ case Format::R16G16_TYPELESS: return MTL::PixelFormatRG16Float;
+ case Format::R16_TYPELESS: return MTL::PixelFormatR16Float;
+
+ case Format::R8G8B8A8_TYPELESS: return MTL::PixelFormatRGBA8Unorm;
+ case Format::R8G8_TYPELESS: return MTL::PixelFormatRG8Unorm;
+ case Format::R8_TYPELESS: return MTL::PixelFormatR8Unorm;
+ case Format::B8G8R8A8_TYPELESS: return MTL::PixelFormatBGRA8Unorm;
+
+ case Format::R32G32B32A32_FLOAT: return MTL::PixelFormatRGBA32Float;
+ case Format::R32G32B32_FLOAT: return MTL::PixelFormatInvalid;
+ case Format::R32G32_FLOAT: return MTL::PixelFormatRG32Float;
+ case Format::R32_FLOAT: return MTL::PixelFormatR32Float;
+
+ case Format::R16G16B16A16_FLOAT: return MTL::PixelFormatRGBA16Float;
+ case Format::R16G16_FLOAT: return MTL::PixelFormatRG16Float;
+ case Format::R16_FLOAT: return MTL::PixelFormatR16Float;
+
+ case Format::R32G32B32A32_UINT: return MTL::PixelFormatRGBA32Uint;
+ case Format::R32G32B32_UINT: return MTL::PixelFormatInvalid;
+ case Format::R32G32_UINT: return MTL::PixelFormatRG32Uint;
+ case Format::R32_UINT: return MTL::PixelFormatR32Uint;
+
+ case Format::R16G16B16A16_UINT: return MTL::PixelFormatRGBA16Uint;
+ case Format::R16G16_UINT: return MTL::PixelFormatRG16Uint;
+ case Format::R16_UINT: return MTL::PixelFormatR16Uint;
+
+ case Format::R8G8B8A8_UINT: return MTL::PixelFormatRGBA8Uint;
+ case Format::R8G8_UINT: return MTL::PixelFormatRG8Uint;
+ case Format::R8_UINT: return MTL::PixelFormatR8Uint;
+
+ case Format::R32G32B32A32_SINT: return MTL::PixelFormatRGBA32Sint;
+ case Format::R32G32B32_SINT: return MTL::PixelFormatInvalid;
+ case Format::R32G32_SINT: return MTL::PixelFormatRG32Sint;
+ case Format::R32_SINT: return MTL::PixelFormatR32Sint;
+
+ case Format::R16G16B16A16_SINT: return MTL::PixelFormatRGBA16Sint;
+ case Format::R16G16_SINT: return MTL::PixelFormatRG16Sint;
+ case Format::R16_SINT: return MTL::PixelFormatR16Sint;
+
+ case Format::R8G8B8A8_SINT: return MTL::PixelFormatRGBA8Sint;
+ case Format::R8G8_SINT: return MTL::PixelFormatRG8Sint;
+ case Format::R8_SINT: return MTL::PixelFormatR8Sint;
+
+ case Format::R16G16B16A16_UNORM: return MTL::PixelFormatRGBA16Unorm;
+ case Format::R16G16_UNORM: return MTL::PixelFormatRG16Unorm;
+ case Format::R16_UNORM: return MTL::PixelFormatR16Unorm;
+
+ case Format::R8G8B8A8_UNORM: return MTL::PixelFormatRGBA8Unorm;
+ case Format::R8G8B8A8_UNORM_SRGB: return MTL::PixelFormatRGBA8Unorm_sRGB;
+ case Format::R8G8_UNORM: return MTL::PixelFormatRG8Unorm;
+ case Format::R8_UNORM: return MTL::PixelFormatR8Unorm;
+ case Format::B8G8R8A8_UNORM: return MTL::PixelFormatBGRA8Unorm;
+ case Format::B8G8R8A8_UNORM_SRGB: return MTL::PixelFormatBGRA8Unorm_sRGB;
+ case Format::B8G8R8X8_UNORM: return MTL::PixelFormatInvalid;
+ case Format::B8G8R8X8_UNORM_SRGB: return MTL::PixelFormatInvalid;
+
+ case Format::R16G16B16A16_SNORM: return MTL::PixelFormatRGBA16Snorm;
+ case Format::R16G16_SNORM: return MTL::PixelFormatRG16Snorm;
+ case Format::R16_SNORM: return MTL::PixelFormatR16Snorm;
+
+ case Format::R8G8B8A8_SNORM: return MTL::PixelFormatRGBA8Snorm;
+ case Format::R8G8_SNORM: return MTL::PixelFormatRG8Snorm;
+ case Format::R8_SNORM: return MTL::PixelFormatR8Snorm;
+
+ case Format::D32_FLOAT: return MTL::PixelFormatDepth32Float;
+ case Format::D16_UNORM: return MTL::PixelFormatDepth16Unorm;
+ case Format::D32_FLOAT_S8_UINT: return MTL::PixelFormatDepth32Float_Stencil8;
+ case Format::R32_FLOAT_X32_TYPELESS: return MTL::PixelFormatInvalid;
+
+ case Format::B4G4R4A4_UNORM: return MTL::PixelFormatABGR4Unorm;
+ case Format::B5G6R5_UNORM: return MTL::PixelFormatB5G6R5Unorm;
+ case Format::B5G5R5A1_UNORM: return MTL::PixelFormatA1BGR5Unorm;
+
+ case Format::R9G9B9E5_SHAREDEXP: return MTL::PixelFormatRGB9E5Float;
+ case Format::R10G10B10A2_TYPELESS: return MTL::PixelFormatInvalid;
+ case Format::R10G10B10A2_UINT: return MTL::PixelFormatRGB10A2Uint;
+ case Format::R10G10B10A2_UNORM: return MTL::PixelFormatRGB10A2Unorm;
+ case Format::R11G11B10_FLOAT: return MTL::PixelFormatRG11B10Float;
+
+ case Format::BC1_UNORM: return MTL::PixelFormatBC1_RGBA;
+ case Format::BC1_UNORM_SRGB: return MTL::PixelFormatBC1_RGBA_sRGB;
+ case Format::BC2_UNORM: return MTL::PixelFormatBC2_RGBA;
+ case Format::BC2_UNORM_SRGB: return MTL::PixelFormatBC2_RGBA_sRGB;
+ case Format::BC3_UNORM: return MTL::PixelFormatBC3_RGBA;
+ case Format::BC3_UNORM_SRGB: return MTL::PixelFormatBC3_RGBA_sRGB;
+ case Format::BC4_UNORM: return MTL::PixelFormatBC4_RUnorm;
+ case Format::BC4_SNORM: return MTL::PixelFormatBC4_RSnorm;
+ case Format::BC5_UNORM: return MTL::PixelFormatBC5_RGUnorm;
+ case Format::BC5_SNORM: return MTL::PixelFormatBC5_RGSnorm;
+ case Format::BC6H_UF16: return MTL::PixelFormatBC6H_RGBUfloat;
+ case Format::BC6H_SF16: return MTL::PixelFormatBC6H_RGBFloat;
+ case Format::BC7_UNORM: return MTL::PixelFormatBC7_RGBAUnorm;
+ case Format::BC7_UNORM_SRGB: return MTL::PixelFormatBC7_RGBAUnorm_sRGB;
+
+ default: return MTL::PixelFormatInvalid;
}
}
@@ -119,60 +121,60 @@ MTL::VertexFormat MetalUtil::translateVertexFormat(Format format)
{
switch (format)
{
- case Format::R8G8_UINT: return MTL::VertexFormatUChar2;
+ case Format::R8G8_UINT: return MTL::VertexFormatUChar2;
// VertexFormatUChar3
- case Format::R8G8B8A8_UINT: return MTL::VertexFormatUChar4;
- case Format::R8G8_SINT: return MTL::VertexFormatChar2;
+ case Format::R8G8B8A8_UINT: return MTL::VertexFormatUChar4;
+ case Format::R8G8_SINT: return MTL::VertexFormatChar2;
// return VertexFormatChar3
- case Format::R8G8B8A8_SINT: return MTL::VertexFormatChar4;
- case Format::R8G8_UNORM: return MTL::VertexFormatUChar2Normalized;
+ case Format::R8G8B8A8_SINT: return MTL::VertexFormatChar4;
+ case Format::R8G8_UNORM: return MTL::VertexFormatUChar2Normalized;
// return VertexFormatUChar3Normalized;
- case Format::R8G8B8A8_UNORM: return MTL::VertexFormatUChar4Normalized;
- case Format::R8G8_SNORM: return MTL::VertexFormatChar2Normalized;
+ case Format::R8G8B8A8_UNORM: return MTL::VertexFormatUChar4Normalized;
+ case Format::R8G8_SNORM: return MTL::VertexFormatChar2Normalized;
// return VertexFormatChar3Normalized
- case Format::R8G8B8A8_SNORM: return MTL::VertexFormatChar4Normalized;
- case Format::R16G16_UINT: return MTL::VertexFormatUShort2;
+ case Format::R8G8B8A8_SNORM: return MTL::VertexFormatChar4Normalized;
+ case Format::R16G16_UINT: return MTL::VertexFormatUShort2;
// return VertexFormatUShort3;
- case Format::R16G16B16A16_UINT: return MTL::VertexFormatUShort4;
- case Format::R16G16_SINT: return MTL::VertexFormatShort2;
+ case Format::R16G16B16A16_UINT: return MTL::VertexFormatUShort4;
+ case Format::R16G16_SINT: return MTL::VertexFormatShort2;
// return VertexFormatShort3;
- case Format::R16G16B16A16_SINT: return MTL::VertexFormatShort4;
- case Format::R16G16_UNORM: return MTL::VertexFormatUShort2Normalized;
+ case Format::R16G16B16A16_SINT: return MTL::VertexFormatShort4;
+ case Format::R16G16_UNORM: return MTL::VertexFormatUShort2Normalized;
// return VertexFormatUShort3Normalized;
- case Format::R16G16B16A16_UNORM: return MTL::VertexFormatUShort4Normalized;
- case Format::R16G16_SNORM: return MTL::VertexFormatShort2Normalized;
+ case Format::R16G16B16A16_UNORM: return MTL::VertexFormatUShort4Normalized;
+ case Format::R16G16_SNORM: return MTL::VertexFormatShort2Normalized;
// return VertexFormatShort3Normalized;
- case Format::R16G16B16A16_SNORM: return MTL::VertexFormatShort4Normalized;
- case Format::R16G16_FLOAT: return MTL::VertexFormatHalf2;
+ case Format::R16G16B16A16_SNORM: return MTL::VertexFormatShort4Normalized;
+ case Format::R16G16_FLOAT: return MTL::VertexFormatHalf2;
// return VertexFormatHalf3;
- case Format::R16G16B16A16_FLOAT: return MTL::VertexFormatHalf4;
- case Format::R32_FLOAT: return MTL::VertexFormatFloat;
- case Format::R32G32_FLOAT: return MTL::VertexFormatFloat2;
- case Format::R32G32B32_FLOAT: return MTL::VertexFormatFloat3;
- case Format::R32G32B32A32_FLOAT: return MTL::VertexFormatFloat4;
- case Format::R32_SINT: return MTL::VertexFormatInt;
- case Format::R32G32_SINT: return MTL::VertexFormatInt2;
- case Format::R32G32B32_SINT: return MTL::VertexFormatInt3;
- case Format::R32G32B32A32_SINT: return MTL::VertexFormatInt4;
- case Format::R32_UINT: return MTL::VertexFormatUInt;
- case Format::R32G32_UINT: return MTL::VertexFormatUInt2;
- case Format::R32G32B32_UINT: return MTL::VertexFormatUInt3;
- case Format::R32G32B32A32_UINT: return MTL::VertexFormatUInt4;
+ case Format::R16G16B16A16_FLOAT: return MTL::VertexFormatHalf4;
+ case Format::R32_FLOAT: return MTL::VertexFormatFloat;
+ case Format::R32G32_FLOAT: return MTL::VertexFormatFloat2;
+ case Format::R32G32B32_FLOAT: return MTL::VertexFormatFloat3;
+ case Format::R32G32B32A32_FLOAT: return MTL::VertexFormatFloat4;
+ case Format::R32_SINT: return MTL::VertexFormatInt;
+ case Format::R32G32_SINT: return MTL::VertexFormatInt2;
+ case Format::R32G32B32_SINT: return MTL::VertexFormatInt3;
+ case Format::R32G32B32A32_SINT: return MTL::VertexFormatInt4;
+ case Format::R32_UINT: return MTL::VertexFormatUInt;
+ case Format::R32G32_UINT: return MTL::VertexFormatUInt2;
+ case Format::R32G32B32_UINT: return MTL::VertexFormatUInt3;
+ case Format::R32G32B32A32_UINT: return MTL::VertexFormatUInt4;
// return VertexFormatInt1010102Normalized;
- case Format::R10G10B10A2_UNORM: return MTL::VertexFormatUInt1010102Normalized;
- case Format::B4G4R4A4_UNORM: return MTL::VertexFormatUChar4Normalized_BGRA;
- case Format::R8_UINT: return MTL::VertexFormatUChar;
- case Format::R8_SINT: return MTL::VertexFormatChar;
- case Format::R8_UNORM: return MTL::VertexFormatUCharNormalized;
- case Format::R8_SNORM: return MTL::VertexFormatCharNormalized;
- case Format::R16_UINT: return MTL::VertexFormatUShort;
- case Format::R16_SINT: return MTL::VertexFormatShort;
- case Format::R16_UNORM: return MTL::VertexFormatUShortNormalized;
- case Format::R16_SNORM: return MTL::VertexFormatShortNormalized;
- case Format::R16_FLOAT: return MTL::VertexFormatHalf;
- case Format::R11G11B10_FLOAT: return MTL::VertexFormatFloatRG11B10;
- case Format::R9G9B9E5_SHAREDEXP: return MTL::VertexFormatFloatRGB9E5;
- default: return MTL::VertexFormatInvalid;
+ case Format::R10G10B10A2_UNORM: return MTL::VertexFormatUInt1010102Normalized;
+ case Format::B4G4R4A4_UNORM: return MTL::VertexFormatUChar4Normalized_BGRA;
+ case Format::R8_UINT: return MTL::VertexFormatUChar;
+ case Format::R8_SINT: return MTL::VertexFormatChar;
+ case Format::R8_UNORM: return MTL::VertexFormatUCharNormalized;
+ case Format::R8_SNORM: return MTL::VertexFormatCharNormalized;
+ case Format::R16_UINT: return MTL::VertexFormatUShort;
+ case Format::R16_SINT: return MTL::VertexFormatShort;
+ case Format::R16_UNORM: return MTL::VertexFormatUShortNormalized;
+ case Format::R16_SNORM: return MTL::VertexFormatShortNormalized;
+ case Format::R16_FLOAT: return MTL::VertexFormatHalf;
+ case Format::R11G11B10_FLOAT: return MTL::VertexFormatFloatRG11B10;
+ case Format::R9G9B9E5_SHAREDEXP: return MTL::VertexFormatFloatRGB9E5;
+ default: return MTL::VertexFormatInvalid;
}
}
@@ -183,10 +185,8 @@ bool MetalUtil::isDepthFormat(MTL::PixelFormat format)
case MTL::PixelFormatDepth16Unorm:
case MTL::PixelFormatDepth32Float:
case MTL::PixelFormatDepth24Unorm_Stencil8:
- case MTL::PixelFormatDepth32Float_Stencil8:
- return true;
- default:
- return false;
+ case MTL::PixelFormatDepth32Float_Stencil8: return true;
+ default: return false;
}
}
@@ -198,10 +198,8 @@ bool MetalUtil::isStencilFormat(MTL::PixelFormat format)
case MTL::PixelFormatDepth24Unorm_Stencil8:
case MTL::PixelFormatDepth32Float_Stencil8:
case MTL::PixelFormatX32_Stencil8:
- case MTL::PixelFormatX24_Stencil8:
- return true;
- default:
- return false;
+ case MTL::PixelFormatX24_Stencil8: return true;
+ default: return false;
}
}
@@ -209,12 +207,9 @@ MTL::SamplerMinMagFilter MetalUtil::translateSamplerMinMagFilter(TextureFilterin
{
switch (mode)
{
- case TextureFilteringMode::Point:
- return MTL::SamplerMinMagFilterNearest;
- case TextureFilteringMode::Linear:
- return MTL::SamplerMinMagFilterLinear;
- default:
- return MTL::SamplerMinMagFilter(0);
+ case TextureFilteringMode::Point: return MTL::SamplerMinMagFilterNearest;
+ case TextureFilteringMode::Linear: return MTL::SamplerMinMagFilterLinear;
+ default: return MTL::SamplerMinMagFilter(0);
}
}
@@ -222,31 +217,22 @@ MTL::SamplerMipFilter MetalUtil::translateSamplerMipFilter(TextureFilteringMode
{
switch (mode)
{
- case TextureFilteringMode::Point:
- return MTL::SamplerMipFilterNearest;
- case TextureFilteringMode::Linear:
- return MTL::SamplerMipFilterLinear;
- default:
- return MTL::SamplerMipFilter(0);
- }
+ case TextureFilteringMode::Point: return MTL::SamplerMipFilterNearest;
+ case TextureFilteringMode::Linear: return MTL::SamplerMipFilterLinear;
+ default: return MTL::SamplerMipFilter(0);
+ }
}
MTL::SamplerAddressMode MetalUtil::translateSamplerAddressMode(TextureAddressingMode mode)
{
switch (mode)
{
- case TextureAddressingMode::Wrap:
- return MTL::SamplerAddressModeRepeat;
- case TextureAddressingMode::ClampToEdge:
- return MTL::SamplerAddressModeClampToEdge;
- case TextureAddressingMode::ClampToBorder:
- return MTL::SamplerAddressModeClampToBorderColor;
- case TextureAddressingMode::MirrorRepeat:
- return MTL::SamplerAddressModeMirrorRepeat;
- case TextureAddressingMode::MirrorOnce:
- return MTL::SamplerAddressModeMirrorClampToEdge;
- default:
- return MTL::SamplerAddressMode(0);
+ case TextureAddressingMode::Wrap: return MTL::SamplerAddressModeRepeat;
+ case TextureAddressingMode::ClampToEdge: return MTL::SamplerAddressModeClampToEdge;
+ case TextureAddressingMode::ClampToBorder: return MTL::SamplerAddressModeClampToBorderColor;
+ case TextureAddressingMode::MirrorRepeat: return MTL::SamplerAddressModeMirrorRepeat;
+ case TextureAddressingMode::MirrorOnce: return MTL::SamplerAddressModeMirrorClampToEdge;
+ default: return MTL::SamplerAddressMode(0);
}
}
@@ -254,24 +240,15 @@ MTL::CompareFunction MetalUtil::translateCompareFunction(ComparisonFunc func)
{
switch (func)
{
- case ComparisonFunc::Never:
- return MTL::CompareFunctionNever;
- case ComparisonFunc::Less:
- return MTL::CompareFunctionLess;
- case ComparisonFunc::Equal:
- return MTL::CompareFunctionEqual;
- case ComparisonFunc::LessEqual:
- return MTL::CompareFunctionLessEqual;
- case ComparisonFunc::Greater:
- return MTL::CompareFunctionGreater;
- case ComparisonFunc::NotEqual:
- return MTL::CompareFunctionNotEqual;
- case ComparisonFunc::GreaterEqual:
- return MTL::CompareFunctionGreaterEqual;
- case ComparisonFunc::Always:
- return MTL::CompareFunctionAlways;
- default:
- return MTL::CompareFunction(0);
+ case ComparisonFunc::Never: return MTL::CompareFunctionNever;
+ case ComparisonFunc::Less: return MTL::CompareFunctionLess;
+ case ComparisonFunc::Equal: return MTL::CompareFunctionEqual;
+ case ComparisonFunc::LessEqual: return MTL::CompareFunctionLessEqual;
+ case ComparisonFunc::Greater: return MTL::CompareFunctionGreater;
+ case ComparisonFunc::NotEqual: return MTL::CompareFunctionNotEqual;
+ case ComparisonFunc::GreaterEqual: return MTL::CompareFunctionGreaterEqual;
+ case ComparisonFunc::Always: return MTL::CompareFunctionAlways;
+ default: return MTL::CompareFunction(0);
}
}
@@ -279,24 +256,15 @@ MTL::StencilOperation MetalUtil::translateStencilOperation(StencilOp op)
{
switch (op)
{
- case StencilOp::Keep:
- return MTL::StencilOperationKeep;
- case StencilOp::Zero:
- return MTL::StencilOperationZero;
- case StencilOp::Replace:
- return MTL::StencilOperationReplace;
- case StencilOp::IncrementSaturate:
- return MTL::StencilOperationIncrementClamp;
- case StencilOp::DecrementSaturate:
- return MTL::StencilOperationDecrementClamp;
- case StencilOp::Invert:
- return MTL::StencilOperationInvert;
- case StencilOp::IncrementWrap:
- return MTL::StencilOperationIncrementWrap;
- case StencilOp::DecrementWrap:
- return MTL::StencilOperationDecrementWrap;
- default:
- return MTL::StencilOperation(0);
+ case StencilOp::Keep: return MTL::StencilOperationKeep;
+ case StencilOp::Zero: return MTL::StencilOperationZero;
+ case StencilOp::Replace: return MTL::StencilOperationReplace;
+ case StencilOp::IncrementSaturate: return MTL::StencilOperationIncrementClamp;
+ case StencilOp::DecrementSaturate: return MTL::StencilOperationDecrementClamp;
+ case StencilOp::Invert: return MTL::StencilOperationInvert;
+ case StencilOp::IncrementWrap: return MTL::StencilOperationIncrementWrap;
+ case StencilOp::DecrementWrap: return MTL::StencilOperationDecrementWrap;
+ default: return MTL::StencilOperation(0);
}
}
@@ -304,12 +272,9 @@ MTL::VertexStepFunction MetalUtil::translateVertexStepFunction(InputSlotClass sl
{
switch (slotClass)
{
- case InputSlotClass::PerVertex:
- return MTL::VertexStepFunctionPerVertex;
- case InputSlotClass::PerInstance:
- return MTL::VertexStepFunctionPerInstance;
- default:
- return MTL::VertexStepFunctionPerVertex;
+ case InputSlotClass::PerVertex: return MTL::VertexStepFunctionPerVertex;
+ case InputSlotClass::PerInstance: return MTL::VertexStepFunctionPerInstance;
+ default: return MTL::VertexStepFunctionPerVertex;
}
}
@@ -317,18 +282,12 @@ MTL::PrimitiveType MetalUtil::translatePrimitiveType(PrimitiveTopology topology)
{
switch (topology)
{
- case PrimitiveTopology::TriangleList:
- return MTL::PrimitiveTypeTriangle;
- case PrimitiveTopology::TriangleStrip:
- return MTL::PrimitiveTypeTriangleStrip;
- case PrimitiveTopology::PointList:
- return MTL::PrimitiveTypePoint;
- case PrimitiveTopology::LineList:
- return MTL::PrimitiveTypeLine;
- case PrimitiveTopology::LineStrip:
- return MTL::PrimitiveTypeLineStrip;
- default:
- return MTL::PrimitiveType(0);
+ case PrimitiveTopology::TriangleList: return MTL::PrimitiveTypeTriangle;
+ case PrimitiveTopology::TriangleStrip: return MTL::PrimitiveTypeTriangleStrip;
+ case PrimitiveTopology::PointList: return MTL::PrimitiveTypePoint;
+ case PrimitiveTopology::LineList: return MTL::PrimitiveTypeLine;
+ case PrimitiveTopology::LineStrip: return MTL::PrimitiveTypeLineStrip;
+ default: return MTL::PrimitiveType(0);
}
}
@@ -336,15 +295,11 @@ MTL::PrimitiveTopologyClass MetalUtil::translatePrimitiveTopologyClass(Primitive
{
switch (type)
{
- case PrimitiveType::Point:
- return MTL::PrimitiveTopologyClassPoint;
- case PrimitiveType::Line:
- return MTL::PrimitiveTopologyClassLine;
- case PrimitiveType::Triangle:
- return MTL::PrimitiveTopologyClassTriangle;
+ case PrimitiveType::Point: return MTL::PrimitiveTopologyClassPoint;
+ case PrimitiveType::Line: return MTL::PrimitiveTopologyClassLine;
+ case PrimitiveType::Triangle: return MTL::PrimitiveTopologyClassTriangle;
case PrimitiveType::Patch:
- default:
- return MTL::PrimitiveTopologyClassUnspecified;
+ default: return MTL::PrimitiveTopologyClassUnspecified;
}
}
@@ -352,42 +307,24 @@ MTL::BlendFactor MetalUtil::translateBlendFactor(BlendFactor factor)
{
switch (factor)
{
- case BlendFactor::Zero:
- return MTL::BlendFactorZero;
- case BlendFactor::One:
- return MTL::BlendFactorOne;
- case BlendFactor::SrcColor:
- return MTL::BlendFactorSourceColor;
- case BlendFactor::InvSrcColor:
- return MTL::BlendFactorOneMinusSourceColor;
- case BlendFactor::SrcAlpha:
- return MTL::BlendFactorSourceAlpha;
- case BlendFactor::InvSrcAlpha:
- return MTL::BlendFactorOneMinusSourceAlpha;
- case BlendFactor::DestAlpha:
- return MTL::BlendFactorDestinationAlpha;
- case BlendFactor::InvDestAlpha:
- return MTL::BlendFactorOneMinusDestinationAlpha;
- case BlendFactor::DestColor:
- return MTL::BlendFactorDestinationColor;
- case BlendFactor::InvDestColor:
- return MTL::BlendFactorOneMinusDestinationColor;
- case BlendFactor::SrcAlphaSaturate:
- return MTL::BlendFactorSourceAlphaSaturated;
- case BlendFactor::BlendColor:
- return MTL::BlendFactorBlendColor;
- case BlendFactor::InvBlendColor:
- return MTL::BlendFactorOneMinusBlendColor;
- case BlendFactor::SecondarySrcColor:
- return MTL::BlendFactorSource1Color;
- case BlendFactor::InvSecondarySrcColor:
- return MTL::BlendFactorOneMinusSource1Color;
- case BlendFactor::SecondarySrcAlpha:
- return MTL::BlendFactorSource1Alpha;
- case BlendFactor::InvSecondarySrcAlpha:
- return MTL::BlendFactorOneMinusSource1Alpha;
- default:
- return MTL::BlendFactor(0);
+ case BlendFactor::Zero: return MTL::BlendFactorZero;
+ case BlendFactor::One: return MTL::BlendFactorOne;
+ case BlendFactor::SrcColor: return MTL::BlendFactorSourceColor;
+ case BlendFactor::InvSrcColor: return MTL::BlendFactorOneMinusSourceColor;
+ case BlendFactor::SrcAlpha: return MTL::BlendFactorSourceAlpha;
+ case BlendFactor::InvSrcAlpha: return MTL::BlendFactorOneMinusSourceAlpha;
+ case BlendFactor::DestAlpha: return MTL::BlendFactorDestinationAlpha;
+ case BlendFactor::InvDestAlpha: return MTL::BlendFactorOneMinusDestinationAlpha;
+ case BlendFactor::DestColor: return MTL::BlendFactorDestinationColor;
+ case BlendFactor::InvDestColor: return MTL::BlendFactorOneMinusDestinationColor;
+ case BlendFactor::SrcAlphaSaturate: return MTL::BlendFactorSourceAlphaSaturated;
+ case BlendFactor::BlendColor: return MTL::BlendFactorBlendColor;
+ case BlendFactor::InvBlendColor: return MTL::BlendFactorOneMinusBlendColor;
+ case BlendFactor::SecondarySrcColor: return MTL::BlendFactorSource1Color;
+ case BlendFactor::InvSecondarySrcColor: return MTL::BlendFactorOneMinusSource1Color;
+ case BlendFactor::SecondarySrcAlpha: return MTL::BlendFactorSource1Alpha;
+ case BlendFactor::InvSecondarySrcAlpha: return MTL::BlendFactorOneMinusSource1Alpha;
+ default: return MTL::BlendFactor(0);
}
}
@@ -395,18 +332,12 @@ MTL::BlendOperation MetalUtil::translateBlendOperation(BlendOp op)
{
switch (op)
{
- case BlendOp::Add:
- return MTL::BlendOperationAdd;
- case BlendOp::Subtract:
- return MTL::BlendOperationSubtract;
- case BlendOp::ReverseSubtract:
- return MTL::BlendOperationReverseSubtract;
- case BlendOp::Min:
- return MTL::BlendOperationMin;
- case BlendOp::Max:
- return MTL::BlendOperationMax;
- default:
- return MTL::BlendOperation(0);
+ case BlendOp::Add: return MTL::BlendOperationAdd;
+ case BlendOp::Subtract: return MTL::BlendOperationSubtract;
+ case BlendOp::ReverseSubtract: return MTL::BlendOperationReverseSubtract;
+ case BlendOp::Min: return MTL::BlendOperationMin;
+ case BlendOp::Max: return MTL::BlendOperationMax;
+ default: return MTL::BlendOperation(0);
}
}
@@ -428,12 +359,9 @@ MTL::Winding MetalUtil::translateWinding(FrontFaceMode mode)
{
switch (mode)
{
- case FrontFaceMode::CounterClockwise:
- return MTL::WindingCounterClockwise;
- case FrontFaceMode::Clockwise:
- return MTL::WindingClockwise;
- default:
- return MTL::Winding(0);
+ case FrontFaceMode::CounterClockwise: return MTL::WindingCounterClockwise;
+ case FrontFaceMode::Clockwise: return MTL::WindingClockwise;
+ default: return MTL::Winding(0);
}
}
@@ -441,14 +369,10 @@ MTL::CullMode MetalUtil::translateCullMode(CullMode mode)
{
switch (mode)
{
- case CullMode::None:
- return MTL::CullModeNone;
- case CullMode::Front:
- return MTL::CullModeFront;
- case CullMode::Back:
- return MTL::CullModeBack;
- default:
- return MTL::CullMode(0);
+ case CullMode::None: return MTL::CullModeNone;
+ case CullMode::Front: return MTL::CullModeFront;
+ case CullMode::Back: return MTL::CullModeBack;
+ default: return MTL::CullMode(0);
}
}
@@ -456,12 +380,9 @@ MTL::TriangleFillMode MetalUtil::translateTriangleFillMode(FillMode mode)
{
switch (mode)
{
- case FillMode::Solid:
- return MTL::TriangleFillModeFill;
- case FillMode::Wireframe:
- return MTL::TriangleFillModeLines;
- default:
- return MTL::TriangleFillMode(0);
+ case FillMode::Solid: return MTL::TriangleFillModeFill;
+ case FillMode::Wireframe: return MTL::TriangleFillModeLines;
+ default: return MTL::TriangleFillMode(0);
}
}
diff --git a/tools/gfx/metal/metal-util.h b/tools/gfx/metal/metal-util.h
index 279f0c67e..bcf988c3b 100644
--- a/tools/gfx/metal/metal-util.h
+++ b/tools/gfx/metal/metal-util.h
@@ -5,20 +5,28 @@
#include "metal-api.h"
#include "slang-gfx.h"
-namespace gfx {
+namespace gfx
+{
// Utility functions for Metal
-struct MetalUtil
+struct MetalUtil
{
- static NS::SharedPtr<NS::String> createString(const char* str, NS::StringEncoding encoding = NS::UTF8StringEncoding)
+ static NS::SharedPtr<NS::String> createString(
+ const char* str,
+ NS::StringEncoding encoding = NS::UTF8StringEncoding)
{
- NS::SharedPtr<NS::String> nsString = NS::TransferPtr(NS::String::alloc()->init(str, encoding));
+ NS::SharedPtr<NS::String> nsString =
+ NS::TransferPtr(NS::String::alloc()->init(str, encoding));
return nsString;
}
- static NS::SharedPtr<NS::String> createStringView(void* bytes, size_t len, NS::StringEncoding encoding = NS::UTF8StringEncoding)
+ static NS::SharedPtr<NS::String> createStringView(
+ void* bytes,
+ size_t len,
+ NS::StringEncoding encoding = NS::UTF8StringEncoding)
{
- NS::SharedPtr<NS::String> nsString = NS::TransferPtr(NS::String::alloc()->init(bytes, len, encoding, false));
+ NS::SharedPtr<NS::String> nsString =
+ NS::TransferPtr(NS::String::alloc()->init(bytes, len, encoding, false));
return nsString;
}
@@ -31,7 +39,7 @@ struct MetalUtil
static MTL::SamplerMinMagFilter translateSamplerMinMagFilter(TextureFilteringMode mode);
static MTL::SamplerMipFilter translateSamplerMipFilter(TextureFilteringMode mode);
static MTL::SamplerAddressMode translateSamplerAddressMode(TextureAddressingMode mode);
- static MTL::CompareFunction translateCompareFunction(ComparisonFunc func);
+ static MTL::CompareFunction translateCompareFunction(ComparisonFunc func);
static MTL::StencilOperation translateStencilOperation(StencilOp op);
static MTL::VertexStepFunction translateVertexStepFunction(InputSlotClass slotClass);
@@ -46,7 +54,6 @@ struct MetalUtil
static MTL::Winding translateWinding(FrontFaceMode mode);
static MTL::CullMode translateCullMode(CullMode mode);
static MTL::TriangleFillMode translateTriangleFillMode(FillMode mode);
-
};
struct ScopedAutoreleasePool
diff --git a/tools/gfx/metal/metal-vertex-layout.cpp b/tools/gfx/metal/metal-vertex-layout.cpp
index 686f3ad0c..722d5396d 100644
--- a/tools/gfx/metal/metal-vertex-layout.cpp
+++ b/tools/gfx/metal/metal-vertex-layout.cpp
@@ -1,5 +1,6 @@
// metal-vertex-layout.cpp
#include "metal-vertex-layout.h"
+
#include "metal-util.h"
namespace gfx
@@ -14,7 +15,8 @@ Result InputLayoutImpl::init(const IInputLayout::Desc& desc)
{
for (Index i = 0; i < desc.inputElementCount; i++)
{
- if (MetalUtil::translateVertexFormat(desc.inputElements[i].format) == MTL::VertexFormatInvalid)
+ if (MetalUtil::translateVertexFormat(desc.inputElements[i].format) ==
+ MTL::VertexFormatInvalid)
{
return SLANG_E_INVALID_ARG;
}
@@ -27,9 +29,11 @@ Result InputLayoutImpl::init(const IInputLayout::Desc& desc)
return SLANG_OK;
}
-NS::SharedPtr<MTL::VertexDescriptor> InputLayoutImpl::createVertexDescriptor(NS::UInteger vertexBufferIndexOffset)
+NS::SharedPtr<MTL::VertexDescriptor> InputLayoutImpl::createVertexDescriptor(
+ NS::UInteger vertexBufferIndexOffset)
{
- NS::SharedPtr<MTL::VertexDescriptor> vertexDescriptor = NS::TransferPtr(MTL::VertexDescriptor::alloc()->init());
+ NS::SharedPtr<MTL::VertexDescriptor> vertexDescriptor =
+ NS::TransferPtr(MTL::VertexDescriptor::alloc()->init());
for (Index i = 0; i < m_inputElements.getCount(); i++)
{
@@ -44,9 +48,13 @@ NS::SharedPtr<MTL::VertexDescriptor> InputLayoutImpl::createVertexDescriptor(NS:
for (Index i = 0; i < m_vertexStreams.getCount(); i++)
{
const auto& vertexStream = m_vertexStreams[i];
- MTL::VertexBufferLayoutDescriptor* desc = vertexDescriptor->layouts()->object(i + vertexBufferIndexOffset);
+ MTL::VertexBufferLayoutDescriptor* desc =
+ vertexDescriptor->layouts()->object(i + vertexBufferIndexOffset);
desc->setStepFunction(MetalUtil::translateVertexStepFunction(vertexStream.slotClass));
- desc->setStepRate(vertexStream.slotClass == InputSlotClass::PerVertex ? 1 : vertexStream.instanceDataStepRate);
+ desc->setStepRate(
+ vertexStream.slotClass == InputSlotClass::PerVertex
+ ? 1
+ : vertexStream.instanceDataStepRate);
desc->setStride(vertexStream.stride);
}
diff --git a/tools/gfx/metal/metal-vertex-layout.h b/tools/gfx/metal/metal-vertex-layout.h
index 5cfdf3dc6..26af7f496 100644
--- a/tools/gfx/metal/metal-vertex-layout.h
+++ b/tools/gfx/metal/metal-vertex-layout.h
@@ -18,7 +18,8 @@ public:
List<VertexStreamDesc> m_vertexStreams;
Result init(const IInputLayout::Desc& desc);
- NS::SharedPtr<MTL::VertexDescriptor> createVertexDescriptor(NS::UInteger vertexBufferIndexOffset);
+ NS::SharedPtr<MTL::VertexDescriptor> createVertexDescriptor(
+ NS::UInteger vertexBufferIndexOffset);
};
} // namespace metal
diff --git a/tools/gfx/mutable-shader-object.h b/tools/gfx/mutable-shader-object.h
index 1864be158..420ba08fe 100644
--- a/tools/gfx/mutable-shader-object.h
+++ b/tools/gfx/mutable-shader-object.h
@@ -1,390 +1,392 @@
#pragma once
-#include "slang-gfx.h"
#include "core/slang-basic.h"
#include "core/slang-com-object.h"
#include "renderer-shared.h"
+#include "slang-gfx.h"
namespace gfx
{
- class ShaderObjectLayoutBase;
-
- template<typename T>
- class VersionedObjectPool
- {
- public:
- struct ObjectVersion
- {
- Slang::RefPtr<T> object;
- Slang::RefPtr<TransientResourceHeapBase> transientHeap;
- uint64_t transientHeapVersion;
- bool canRecycle()
- {
- return (transientHeap->getVersion() != transientHeapVersion);
- }
- };
- Slang::List<ObjectVersion> objects;
- SlangInt lastAllocationIndex = -1;
- ObjectVersion& allocate(TransientResourceHeapBase* currentTransientHeap)
- {
- for (SlangInt i = 0; i < objects.getCount(); i++)
- {
- auto& object = objects[i];
- if (object.canRecycle())
- {
- object.transientHeap = currentTransientHeap;
- object.transientHeapVersion = currentTransientHeap->getVersion();
- lastAllocationIndex = i;
- return object;
- }
- }
- ObjectVersion v;
- v.transientHeap = currentTransientHeap;
- v.transientHeapVersion = currentTransientHeap->getVersion();
- objects.add(v);
- lastAllocationIndex = objects.getCount() - 1;
- return objects.getLast();
- }
- ObjectVersion& getLastAllocation() { return objects[lastAllocationIndex]; }
- };
+class ShaderObjectLayoutBase;
- class MutableShaderObjectData
+template<typename T>
+class VersionedObjectPool
+{
+public:
+ struct ObjectVersion
{
- public:
- // Any "ordinary" / uniform data for this object
- Slang::List<char> m_ordinaryData;
-
- bool m_dirty = true;
-
- Slang::Index getCount() { return m_ordinaryData.getCount(); }
- void setCount(Slang::Index count) { m_ordinaryData.setCount(count); }
- char* getBuffer() { return m_ordinaryData.getBuffer(); }
- void markDirty() { m_dirty = true; }
-
- // We don't actually create any GPU buffers here, since they will be handled
- // by the immutable shader objects once the user calls `getCurrentVersion`.
- ResourceViewBase* getResourceView(
- RendererBase* device,
- slang::TypeLayoutReflection* elementLayout,
- slang::BindingType bindingType)
- {
- return nullptr;
- }
+ Slang::RefPtr<T> object;
+ Slang::RefPtr<TransientResourceHeapBase> transientHeap;
+ uint64_t transientHeapVersion;
+ bool canRecycle() { return (transientHeap->getVersion() != transientHeapVersion); }
};
-
- template<typename TShaderObject, typename TShaderObjectLayoutImpl>
- class MutableShaderObject : public ShaderObjectBaseImpl<
- TShaderObject,
- TShaderObjectLayoutImpl,
- MutableShaderObjectData>
+ Slang::List<ObjectVersion> objects;
+ SlangInt lastAllocationIndex = -1;
+ ObjectVersion& allocate(TransientResourceHeapBase* currentTransientHeap)
{
- typedef ShaderObjectBaseImpl<
- TShaderObject,
- TShaderObjectLayoutImpl,
- MutableShaderObjectData> Super;
- protected:
- Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<ResourceViewBase>> m_resources;
- Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<SamplerStateBase>> m_samplers;
- Slang::OrderedHashSet<ShaderOffset> m_objectOffsets;
- VersionedObjectPool<ShaderObjectBase> m_shaderObjectVersions;
- bool m_dirty = true;
- bool isDirty()
+ for (SlangInt i = 0; i < objects.getCount(); i++)
{
- if (m_dirty) return true;
- if (this->m_data.m_dirty) return true;
- for (auto& object : this->m_objects)
+ auto& object = objects[i];
+ if (object.canRecycle())
{
- if (object && object->isDirty())
- return true;
+ object.transientHeap = currentTransientHeap;
+ object.transientHeapVersion = currentTransientHeap->getVersion();
+ lastAllocationIndex = i;
+ return object;
}
- return false;
- }
-
- void markDirty()
- {
- m_dirty = true;
- }
- public:
- Result init(RendererBase* device, ShaderObjectLayoutBase* layout)
- {
- this->m_device = device;
- auto layoutImpl = static_cast<TShaderObjectLayoutImpl*>(layout);
- this->m_layout = layoutImpl;
- Slang::Index subObjectCount = layoutImpl->getSubObjectCount();
- this->m_objects.setCount(subObjectCount);
- auto dataSize = layoutImpl->getElementTypeLayout()->getSize();
- assert(dataSize >= 0);
- this->m_data.setCount(dataSize);
- memset(this->m_data.getBuffer(), 0, dataSize);
- return SLANG_OK;
- }
- public:
- virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override
- {
- return this->m_data.getBuffer();
- }
- virtual SLANG_NO_THROW size_t SLANG_MCALL getSize() override
- {
- return this->m_data.getCount();
- }
- virtual SLANG_NO_THROW Result SLANG_MCALL setData(ShaderOffset const& offset, void const* data, size_t size) override
- {
- if (!size) return SLANG_OK;
- if (SlangInt(offset.uniformOffset + size) > this->m_data.getCount())
- this->m_data.setCount(offset.uniformOffset + size);
- memcpy(this->m_data.getBuffer() + offset.uniformOffset, data, size);
- this->m_data.markDirty();
- markDirty();
- return SLANG_OK;
}
+ ObjectVersion v;
+ v.transientHeap = currentTransientHeap;
+ v.transientHeapVersion = currentTransientHeap->getVersion();
+ objects.add(v);
+ lastAllocationIndex = objects.getCount() - 1;
+ return objects.getLast();
+ }
+ ObjectVersion& getLastAllocation() { return objects[lastAllocationIndex]; }
+};
+
+class MutableShaderObjectData
+{
+public:
+ // Any "ordinary" / uniform data for this object
+ Slang::List<char> m_ordinaryData;
+
+ bool m_dirty = true;
+
+ Slang::Index getCount() { return m_ordinaryData.getCount(); }
+ void setCount(Slang::Index count) { m_ordinaryData.setCount(count); }
+ char* getBuffer() { return m_ordinaryData.getBuffer(); }
+ void markDirty() { m_dirty = true; }
+
+ // We don't actually create any GPU buffers here, since they will be handled
+ // by the immutable shader objects once the user calls `getCurrentVersion`.
+ ResourceViewBase* getResourceView(
+ RendererBase* device,
+ slang::TypeLayoutReflection* elementLayout,
+ slang::BindingType bindingType)
+ {
+ return nullptr;
+ }
+};
- virtual SLANG_NO_THROW Result SLANG_MCALL
- setObject(ShaderOffset const& offset, IShaderObject* object) override
+template<typename TShaderObject, typename TShaderObjectLayoutImpl>
+class MutableShaderObject
+ : public ShaderObjectBaseImpl<TShaderObject, TShaderObjectLayoutImpl, MutableShaderObjectData>
+{
+ typedef ShaderObjectBaseImpl<TShaderObject, TShaderObjectLayoutImpl, MutableShaderObjectData>
+ Super;
+
+protected:
+ Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<ResourceViewBase>> m_resources;
+ Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<SamplerStateBase>> m_samplers;
+ Slang::OrderedHashSet<ShaderOffset> m_objectOffsets;
+ VersionedObjectPool<ShaderObjectBase> m_shaderObjectVersions;
+ bool m_dirty = true;
+ bool isDirty()
+ {
+ if (m_dirty)
+ return true;
+ if (this->m_data.m_dirty)
+ return true;
+ for (auto& object : this->m_objects)
{
- Super::setObject(offset, object);
- m_objectOffsets.add(offset);
- markDirty();
- return SLANG_OK;
+ if (object && object->isDirty())
+ return true;
}
+ return false;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL setResource(ShaderOffset const& offset, IResourceView* resourceView) override
- {
- m_resources[offset] = static_cast<ResourceViewBase*>(resourceView);
- markDirty();
- return SLANG_OK;
- }
+ void markDirty() { m_dirty = true; }
- virtual SLANG_NO_THROW Result SLANG_MCALL setSampler(ShaderOffset const& offset, ISamplerState* sampler) override
- {
- m_samplers[offset] = static_cast<SamplerStateBase*>(sampler);
- markDirty();
+public:
+ Result init(RendererBase* device, ShaderObjectLayoutBase* layout)
+ {
+ this->m_device = device;
+ auto layoutImpl = static_cast<TShaderObjectLayoutImpl*>(layout);
+ this->m_layout = layoutImpl;
+ Slang::Index subObjectCount = layoutImpl->getSubObjectCount();
+ this->m_objects.setCount(subObjectCount);
+ auto dataSize = layoutImpl->getElementTypeLayout()->getSize();
+ assert(dataSize >= 0);
+ this->m_data.setCount(dataSize);
+ memset(this->m_data.getBuffer(), 0, dataSize);
+ return SLANG_OK;
+ }
+
+public:
+ virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override
+ {
+ return this->m_data.getBuffer();
+ }
+ virtual SLANG_NO_THROW size_t SLANG_MCALL getSize() override { return this->m_data.getCount(); }
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setData(ShaderOffset const& offset, void const* data, size_t size) override
+ {
+ if (!size)
return SLANG_OK;
- }
+ if (SlangInt(offset.uniformOffset + size) > this->m_data.getCount())
+ this->m_data.setCount(offset.uniformOffset + size);
+ memcpy(this->m_data.getBuffer() + offset.uniformOffset, data, size);
+ this->m_data.markDirty();
+ markDirty();
+ return SLANG_OK;
+ }
+
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setObject(ShaderOffset const& offset, IShaderObject* object) override
+ {
+ Super::setObject(offset, object);
+ m_objectOffsets.add(offset);
+ markDirty();
+ return SLANG_OK;
+ }
+
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) override
+ {
+ m_resources[offset] = static_cast<ResourceViewBase*>(resourceView);
+ markDirty();
+ return SLANG_OK;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) override
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setSampler(ShaderOffset const& offset, ISamplerState* sampler) override
+ {
+ m_samplers[offset] = static_cast<SamplerStateBase*>(sampler);
+ markDirty();
+ return SLANG_OK;
+ }
+
+ virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) override
+ {
+ m_samplers[offset] = static_cast<SamplerStateBase*>(sampler);
+ m_resources[offset] = static_cast<ResourceViewBase*>(textureView);
+ markDirty();
+ return SLANG_OK;
+ }
+
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getCurrentVersion(ITransientResourceHeap* transientHeap, IShaderObject** outObject) override
+ {
+ if (!isDirty())
{
- m_samplers[offset] = static_cast<SamplerStateBase*>(sampler);
- m_resources[offset] = static_cast<ResourceViewBase*>(textureView);
- markDirty();
+ returnComPtr(outObject, getLastAllocatedShaderObject());
return SLANG_OK;
}
- virtual SLANG_NO_THROW Result SLANG_MCALL getCurrentVersion(
- ITransientResourceHeap* transientHeap, IShaderObject** outObject) override
- {
- if (!isDirty())
- {
- returnComPtr(outObject, getLastAllocatedShaderObject());
- return SLANG_OK;
- }
-
- Slang::RefPtr<ShaderObjectBase> object =
- allocateShaderObject(static_cast<TransientResourceHeapBase*>(transientHeap));
- SLANG_RETURN_ON_FAIL(object->setData(ShaderOffset(), this->m_data.getBuffer(), this->m_data.getCount()));
- for (auto res : m_resources)
- SLANG_RETURN_ON_FAIL(object->setResource(res.key, res.value));
- for (auto sampler : m_samplers)
- SLANG_RETURN_ON_FAIL(object->setSampler(sampler.key, sampler.value));
- for (auto offset : m_objectOffsets)
- {
- if (offset.bindingRangeIndex < 0)
- return SLANG_E_INVALID_ARG;
- auto layout = this->getLayout();
- if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
- return SLANG_E_INVALID_ARG;
- auto bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
-
- auto subObject = this->m_objects[bindingRange.subObjectIndex + offset.bindingArrayIndex];
- if (subObject)
- {
- ComPtr<IShaderObject> subObjectVersion;
- SLANG_RETURN_ON_FAIL(subObject->getCurrentVersion(transientHeap, subObjectVersion.writeRef()));
- SLANG_RETURN_ON_FAIL(object->setObject(offset, subObjectVersion));
- }
- }
- m_dirty = false;
- this->m_data.m_dirty = false;
- returnComPtr(outObject, object);
- return SLANG_OK;
- }
- public:
- Slang::RefPtr<ShaderObjectBase> allocateShaderObject(TransientResourceHeapBase* transientHeap)
- {
- auto& version = m_shaderObjectVersions.allocate(transientHeap);
- if (!version.object)
+ Slang::RefPtr<ShaderObjectBase> object =
+ allocateShaderObject(static_cast<TransientResourceHeapBase*>(transientHeap));
+ SLANG_RETURN_ON_FAIL(
+ object->setData(ShaderOffset(), this->m_data.getBuffer(), this->m_data.getCount()));
+ for (auto res : m_resources)
+ SLANG_RETURN_ON_FAIL(object->setResource(res.key, res.value));
+ for (auto sampler : m_samplers)
+ SLANG_RETURN_ON_FAIL(object->setSampler(sampler.key, sampler.value));
+ for (auto offset : m_objectOffsets)
+ {
+ if (offset.bindingRangeIndex < 0)
+ return SLANG_E_INVALID_ARG;
+ auto layout = this->getLayout();
+ if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
+ return SLANG_E_INVALID_ARG;
+ auto bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
+
+ auto subObject =
+ this->m_objects[bindingRange.subObjectIndex + offset.bindingArrayIndex];
+ if (subObject)
{
- ComPtr<IShaderObject> shaderObject;
- SLANG_RETURN_NULL_ON_FAIL(this->m_device->createShaderObject(this->m_layout, shaderObject.writeRef()));
- version.object = static_cast<ShaderObjectBase*>(shaderObject.get());
+ ComPtr<IShaderObject> subObjectVersion;
+ SLANG_RETURN_ON_FAIL(
+ subObject->getCurrentVersion(transientHeap, subObjectVersion.writeRef()));
+ SLANG_RETURN_ON_FAIL(object->setObject(offset, subObjectVersion));
}
- return version.object;
- }
- Slang::RefPtr<ShaderObjectBase> getLastAllocatedShaderObject()
- {
- return m_shaderObjectVersions.getLastAllocation().object;
}
- };
+ m_dirty = false;
+ this->m_data.m_dirty = false;
+ returnComPtr(outObject, object);
+ return SLANG_OK;
+ }
- // A proxy shader object to hold mutable shader parameters for global scope and entry-points.
- class MutableRootShaderObject : public ShaderObjectBase
+public:
+ Slang::RefPtr<ShaderObjectBase> allocateShaderObject(TransientResourceHeapBase* transientHeap)
{
- public:
- Slang::List<uint8_t> m_data;
- Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<ResourceViewBase>> m_resources;
- Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<SamplerStateBase>> m_samplers;
- Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<ShaderObjectBase>> m_objects;
- Slang::OrderedDictionary<ShaderOffset, Slang::List<slang::SpecializationArg>> m_specializationArgs;
- Slang::List<Slang::RefPtr<MutableRootShaderObject>> m_entryPoints;
- Slang::RefPtr<BufferResource> m_constantBufferOverride;
- slang::TypeLayoutReflection* m_elementTypeLayout;
-
- MutableRootShaderObject(RendererBase* device, slang::TypeLayoutReflection* entryPointLayout)
- {
- this->m_device = device;
- m_elementTypeLayout = entryPointLayout;
- m_data.setCount(entryPointLayout->getSize());
- memset(m_data.begin(), 0, m_data.getCount());
- }
-
- MutableRootShaderObject(RendererBase* device, Slang::RefPtr<ShaderProgramBase> program)
+ auto& version = m_shaderObjectVersions.allocate(transientHeap);
+ if (!version.object)
{
- this->m_device = device;
- auto programLayout = program->slangGlobalScope->getLayout();
- SlangInt entryPointCount = programLayout->getEntryPointCount();
- for (SlangInt e = 0; e < entryPointCount; ++e)
- {
- auto slangEntryPoint = programLayout->getEntryPointByIndex(e);
- Slang::RefPtr<MutableRootShaderObject> entryPointObject =
- new MutableRootShaderObject(device, slangEntryPoint->getTypeLayout()->getElementTypeLayout());
-
- m_entryPoints.add(entryPointObject);
- }
- m_data.setCount(programLayout->getGlobalParamsTypeLayout()->getSize());
- memset(m_data.begin(), 0, m_data.getCount());
- m_elementTypeLayout = programLayout->getGlobalParamsTypeLayout();
+ ComPtr<IShaderObject> shaderObject;
+ SLANG_RETURN_NULL_ON_FAIL(
+ this->m_device->createShaderObject(this->m_layout, shaderObject.writeRef()));
+ version.object = static_cast<ShaderObjectBase*>(shaderObject.get());
}
+ return version.object;
+ }
+ Slang::RefPtr<ShaderObjectBase> getLastAllocatedShaderObject()
+ {
+ return m_shaderObjectVersions.getLastAllocation().object;
+ }
+};
+// A proxy shader object to hold mutable shader parameters for global scope and entry-points.
+class MutableRootShaderObject : public ShaderObjectBase
+{
+public:
+ Slang::List<uint8_t> m_data;
+ Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<ResourceViewBase>> m_resources;
+ Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<SamplerStateBase>> m_samplers;
+ Slang::OrderedDictionary<ShaderOffset, Slang::RefPtr<ShaderObjectBase>> m_objects;
+ Slang::OrderedDictionary<ShaderOffset, Slang::List<slang::SpecializationArg>>
+ m_specializationArgs;
+ Slang::List<Slang::RefPtr<MutableRootShaderObject>> m_entryPoints;
+ Slang::RefPtr<BufferResource> m_constantBufferOverride;
+ slang::TypeLayoutReflection* m_elementTypeLayout;
+
+ MutableRootShaderObject(RendererBase* device, slang::TypeLayoutReflection* entryPointLayout)
+ {
+ this->m_device = device;
+ m_elementTypeLayout = entryPointLayout;
+ m_data.setCount(entryPointLayout->getSize());
+ memset(m_data.begin(), 0, m_data.getCount());
+ }
- virtual SLANG_NO_THROW slang::TypeLayoutReflection* SLANG_MCALL
- getElementTypeLayout() override
+ MutableRootShaderObject(RendererBase* device, Slang::RefPtr<ShaderProgramBase> program)
+ {
+ this->m_device = device;
+ auto programLayout = program->slangGlobalScope->getLayout();
+ SlangInt entryPointCount = programLayout->getEntryPointCount();
+ for (SlangInt e = 0; e < entryPointCount; ++e)
{
- return m_elementTypeLayout;
- }
+ auto slangEntryPoint = programLayout->getEntryPointByIndex(e);
+ Slang::RefPtr<MutableRootShaderObject> entryPointObject = new MutableRootShaderObject(
+ device,
+ slangEntryPoint->getTypeLayout()->getElementTypeLayout());
- virtual SLANG_NO_THROW ShaderObjectContainerType SLANG_MCALL getContainerType() override
- {
- return ShaderObjectContainerType::None;
+ m_entryPoints.add(entryPointObject);
}
+ m_data.setCount(programLayout->getGlobalParamsTypeLayout()->getSize());
+ memset(m_data.begin(), 0, m_data.getCount());
+ m_elementTypeLayout = programLayout->getGlobalParamsTypeLayout();
+ }
- virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override
- {
- return (GfxCount)m_entryPoints.getCount();
- }
- virtual SLANG_NO_THROW Result SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** entryPoint) override
- {
- returnComPtr(entryPoint, m_entryPoints[index]);
- return SLANG_OK;
- }
+ virtual SLANG_NO_THROW slang::TypeLayoutReflection* SLANG_MCALL getElementTypeLayout() override
+ {
+ return m_elementTypeLayout;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& offset, void const* data, Size size) override
- {
- auto newSize = Slang::Index(size + offset.uniformOffset);
- if (newSize > m_data.getCount())
- m_data.setCount((Slang::Index)newSize);
- memcpy(m_data.begin() + offset.uniformOffset, data, size);
- return SLANG_OK;
- }
+ virtual SLANG_NO_THROW ShaderObjectContainerType SLANG_MCALL getContainerType() override
+ {
+ return ShaderObjectContainerType::None;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL
- getObject(ShaderOffset const& offset, IShaderObject** object) override
- {
- *object = nullptr;
+ virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override
+ {
+ return (GfxCount)m_entryPoints.getCount();
+ }
- Slang::RefPtr<ShaderObjectBase> subObject;
- if (m_objects.tryGetValue(offset, subObject))
- {
- returnComPtr(object, subObject);
- }
- return SLANG_OK;
- }
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getEntryPoint(GfxIndex index, IShaderObject** entryPoint) override
+ {
+ returnComPtr(entryPoint, m_entryPoints[index]);
+ return SLANG_OK;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL
- setObject(ShaderOffset const& offset, IShaderObject* object) override
- {
- m_objects[offset] = static_cast<ShaderObjectBase*>(object);
- return SLANG_OK;
- }
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setData(ShaderOffset const& offset, void const* data, Size size) override
+ {
+ auto newSize = Slang::Index(size + offset.uniformOffset);
+ if (newSize > m_data.getCount())
+ m_data.setCount((Slang::Index)newSize);
+ memcpy(m_data.begin() + offset.uniformOffset, data, size);
+ return SLANG_OK;
+ }
+
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getObject(ShaderOffset const& offset, IShaderObject** object) override
+ {
+ *object = nullptr;
- virtual SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* resourceView) override
+ Slang::RefPtr<ShaderObjectBase> subObject;
+ if (m_objects.tryGetValue(offset, subObject))
{
- m_resources[offset] = static_cast<ResourceViewBase*>(resourceView);
- return SLANG_OK;
+ returnComPtr(object, subObject);
}
+ return SLANG_OK;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL
- setSampler(ShaderOffset const& offset, ISamplerState* sampler) override
- {
- m_samplers[offset] = static_cast<SamplerStateBase*>(sampler);
- return SLANG_OK;
- }
- virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) override
- {
- m_resources[offset] = static_cast<ResourceViewBase*>(textureView);
- m_samplers[offset] = static_cast<SamplerStateBase*>(sampler);
- return SLANG_OK;
- }
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setObject(ShaderOffset const& offset, IShaderObject* object) override
+ {
+ m_objects[offset] = static_cast<ShaderObjectBase*>(object);
+ return SLANG_OK;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL setSpecializationArgs(
- ShaderOffset const& offset,
- const slang::SpecializationArg* args,
- GfxCount count) override
- {
- Slang::List<slang::SpecializationArg> specArgs;
- specArgs.addRange(args, count);
- m_specializationArgs[offset] = specArgs;
- return SLANG_OK;
- }
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) override
+ {
+ m_resources[offset] = static_cast<ResourceViewBase*>(resourceView);
+ return SLANG_OK;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL getCurrentVersion(
- ITransientResourceHeap* transientHeap, IShaderObject** outObject) override
- {
- return SLANG_FAIL;
- }
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setSampler(ShaderOffset const& offset, ISamplerState* sampler) override
+ {
+ m_samplers[offset] = static_cast<SamplerStateBase*>(sampler);
+ return SLANG_OK;
+ }
+ virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) override
+ {
+ m_resources[offset] = static_cast<ResourceViewBase*>(textureView);
+ m_samplers[offset] = static_cast<SamplerStateBase*>(sampler);
+ return SLANG_OK;
+ }
+
+ virtual SLANG_NO_THROW Result SLANG_MCALL setSpecializationArgs(
+ ShaderOffset const& offset,
+ const slang::SpecializationArg* args,
+ GfxCount count) override
+ {
+ Slang::List<slang::SpecializationArg> specArgs;
+ specArgs.addRange(args, count);
+ m_specializationArgs[offset] = specArgs;
+ return SLANG_OK;
+ }
+
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getCurrentVersion(ITransientResourceHeap* transientHeap, IShaderObject** outObject) override
+ {
+ return SLANG_FAIL;
+ }
- virtual SLANG_NO_THROW Result SLANG_MCALL copyFrom(IShaderObject* other, ITransientResourceHeap* transientHeap) override
- {
- auto otherObject = static_cast<MutableRootShaderObject*>(other);
- *this = *otherObject;
- return SLANG_OK;
- }
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ copyFrom(IShaderObject* other, ITransientResourceHeap* transientHeap) override
+ {
+ auto otherObject = static_cast<MutableRootShaderObject*>(other);
+ *this = *otherObject;
+ return SLANG_OK;
+ }
- virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override
- {
- return m_data.begin();
- }
+ virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override { return m_data.begin(); }
- virtual SLANG_NO_THROW Size SLANG_MCALL getSize() override
- {
- return (Size)m_data.getCount();
- }
+ virtual SLANG_NO_THROW Size SLANG_MCALL getSize() override { return (Size)m_data.getCount(); }
- virtual SLANG_NO_THROW Result SLANG_MCALL
- setConstantBufferOverride(IBufferResource* constantBuffer) override
- {
- m_constantBufferOverride = static_cast<BufferResource*>(constantBuffer);
- return SLANG_OK;
- }
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setConstantBufferOverride(IBufferResource* constantBuffer) override
+ {
+ m_constantBufferOverride = static_cast<BufferResource*>(constantBuffer);
+ return SLANG_OK;
+ }
- virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override
- {
- SLANG_UNUSED(args);
- return SLANG_OK;
- }
- };
+ virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override
+ {
+ SLANG_UNUSED(args);
+ return SLANG_OK;
+ }
+};
-}
+} // namespace gfx
diff --git a/tools/gfx/nvapi/nvapi-include.h b/tools/gfx/nvapi/nvapi-include.h
index 513977048..45a8ca77b 100644
--- a/tools/gfx/nvapi/nvapi-include.h
+++ b/tools/gfx/nvapi/nvapi-include.h
@@ -6,20 +6,19 @@
#ifdef GFX_NVAPI
// On windows if we include NVAPI, we must include windows.h first
-# ifdef _WIN32
-# pragma push_macro("WIN32_LEAN_AND_MEAN")
-# pragma push_macro("NOMINMAX")
-# undef WIN32_LEAN_AND_MEAN
-# define WIN32_LEAN_AND_MEAN
-# undef NOMINMAX
-# define NOMINMAX
-# include <windows.h>
-# pragma pop_macro("NOMINMAX")
-# pragma pop_macro("WIN32_LEAN_AND_MEAN")
-# endif
+#ifdef _WIN32
+#pragma push_macro("WIN32_LEAN_AND_MEAN")
+#pragma push_macro("NOMINMAX")
+#undef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#undef NOMINMAX
+#define NOMINMAX
+#include <windows.h>
+#pragma pop_macro("NOMINMAX")
+#pragma pop_macro("WIN32_LEAN_AND_MEAN")
+#endif
-# include <nvapi.h>
-# include <nvShaderExtnEnums.h>
+#include <nvShaderExtnEnums.h>
+#include <nvapi.h>
#endif
-
diff --git a/tools/gfx/nvapi/nvapi-util.cpp b/tools/gfx/nvapi/nvapi-util.cpp
index 63bcc65fc..efb053c07 100644
--- a/tools/gfx/nvapi/nvapi-util.cpp
+++ b/tools/gfx/nvapi/nvapi-util.cpp
@@ -2,11 +2,12 @@
#include "nvapi-include.h"
-namespace gfx {
+namespace gfx
+{
static SlangResult g_initStatus = SLANG_E_UNINITIALIZED;
-/* static */SlangResult NVAPIUtil::initialize()
+/* static */ SlangResult NVAPIUtil::initialize()
{
#ifdef GFX_NVAPI
if (g_initStatus == SLANG_E_UNINITIALIZED)
@@ -22,9 +23,9 @@ static SlangResult g_initStatus = SLANG_E_UNINITIALIZED;
return g_initStatus;
}
-/* static */bool NVAPIUtil::isAvailable()
+/* static */ bool NVAPIUtil::isAvailable()
{
return SLANG_SUCCEEDED(g_initStatus);
}
-} // gfx
+} // namespace gfx
diff --git a/tools/gfx/nvapi/nvapi-util.h b/tools/gfx/nvapi/nvapi-util.h
index 0bcab7d36..7715df8c6 100644
--- a/tools/gfx/nvapi/nvapi-util.h
+++ b/tools/gfx/nvapi/nvapi-util.h
@@ -4,16 +4,17 @@
#include "slang-com-helper.h"
#include "slang-com-ptr.h"
-namespace gfx {
+namespace gfx
+{
struct NVAPIUtil
{
- /// Set up NVAPI for use. Must be called before any other function is used.
+ /// Set up NVAPI for use. Must be called before any other function is used.
static SlangResult initialize();
- /// True if the NVAPI is available, can be called even if initialize fails.
- /// If initialize has not been called will return false
+ /// True if the NVAPI is available, can be called even if initialize fails.
+ /// If initialize has not been called will return false
static bool isAvailable();
};
-} // gfx
+} // namespace gfx
diff --git a/tools/gfx/open-gl/render-gl.cpp b/tools/gfx/open-gl/render-gl.cpp
index 4b2acd094..3a1460a5b 100644
--- a/tools/gfx/open-gl/render-gl.cpp
+++ b/tools/gfx/open-gl/render-gl.cpp
@@ -1,11 +1,9 @@
// render-gl.cpp
#include "render-gl.h"
-#include "../nvapi/nvapi-util.h"
-
#include "../immediate-renderer-base.h"
#include "../mutable-shader-object.h"
-
+#include "../nvapi/nvapi-util.h"
#include "core/slang-basic.h"
#include "core/slang-blob.h"
#include "core/slang-secure-crt.h"
@@ -43,61 +41,62 @@
// We define an "X-macro" for mapping over loadable OpenGL
// extension entry point that we will use, so that we can
// easily write generic code to iterate over them.
-#define MAP_GL_EXTENSION_FUNCS(F) \
- F(glCreateProgram, PFNGLCREATEPROGRAMPROC) \
- F(glCreateShader, PFNGLCREATESHADERPROC) \
- F(glShaderSource, PFNGLSHADERSOURCEPROC) \
- F(glCompileShader, PFNGLCOMPILESHADERPROC) \
- F(glGetShaderiv, PFNGLGETSHADERIVPROC) \
- F(glDeleteShader, PFNGLDELETESHADERPROC) \
- F(glAttachShader, PFNGLATTACHSHADERPROC) \
- F(glLinkProgram, PFNGLLINKPROGRAMPROC) \
- F(glGetProgramiv, PFNGLGETPROGRAMIVPROC) \
- F(glGetProgramInfoLog, PFNGLGETPROGRAMINFOLOGPROC) \
- F(glDeleteProgram, PFNGLDELETEPROGRAMPROC) \
- F(glGetShaderInfoLog, PFNGLGETSHADERINFOLOGPROC) \
- F(glGenBuffers, PFNGLGENBUFFERSPROC) \
- F(glBindBuffer, PFNGLBINDBUFFERPROC) \
- F(glBufferData, PFNGLBUFFERDATAPROC) \
- F(glCopyBufferSubData, PFNGLCOPYBUFFERSUBDATAPROC) \
- F(glDeleteBuffers, PFNGLDELETEBUFFERSPROC) \
- F(glMapBuffer, PFNGLMAPBUFFERPROC) \
- F(glUnmapBuffer, PFNGLUNMAPBUFFERPROC) \
- F(glUseProgram, PFNGLUSEPROGRAMPROC) \
- F(glBindBufferBase, PFNGLBINDBUFFERBASEPROC) \
- F(glBindBufferRange, PFNGLBINDBUFFERRANGEPROC) \
- F(glVertexAttribPointer, PFNGLVERTEXATTRIBPOINTERPROC) \
- F(glEnableVertexAttribArray, PFNGLENABLEVERTEXATTRIBARRAYPROC) \
- F(glDisableVertexAttribArray, PFNGLDISABLEVERTEXATTRIBARRAYPROC) \
- F(glDebugMessageCallback, PFNGLDEBUGMESSAGECALLBACKPROC) \
- F(glDispatchCompute, PFNGLDISPATCHCOMPUTEPROC) \
- F(glActiveTexture, PFNGLACTIVETEXTUREPROC) \
- F(glCreateSamplers, PFNGLCREATESAMPLERSPROC) \
- F(glDeleteSamplers, PFNGLDELETESAMPLERSPROC) \
- F(glBindSampler, PFNGLBINDSAMPLERPROC) \
- F(glTexImage3D, PFNGLTEXIMAGE3DPROC) \
- F(glBindImageTexture, PFNGLBINDIMAGETEXTUREPROC) \
- F(glSamplerParameteri, PFNGLSAMPLERPARAMETERIPROC) \
- F(glGenFramebuffers, PFNGLGENFRAMEBUFFERSPROC) \
- F(glDeleteFramebuffers, PFNGLDELETEFRAMEBUFFERSPROC) \
- F(glBindFramebuffer, PFNGLBINDFRAMEBUFFERPROC) \
- F(glDrawBuffers, PFNGLDRAWBUFFERSPROC) \
- F(glFramebufferTexture2D, PFNGLFRAMEBUFFERTEXTURE2DPROC) \
- F(glFramebufferTextureLayer, PFNGLFRAMEBUFFERTEXTURELAYERPROC) \
- F(glBlitFramebuffer, PFNGLBLITFRAMEBUFFERPROC) \
- F(glCheckFramebufferStatus, PFNGLCHECKFRAMEBUFFERSTATUSPROC) \
- F(glGenVertexArrays, PFNGLGENVERTEXARRAYSPROC) \
- F(glBindVertexArray, PFNGLBINDVERTEXARRAYPROC) \
- F(glDeleteVertexArrays, PFNGLDELETEVERTEXARRAYSPROC) \
- F(glDrawElementsBaseVertex, PFNGLDRAWELEMENTSBASEVERTEXPROC) \
+#define MAP_GL_EXTENSION_FUNCS(F) \
+ F(glCreateProgram, PFNGLCREATEPROGRAMPROC) \
+ F(glCreateShader, PFNGLCREATESHADERPROC) \
+ F(glShaderSource, PFNGLSHADERSOURCEPROC) \
+ F(glCompileShader, PFNGLCOMPILESHADERPROC) \
+ F(glGetShaderiv, PFNGLGETSHADERIVPROC) \
+ F(glDeleteShader, PFNGLDELETESHADERPROC) \
+ F(glAttachShader, PFNGLATTACHSHADERPROC) \
+ F(glLinkProgram, PFNGLLINKPROGRAMPROC) \
+ F(glGetProgramiv, PFNGLGETPROGRAMIVPROC) \
+ F(glGetProgramInfoLog, PFNGLGETPROGRAMINFOLOGPROC) \
+ F(glDeleteProgram, PFNGLDELETEPROGRAMPROC) \
+ F(glGetShaderInfoLog, PFNGLGETSHADERINFOLOGPROC) \
+ F(glGenBuffers, PFNGLGENBUFFERSPROC) \
+ F(glBindBuffer, PFNGLBINDBUFFERPROC) \
+ F(glBufferData, PFNGLBUFFERDATAPROC) \
+ F(glCopyBufferSubData, PFNGLCOPYBUFFERSUBDATAPROC) \
+ F(glDeleteBuffers, PFNGLDELETEBUFFERSPROC) \
+ F(glMapBuffer, PFNGLMAPBUFFERPROC) \
+ F(glUnmapBuffer, PFNGLUNMAPBUFFERPROC) \
+ F(glUseProgram, PFNGLUSEPROGRAMPROC) \
+ F(glBindBufferBase, PFNGLBINDBUFFERBASEPROC) \
+ F(glBindBufferRange, PFNGLBINDBUFFERRANGEPROC) \
+ F(glVertexAttribPointer, PFNGLVERTEXATTRIBPOINTERPROC) \
+ F(glEnableVertexAttribArray, PFNGLENABLEVERTEXATTRIBARRAYPROC) \
+ F(glDisableVertexAttribArray, PFNGLDISABLEVERTEXATTRIBARRAYPROC) \
+ F(glDebugMessageCallback, PFNGLDEBUGMESSAGECALLBACKPROC) \
+ F(glDispatchCompute, PFNGLDISPATCHCOMPUTEPROC) \
+ F(glActiveTexture, PFNGLACTIVETEXTUREPROC) \
+ F(glCreateSamplers, PFNGLCREATESAMPLERSPROC) \
+ F(glDeleteSamplers, PFNGLDELETESAMPLERSPROC) \
+ F(glBindSampler, PFNGLBINDSAMPLERPROC) \
+ F(glTexImage3D, PFNGLTEXIMAGE3DPROC) \
+ F(glBindImageTexture, PFNGLBINDIMAGETEXTUREPROC) \
+ F(glSamplerParameteri, PFNGLSAMPLERPARAMETERIPROC) \
+ F(glGenFramebuffers, PFNGLGENFRAMEBUFFERSPROC) \
+ F(glDeleteFramebuffers, PFNGLDELETEFRAMEBUFFERSPROC) \
+ F(glBindFramebuffer, PFNGLBINDFRAMEBUFFERPROC) \
+ F(glDrawBuffers, PFNGLDRAWBUFFERSPROC) \
+ F(glFramebufferTexture2D, PFNGLFRAMEBUFFERTEXTURE2DPROC) \
+ F(glFramebufferTextureLayer, PFNGLFRAMEBUFFERTEXTURELAYERPROC) \
+ F(glBlitFramebuffer, PFNGLBLITFRAMEBUFFERPROC) \
+ F(glCheckFramebufferStatus, PFNGLCHECKFRAMEBUFFERSTATUSPROC) \
+ F(glGenVertexArrays, PFNGLGENVERTEXARRAYSPROC) \
+ F(glBindVertexArray, PFNGLBINDVERTEXARRAYPROC) \
+ F(glDeleteVertexArrays, PFNGLDELETEVERTEXARRAYSPROC) \
+ F(glDrawElementsBaseVertex, PFNGLDRAWELEMENTSBASEVERTEXPROC) \
/* end */
-#define MAP_WGL_EXTENSION_FUNCS(F) \
+#define MAP_WGL_EXTENSION_FUNCS(F) \
F(wglCreateContextAttribsARB, PFNWGLCREATECONTEXTATTRIBSARBPROC) \
/* end */
using namespace Slang;
-namespace gfx {
+namespace gfx
+{
class GLDevice : public ImmediateRendererBase
{
@@ -106,12 +105,14 @@ public:
virtual SLANG_NO_THROW Result SLANG_MCALL initialize(const Desc& desc) override;
virtual void clearFrame(uint32_t mask, bool clearDepth, bool clearStencil) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain) override;
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL createFramebuffer(
- const IFramebuffer::Desc& desc,
- IFramebuffer** outFramebuffer) override;
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
virtual void setFramebuffer(IFramebuffer* frameBuffer) override;
virtual void setStencilReference(uint32_t referenceValue) override;
@@ -124,27 +125,32 @@ public:
const void* initData,
IBufferResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
+ createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
- ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView) override;
+ ITextureResource* texture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createBufferView(
IBufferResource* buffer,
IBufferResource* counterBuffer,
IResourceView::Desc const& desc,
IResourceView** outView) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL createInputLayout(
- IInputLayout::Desc const& desc,
- IInputLayout** outLayout) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
virtual Result createShaderObjectLayout(
slang::ISession* session,
slang::TypeLayoutReflection* typeLayout,
ShaderObjectLayoutBase** outLayout) override;
- virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
- virtual Result createMutableShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
- virtual Result createRootShaderObject(IShaderProgram* program, ShaderObjectBase** outObject) override;
+ virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ override;
+ virtual Result createMutableShaderObject(
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject) override;
+ virtual Result createRootShaderObject(IShaderProgram* program, ShaderObjectBase** outObject)
+ override;
virtual void bindRootShaderObject(IShaderObject* shaderObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createProgram(
@@ -152,9 +158,11 @@ public:
IShaderProgram** outProgram,
ISlangBlob** outDiagnosticBlob) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& desc, IPipelineState** outState) override;
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState) override;
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual void copyBuffer(
IBufferResource* dst,
@@ -163,7 +171,11 @@ public:
size_t srcOffset,
size_t size) override;
virtual SLANG_NO_THROW Result SLANG_MCALL readTextureResource(
- ITextureResource* texture, ResourceState state, ISlangBlob** outBlob, size_t* outRowPitch, size_t* outPixelSize) override;
+ ITextureResource* texture,
+ ResourceState state,
+ ISlangBlob** outBlob,
+ size_t* outRowPitch,
+ size_t* outPixelSize) override;
virtual void* map(IBufferResource* buffer, MapFlavor flavor) override;
virtual void unmap(IBufferResource* buffer, size_t offsetWritten, size_t sizeWritten) override;
@@ -174,14 +186,14 @@ public:
GfxCount slotCount,
IBufferResource* const* buffers,
const Offset* offsets) override;
- virtual void setIndexBuffer(
- IBufferResource* buffer, Format indexFormat, Offset offset) override;
+ virtual void setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset)
+ override;
virtual void setViewports(GfxCount count, Viewport const* viewports) override;
virtual void setScissorRects(GfxCount count, ScissorRect const* rects) override;
virtual void setPipelineState(IPipelineState* state) override;
virtual void draw(GfxCount vertexCount, GfxCount startVertex) override;
- virtual void drawIndexed(
- GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex) override;
+ virtual void drawIndexed(GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex)
+ override;
virtual void drawInstanced(
GfxCount vertexCount,
GfxCount instanceCount,
@@ -201,8 +213,8 @@ public:
SLANG_UNUSED(pool);
SLANG_UNUSED(index);
}
- virtual SLANG_NO_THROW Result SLANG_MCALL createQueryPool(
- const IQueryPool::Desc& desc, IQueryPool** pool) override
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ createQueryPool(const IQueryPool::Desc& desc, IQueryPool** pool) override
{
SLANG_UNUSED(desc);
*pool = nullptr;
@@ -217,7 +229,7 @@ public:
GLDevice();
~GLDevice();
- protected:
+protected:
enum
{
kMaxVertexAttributes = 16,
@@ -226,20 +238,20 @@ public:
};
struct VertexAttributeFormat
{
- GLint componentCount;
- GLenum componentType;
- GLboolean normalized;
+ GLint componentCount;
+ GLenum componentType;
+ GLboolean normalized;
};
struct VertexAttributeDesc
{
- VertexAttributeFormat format;
- GLuint streamIndex;
- GLsizei offset;
+ VertexAttributeFormat format;
+ GLuint streamIndex;
+ GLsizei offset;
};
class InputLayoutImpl : public InputLayoutBase
- {
+ {
public:
VertexAttributeDesc m_attributes[kMaxVertexAttributes];
VertexStreamDesc m_streams[kMaxVertexStreams];
@@ -247,38 +259,36 @@ public:
UInt m_streamCount = 0;
};
- class BufferResourceImpl: public BufferResource
- {
- public:
+ class BufferResourceImpl : public BufferResource
+ {
+ public:
typedef BufferResource Parent;
- BufferResourceImpl(const Desc& desc, WeakSink<GLDevice>* renderer, GLuint id, GLenum target):
- Parent(desc),
- m_renderer(renderer),
- m_handle(id),
- m_target(target),
- m_size(desc.sizeInBytes)
- {}
- ~BufferResourceImpl()
- {
- if (auto renderer = m_renderer->get())
- {
- renderer->glDeleteBuffers(1, &m_handle);
- }
- }
-
- RefPtr<WeakSink<GLDevice>> m_renderer;
- GLuint m_handle;
+ BufferResourceImpl(const Desc& desc, WeakSink<GLDevice>* renderer, GLuint id, GLenum target)
+ : Parent(desc)
+ , m_renderer(renderer)
+ , m_handle(id)
+ , m_target(target)
+ , m_size(desc.sizeInBytes)
+ {
+ }
+ ~BufferResourceImpl()
+ {
+ if (auto renderer = m_renderer->get())
+ {
+ renderer->glDeleteBuffers(1, &m_handle);
+ }
+ }
+
+ RefPtr<WeakSink<GLDevice>> m_renderer;
+ GLuint m_handle;
GLenum m_target;
UInt m_size;
- virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override
- {
- return 0;
- }
+ virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override { return 0; }
virtual SLANG_NO_THROW Result SLANG_MCALL
- map(MemoryRange* rangeToRead, void** outPointer) override
+ map(MemoryRange* rangeToRead, void** outPointer) override
{
SLANG_UNUSED(rangeToRead);
SLANG_UNUSED(outPointer);
@@ -290,16 +300,15 @@ public:
SLANG_UNUSED(writtenRange);
return SLANG_FAIL;
}
- };
+ };
- class TextureResourceImpl: public TextureResource
+ class TextureResourceImpl : public TextureResource
{
- public:
+ public:
typedef TextureResource Parent;
- TextureResourceImpl(const Desc& desc, WeakSink<GLDevice>* renderer):
- Parent(desc),
- m_renderer(renderer)
+ TextureResourceImpl(const Desc& desc, WeakSink<GLDevice>* renderer)
+ : Parent(desc), m_renderer(renderer)
{
m_target = 0;
m_handle = 0;
@@ -311,7 +320,7 @@ public:
{
glDeleteTextures(1, &m_handle);
}
- }
+ }
RefPtr<WeakSink<GLDevice>> m_renderer;
GLenum m_target;
@@ -329,7 +338,8 @@ public:
public:
enum class Type
{
- Texture, Buffer
+ Texture,
+ Buffer
};
Type type;
};
@@ -342,7 +352,8 @@ public:
GLuint m_target;
enum class TextureViewType
{
- Texture, Image
+ Texture,
+ Image
};
TextureViewType textureViewType;
GLint level;
@@ -355,8 +366,8 @@ public:
class BufferViewImpl : public ResourceViewImpl
{
public:
- RefPtr<BufferResourceImpl> m_resource;
- GLuint m_bufferID;
+ RefPtr<BufferResourceImpl> m_resource;
+ GLuint m_bufferID;
};
class FramebufferLayoutImpl : public FramebufferLayoutBase
@@ -379,7 +390,10 @@ public:
bool m_sameClearValues = true;
DepthStencilClearValue m_depthStencilClearValue;
- FramebufferImpl(WeakSink<GLDevice>* renderer) :m_renderer(renderer) {}
+ FramebufferImpl(WeakSink<GLDevice>* renderer)
+ : m_renderer(renderer)
+ {
+ }
~FramebufferImpl()
{
if (auto renderer = m_renderer->get())
@@ -398,7 +412,11 @@ public:
{
auto rtv = renderTargetViews[i].Ptr();
renderer->glFramebufferTexture2D(
- GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + (uint32_t)i, GL_TEXTURE_2D, rtv->m_textureID, 0);
+ GL_FRAMEBUFFER,
+ GL_COLOR_ATTACHMENT0 + (uint32_t)i,
+ GL_TEXTURE_2D,
+ rtv->m_textureID,
+ 0);
m_drawBuffers.add((GLenum)(GL_COLOR_ATTACHMENT0 + i));
if (rtv->m_resource->getDesc()->optimalClearValue)
{
@@ -444,9 +462,7 @@ public:
}
};
- class SwapchainImpl
- : public ISwapchain
- , public ComObject
+ class SwapchainImpl : public ISwapchain, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -503,7 +519,11 @@ public:
m_renderer->get()->glGenFramebuffers(1, &m_framebuffer);
m_renderer->get()->glBindFramebuffer(GL_READ_FRAMEBUFFER, m_framebuffer);
m_renderer->get()->glFramebufferTexture2D(
- GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_backBuffer, 0);
+ GL_READ_FRAMEBUFFER,
+ GL_COLOR_ATTACHMENT0,
+ GL_TEXTURE_2D,
+ m_backBuffer,
+ 0);
m_images.clear();
for (GfxIndex i = 0; i < m_desc.imageCount; i++)
@@ -545,7 +565,7 @@ public:
}
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override { return m_desc; }
virtual SLANG_NO_THROW Result SLANG_MCALL
- getImage(GfxIndex index, ITextureResource** outResource) override
+ getImage(GfxIndex index, ITextureResource** outResource) override
{
returnComPtr(outResource, m_images[index]);
return SLANG_OK;
@@ -592,10 +612,7 @@ public:
return SLANG_OK;
}
- virtual SLANG_NO_THROW bool SLANG_MCALL isOccluded() override
- {
- return false;
- }
+ virtual SLANG_NO_THROW bool SLANG_MCALL isOccluded() override { return false; }
virtual SLANG_NO_THROW Result SLANG_MCALL setFullScreenMode(bool mode) override
{
return SLANG_FAIL;
@@ -615,30 +632,29 @@ public:
ShortList<RefPtr<TextureResourceImpl>> m_images;
};
- class ShaderProgramImpl : public ShaderProgramBase
- {
- public:
- ShaderProgramImpl(WeakSink<GLDevice>* renderer, GLuint id):
- m_renderer(renderer),
- m_id(id)
- {
- }
- ~ShaderProgramImpl()
- {
- if (auto renderer = m_renderer->get())
- {
- renderer->glDeleteProgram(m_id);
- }
- }
-
- GLuint m_id;
- RefPtr<WeakSink<GLDevice>> m_renderer;
- };
+ class ShaderProgramImpl : public ShaderProgramBase
+ {
+ public:
+ ShaderProgramImpl(WeakSink<GLDevice>* renderer, GLuint id)
+ : m_renderer(renderer), m_id(id)
+ {
+ }
+ ~ShaderProgramImpl()
+ {
+ if (auto renderer = m_renderer->get())
+ {
+ renderer->glDeleteProgram(m_id);
+ }
+ }
+
+ GLuint m_id;
+ RefPtr<WeakSink<GLDevice>> m_renderer;
+ };
class PipelineStateImpl : public PipelineStateBase
{
public:
- RefPtr<InputLayoutImpl> m_inputLayout;
+ RefPtr<InputLayoutImpl> m_inputLayout;
void init(const GraphicsPipelineStateDesc& inDesc)
{
PipelineStateDesc pipelineDesc;
@@ -687,7 +703,8 @@ public:
public:
Builder(RendererBase* renderer, slang::ISession* session)
: m_renderer(renderer), m_session(session)
- {}
+ {
+ }
RendererBase* m_renderer;
slang::ISession* m_session;
@@ -748,8 +765,7 @@ public:
bindingRangeInfo.baseIndex = m_storageBufferCount;
m_storageBufferCount += count;
break;
- case slang::BindingType::Sampler:
- break;
+ case slang::BindingType::Sampler: break;
case slang::BindingType::Texture:
case slang::BindingType::CombinedTextureSampler:
@@ -767,11 +783,8 @@ public:
m_storageBufferCount += count;
break;
case slang::BindingType::VaryingInput:
- case slang::BindingType::VaryingOutput:
- break;
- default:
- SLANG_ASSERT(!"unsupported binding type.");
- break;
+ case slang::BindingType::VaryingOutput: break;
+ default: SLANG_ASSERT(!"unsupported binding type."); break;
}
m_bindingRanges.add(bindingRangeInfo);
}
@@ -812,8 +825,7 @@ public:
SlangResult build(ShaderObjectLayoutImpl** outLayout)
{
- auto layout =
- RefPtr<ShaderObjectLayoutImpl>(new ShaderObjectLayoutImpl());
+ auto layout = RefPtr<ShaderObjectLayoutImpl>(new ShaderObjectLayoutImpl());
SLANG_RETURN_ON_FAIL(layout->_init(this));
returnRefPtrMove(outLayout, layout);
@@ -843,15 +855,16 @@ public:
Index getStorageBufferCount() { return m_storageBufferCount; }
Index getSubObjectCount() { return m_subObjectCount; }
- SubObjectRangeInfo const& getSubObjectRange(Index index) { return m_subObjectRanges[index]; }
+ SubObjectRangeInfo const& getSubObjectRange(Index index)
+ {
+ return m_subObjectRanges[index];
+ }
List<SubObjectRangeInfo> const& getSubObjectRanges() { return m_subObjectRanges; }
RendererBase* getRenderer() { return m_renderer; }
- slang::TypeReflection* getType()
- {
- return m_elementTypeLayout->getType();
- }
+ slang::TypeReflection* getType() { return m_elementTypeLayout->getType(); }
+
protected:
Result _init(Builder const* builder)
{
@@ -898,7 +911,8 @@ public:
: Super::Builder(renderer, program->getSession())
, m_program(program)
, m_programLayout(programLayout)
- {}
+ {
+ }
Result build(RootShaderObjectLayoutImpl** outLayout)
{
@@ -945,7 +959,10 @@ public:
auto slangEntryPoint = programLayout->getEntryPointByIndex(e);
RefPtr<ShaderObjectLayoutImpl> entryPointLayout;
SLANG_RETURN_ON_FAIL(ShaderObjectLayoutImpl::createForElementType(
- renderer, program->getSession(), slangEntryPoint->getTypeLayout(), entryPointLayout.writeRef()));
+ renderer,
+ program->getSession(),
+ slangEntryPoint->getTypeLayout(),
+ entryPointLayout.writeRef()));
builder.addEntryPoint(slangEntryPoint->getStage(), entryPointLayout);
}
@@ -970,17 +987,16 @@ public:
return SLANG_OK;
}
- ComPtr<slang::IComponentType> m_program;
+ ComPtr<slang::IComponentType> m_program;
slang::ProgramLayout* m_programLayout = nullptr;
List<EntryPointInfo> m_entryPoints;
};
- class ShaderObjectImpl
- : public ShaderObjectBaseImpl<
- ShaderObjectImpl,
- ShaderObjectLayoutImpl,
- SimpleShaderObjectData>
+ class ShaderObjectImpl : public ShaderObjectBaseImpl<
+ ShaderObjectImpl,
+ ShaderObjectLayoutImpl,
+ SimpleShaderObjectData>
{
public:
static Result create(
@@ -999,8 +1015,8 @@ public:
SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE { return 0; }
- SLANG_NO_THROW Result SLANG_MCALL getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
- SLANG_OVERRIDE
+ SLANG_NO_THROW Result SLANG_MCALL
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) SLANG_OVERRIDE
{
*outEntryPoint = nullptr;
return SLANG_OK;
@@ -1022,7 +1038,7 @@ public:
}
SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& inOffset, void const* data, size_t inSize) SLANG_OVERRIDE
+ setData(ShaderOffset const& inOffset, void const* data, size_t inSize) SLANG_OVERRIDE
{
Index offset = inOffset.uniformOffset;
Index size = inSize;
@@ -1051,7 +1067,7 @@ public:
SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* resourceView) SLANG_OVERRIDE
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) SLANG_OVERRIDE
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
@@ -1067,21 +1083,24 @@ public:
case slang::BindingType::MutableTypedBuffer:
case slang::BindingType::RawBuffer:
case slang::BindingType::TypedBuffer:
- m_storageBuffers[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<BufferViewImpl*>(resourceView);
+ m_storageBuffers[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<BufferViewImpl*>(resourceView);
break;
case slang::BindingType::MutableTexture:
- m_images[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<TextureViewImpl*>(resourceView);
+ m_images[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<TextureViewImpl*>(resourceView);
break;
case slang::BindingType::Texture:
- m_textures[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<TextureViewImpl*>(resourceView);
+ m_textures[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<TextureViewImpl*>(resourceView);
m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] = nullptr;
break;
}
return SLANG_OK;
}
- SLANG_NO_THROW Result SLANG_MCALL setSampler(ShaderOffset const& offset, ISamplerState* sampler)
- SLANG_OVERRIDE
+ SLANG_NO_THROW Result SLANG_MCALL
+ setSampler(ShaderOffset const& offset, ISamplerState* sampler) SLANG_OVERRIDE
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
@@ -1090,12 +1109,15 @@ public:
return SLANG_E_INVALID_ARG;
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
- m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<SamplerStateImpl*>(sampler);
+ m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<SamplerStateImpl*>(sampler);
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) SLANG_OVERRIDE
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) SLANG_OVERRIDE
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
@@ -1103,13 +1125,14 @@ public:
if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
return SLANG_E_INVALID_ARG;
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
- m_textures[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<TextureViewImpl*>(textureView);
- m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] = static_cast<SamplerStateImpl*>(sampler);
+ m_textures[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<TextureViewImpl*>(textureView);
+ m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] =
+ static_cast<SamplerStateImpl*>(sampler);
return SLANG_OK;
}
public:
-
protected:
friend class ProgramVars;
@@ -1161,7 +1184,8 @@ public:
// in each entry in this range, based on the layout
// information we already have.
- auto& bindingRangeInfo = layout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
+ auto& bindingRangeInfo =
+ layout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
for (Index i = 0; i < bindingRangeInfo.count; ++i)
{
RefPtr<ShaderObjectImpl> subObject;
@@ -1174,12 +1198,13 @@ public:
return SLANG_OK;
}
- /// Write the uniform/ordinary data of this object into the given `dest` buffer at the given `offset`
+ /// Write the uniform/ordinary data of this object into the given `dest` buffer at the given
+ /// `offset`
Result _writeOrdinaryData(
GLDevice* device,
BufferResourceImpl* buffer,
size_t offset,
- size_t destSize,
+ size_t destSize,
ShaderObjectLayoutImpl* specializedLayout)
{
auto src = m_data.getBuffer();
@@ -1207,7 +1232,8 @@ public:
for (auto const& subObjectRangeInfo : specializedLayout->getSubObjectRanges())
{
Index subObjectRangeIndex = subObjectRangeCounter++;
- auto const& bindingRangeInfo = specializedLayout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
+ auto const& bindingRangeInfo =
+ specializedLayout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
// We only need to handle sub-object ranges for interface/existential-type fields,
// because fields of constant-buffer or parameter-block type are responsible for
@@ -1231,24 +1257,27 @@ public:
// of the parent object's type layout.
//
// Here we assume that the Slang reflection API can provide us with a single byte
- // offset and stride for the location of the pending data allocation in the specialized
- // type layout, which will store the values for this sub-object range.
+ // offset and stride for the location of the pending data allocation in the
+ // specialized type layout, which will store the values for this sub-object range.
//
// TODO: The reflection API functions we are assuming here haven't been implemented
// yet, so the functions being called here are stubs.
//
// TODO: It might not be that a single sub-object range can reliably map to a single
- // contiguous array with a single stride; we need to carefully consider what the layout
- // logic does for complex cases with multiple layers of nested arrays and structures.
+ // contiguous array with a single stride; we need to carefully consider what the
+ // layout logic does for complex cases with multiple layers of nested arrays and
+ // structures.
//
- size_t subObjectRangePendingDataOffset = 0; //subObjectRangeInfo.offset.pendingOrdinaryData;
- size_t subObjectRangePendingDataStride = 0; //subObjectRangeInfo.stride.pendingOrdinaryData;
+ size_t subObjectRangePendingDataOffset =
+ 0; // subObjectRangeInfo.offset.pendingOrdinaryData;
+ size_t subObjectRangePendingDataStride =
+ 0; // subObjectRangeInfo.stride.pendingOrdinaryData;
// If the range doesn't actually need/use the "pending" allocation at all, then
// we need to detect that case and skip such ranges.
//
- // TODO: This should probably be handled on a per-object basis by caching a "does it fit?"
- // bit as part of the information for bound sub-objects, given that we already
+ // TODO: This should probably be handled on a per-object basis by caching a "does it
+ // fit?" bit as part of the information for bound sub-objects, given that we already
// compute the "does it fit?" status as part of `setObject()`.
//
if (subObjectRangePendingDataOffset == 0)
@@ -1259,11 +1288,18 @@ public:
auto subObject = m_objects[bindingRangeInfo.subObjectIndex + i];
RefPtr<ShaderObjectLayoutImpl> subObjectLayout;
- SLANG_RETURN_ON_FAIL(subObject->_getSpecializedLayout(subObjectLayout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ subObject->_getSpecializedLayout(subObjectLayout.writeRef()));
- auto subObjectOffset = subObjectRangePendingDataOffset + i * subObjectRangePendingDataStride;
+ auto subObjectOffset =
+ subObjectRangePendingDataOffset + i * subObjectRangePendingDataStride;
- subObject->_writeOrdinaryData(device, buffer, offset + subObjectOffset, destSize - subObjectOffset, subObjectLayout);
+ subObject->_writeOrdinaryData(
+ device,
+ buffer,
+ offset + subObjectOffset,
+ destSize - subObjectOffset,
+ subObjectLayout);
}
}
@@ -1325,15 +1361,18 @@ public:
// where this object contains interface/existential-type fields, so we
// don't need or want to inline it into this call site.
//
- SLANG_RETURN_ON_FAIL(_writeOrdinaryData(device, m_ordinaryDataBuffer, 0, specializedOrdinaryDataSize, specializedLayout));
+ SLANG_RETURN_ON_FAIL(_writeOrdinaryData(
+ device,
+ m_ordinaryDataBuffer,
+ 0,
+ specializedOrdinaryDataSize,
+ specializedLayout));
return SLANG_OK;
}
/// Bind the buffer for ordinary/uniform data, if needed
- Result _bindOrdinaryDataBufferIfNeeded(
- GLDevice* device,
- RootBindingState* bindingState)
+ Result _bindOrdinaryDataBufferIfNeeded(GLDevice* device, RootBindingState* bindingState)
{
// We start by ensuring that the buffer is created, if it is needed.
//
@@ -1349,6 +1388,7 @@ public:
return SLANG_OK;
}
+
public:
virtual Result bindObject(GLDevice* device, RootBindingState* bindingState)
{
@@ -1376,10 +1416,8 @@ public:
{
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ParameterBlock:
- case slang::BindingType::ExistentialValue:
- break;
- default:
- continue;
+ case slang::BindingType::ExistentialValue: break;
+ default: continue;
}
for (Index i = 0; i < bindingRange.count; i++)
@@ -1444,17 +1482,24 @@ public:
RefPtr<ShaderObjectLayoutImpl> m_specializedLayout;
};
- class MutableShaderObjectImpl : public MutableShaderObject<MutableShaderObjectImpl, ShaderObjectLayoutImpl>
- {};
+ class MutableShaderObjectImpl
+ : public MutableShaderObject<MutableShaderObjectImpl, ShaderObjectLayoutImpl>
+ {
+ };
class RootShaderObjectImpl : public ShaderObjectImpl
{
typedef ShaderObjectImpl Super;
+
public:
virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() override { return 1; }
virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() override { return 1; }
+
public:
- static Result create(IDevice* device, RootShaderObjectLayoutImpl* layout, RootShaderObjectImpl** outShaderObject)
+ static Result create(
+ IDevice* device,
+ RootShaderObjectLayoutImpl* layout,
+ RootShaderObjectImpl** outShaderObject)
{
RefPtr<RootShaderObjectImpl> object = new RootShaderObjectImpl();
SLANG_RETURN_ON_FAIL(object->init(device, layout));
@@ -1463,10 +1508,17 @@ public:
return SLANG_OK;
}
- RootShaderObjectLayoutImpl* getLayout() { return static_cast<RootShaderObjectLayoutImpl*>(m_layout.Ptr()); }
+ RootShaderObjectLayoutImpl* getLayout()
+ {
+ return static_cast<RootShaderObjectLayoutImpl*>(m_layout.Ptr());
+ }
- GfxCount SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE { return (GfxCount)m_entryPoints.getCount(); }
- SlangResult SLANG_MCALL getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) SLANG_OVERRIDE
+ GfxCount SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE
+ {
+ return (GfxCount)m_entryPoints.getCount();
+ }
+ SlangResult SLANG_MCALL getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
+ SLANG_OVERRIDE
{
*outEntryPoint = m_entryPoints[index];
m_entryPoints[index]->addRef();
@@ -1552,8 +1604,9 @@ public:
// parmaeters, but their layouts are also independent of one another.
//
// Furthermore, in this example, loading another entry point into the system would not
- // rquire re-computing the layouts (or generated kernel code) for any of the entry points
- // that had already been loaded (in contrast to a compose-then-specialize approach).
+ // rquire re-computing the layouts (or generated kernel code) for any of the entry
+ // points that had already been loaded (in contrast to a compose-then-specialize
+ // approach).
//
ComPtr<slang::IComponentType> specializedComponentType;
ComPtr<slang::IBlob> diagnosticBlob;
@@ -1570,7 +1623,11 @@ public:
auto slangSpecializedLayout = specializedComponentType->getLayout();
RefPtr<RootShaderObjectLayoutImpl> specializedLayout;
- RootShaderObjectLayoutImpl::create(getRenderer(), specializedComponentType, slangSpecializedLayout, specializedLayout.writeRef());
+ RootShaderObjectLayoutImpl::create(
+ getRenderer(),
+ specializedComponentType,
+ slangSpecializedLayout,
+ specializedLayout.writeRef());
// Note: Computing the layout for the specialized program will have also computed
// the layouts for the entry points, and we really need to attach that information
@@ -1608,22 +1665,40 @@ public:
struct GlPixelFormatInfo
{
- GLint internalFormat; // such as GL_RGBA8
- GLenum format; // such as GL_RGBA
- GLenum formatType; // such as GL_UNSIGNED_BYTE
+ GLint internalFormat; // such as GL_RGBA8
+ GLenum format; // such as GL_RGBA
+ GLenum formatType; // such as GL_UNSIGNED_BYTE
};
-// void destroyBindingEntries(const BindingState::Desc& desc, const BindingDetail* details);
+ // void destroyBindingEntries(const BindingState::Desc& desc, const BindingDetail* details);
- void bindBufferImpl(int target, UInt startSlot, UInt slotCount, BufferResource*const* buffers, const UInt* offsets);
+ void bindBufferImpl(
+ int target,
+ UInt startSlot,
+ UInt slotCount,
+ BufferResource* const* buffers,
+ const UInt* offsets);
void flushStateForDraw();
GLuint loadShader(GLenum stage, char const* source);
- void debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message);
-
- /// Returns GlPixelFormat::Unknown if not an equivalent
+ void debugCallback(
+ GLenum source,
+ GLenum type,
+ GLuint id,
+ GLenum severity,
+ GLsizei length,
+ const GLchar* message);
+
+ /// Returns GlPixelFormat::Unknown if not an equivalent
static GlPixelFormat _getGlPixelFormat(Format format);
- static void APIENTRY staticDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam);
+ static void APIENTRY staticDebugCallback(
+ GLenum source,
+ GLenum type,
+ GLuint id,
+ GLenum severity,
+ GLsizei length,
+ const GLchar* message,
+ const void* userParam);
static VertexAttributeFormat getVertexAttributeFormat(Format format);
static void compileTimeAsserts();
@@ -1633,8 +1708,8 @@ public:
DeviceInfo m_info;
String m_adapterName;
- HDC m_hdc;
- HGLRC m_glContext = 0;
+ HDC m_hdc;
+ HGLRC m_glContext = 0;
uint32_t m_stencilRef = 0;
GLuint m_vao;
@@ -1645,80 +1720,96 @@ public:
RootBindingState m_rootBindingState;
GLenum m_boundPrimitiveTopology = GL_TRIANGLES;
- GLuint m_boundVertexStreamBuffers[kMaxVertexStreams];
- UInt m_boundVertexStreamOffsets[kMaxVertexStreams];
+ GLuint m_boundVertexStreamBuffers[kMaxVertexStreams];
+ UInt m_boundVertexStreamOffsets[kMaxVertexStreams];
GLuint m_boundIndexBuffer = 0;
UInt m_boundIndexBufferOffset = 0;
UInt m_boundIndexBufferSize = 0;
Desc m_desc;
WindowHandle m_windowHandle;
- // Declare a function pointer for each OpenGL
- // extension function we need to load
+// Declare a function pointer for each OpenGL
+// extension function we need to load
#define DECLARE_GL_EXTENSION_FUNC(NAME, TYPE) TYPE NAME;
MAP_GL_EXTENSION_FUNCS(DECLARE_GL_EXTENSION_FUNC)
MAP_WGL_EXTENSION_FUNCS(DECLARE_GL_EXTENSION_FUNC)
#undef DECLARE_GL_EXTENSION_FUNC
- static const GlPixelFormatInfo s_pixelFormatInfos[]; /// Maps GlPixelFormat to a format info
+ static const GlPixelFormatInfo s_pixelFormatInfos[]; /// Maps GlPixelFormat to a format info
};
-/* static */GLDevice::GlPixelFormat GLDevice::_getGlPixelFormat(Format format)
+/* static */ GLDevice::GlPixelFormat GLDevice::_getGlPixelFormat(Format format)
{
switch (format)
{
- case Format::R8G8B8A8_UNORM: return GlPixelFormat::R8G8B8A8_UNORM;
- case Format::D32_FLOAT: return GlPixelFormat::D32_FLOAT;
- //case Format::D24_UNORM_S8_UINT: return GlPixelFormat::D_Unorm24_S8;
- case Format::D32_FLOAT_S8_UINT: return GlPixelFormat::D32_FLOAT_S8;
+ case Format::R8G8B8A8_UNORM: return GlPixelFormat::R8G8B8A8_UNORM;
+ case Format::D32_FLOAT: return GlPixelFormat::D32_FLOAT;
+ // case Format::D24_UNORM_S8_UINT: return GlPixelFormat::D_Unorm24_S8;
+ case Format::D32_FLOAT_S8_UINT: return GlPixelFormat::D32_FLOAT_S8;
- default: return GlPixelFormat::Unknown;
+ default: return GlPixelFormat::Unknown;
}
}
-/* static */ const GLDevice::GlPixelFormatInfo GLDevice::s_pixelFormatInfos[] =
-{
+/* static */ const GLDevice::GlPixelFormatInfo GLDevice::s_pixelFormatInfos[] = {
// internalType, format, formatType
- { 0, 0, 0}, // GlPixelFormat::Unknown
- { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE }, // GlPixelFormat::R8G8B8A8_UNORM
- { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE}, // GlPixelFormat::D32_FLOAT
- { GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_BYTE}, // GlPixelFormat::D_Unorm24_S8
- { GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV}, // GlPixelFormat::D32_FLOAT_S8
+ {0, 0, 0}, // GlPixelFormat::Unknown
+ {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE}, // GlPixelFormat::R8G8B8A8_UNORM
+ {GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE}, // GlPixelFormat::D32_FLOAT
+ {GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_BYTE}, // GlPixelFormat::D_Unorm24_S8
+ {GL_DEPTH32F_STENCIL8,
+ GL_DEPTH_STENCIL,
+ GL_FLOAT_32_UNSIGNED_INT_24_8_REV}, // GlPixelFormat::D32_FLOAT_S8
};
-/* static */void GLDevice::compileTimeAsserts()
+/* static */ void GLDevice::compileTimeAsserts()
{
SLANG_COMPILE_TIME_ASSERT(SLANG_COUNT_OF(s_pixelFormatInfos) == int(GlPixelFormat::CountOf));
}
-void GLDevice::debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message)
+void GLDevice::debugCallback(
+ GLenum source,
+ GLenum type,
+ GLuint id,
+ GLenum severity,
+ GLsizei length,
+ const GLchar* message)
{
DebugMessageType msgType = DebugMessageType::Info;
- switch(type)
+ switch (type)
{
- case GL_DEBUG_TYPE_ERROR:
- msgType = DebugMessageType::Error;
- break;
- default:
- break;
+ case GL_DEBUG_TYPE_ERROR: msgType = DebugMessageType::Error; break;
+ default: break;
}
getDebugCallback()->handleMessage(msgType, DebugMessageSource::Driver, message);
}
-/* static */void APIENTRY GLDevice::staticDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam)
+/* static */ void APIENTRY GLDevice::staticDebugCallback(
+ GLenum source,
+ GLenum type,
+ GLuint id,
+ GLenum severity,
+ GLsizei length,
+ const GLchar* message,
+ const void* userParam)
{
((GLDevice*)userParam)->debugCallback(source, type, id, severity, length, message);
}
-/* static */GLDevice::VertexAttributeFormat GLDevice::getVertexAttributeFormat(Format format)
+/* static */ GLDevice::VertexAttributeFormat GLDevice::getVertexAttributeFormat(Format format)
{
switch (format)
{
- default: assert(!"unexpected"); return VertexAttributeFormat();
+ default: assert(!"unexpected"); return VertexAttributeFormat();
-#define CASE(NAME, COUNT, TYPE, NORMALIZED) \
- case Format::NAME: do { VertexAttributeFormat result = {COUNT, TYPE, NORMALIZED}; return result; } while (0)
+#define CASE(NAME, COUNT, TYPE, NORMALIZED) \
+ case Format::NAME: \
+ do \
+ { \
+ VertexAttributeFormat result = {COUNT, TYPE, NORMALIZED}; \
+ return result; \
+ } while (0)
CASE(R32G32B32A32_FLOAT, 4, GL_FLOAT, GL_FALSE);
CASE(R32G32B32_FLOAT, 3, GL_FLOAT, GL_FALSE);
@@ -1728,7 +1819,12 @@ void GLDevice::debugCallback(GLenum source, GLenum type, GLuint id, GLenum sever
}
}
-void GLDevice::bindBufferImpl(int target, UInt startSlot, UInt slotCount, BufferResource*const* buffers, const UInt* offsets)
+void GLDevice::bindBufferImpl(
+ int target,
+ UInt startSlot,
+ UInt slotCount,
+ BufferResource* const* buffers,
+ const UInt* offsets)
{
for (UInt ii = 0; ii < slotCount; ++ii)
{
@@ -1780,7 +1876,12 @@ void GLDevice::flushStateForDraw()
}
if (m_boundIndexBuffer)
{
- glBindBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, m_boundIndexBuffer, m_boundIndexBufferOffset, m_boundIndexBufferSize);
+ glBindBufferRange(
+ GL_ELEMENT_ARRAY_BUFFER,
+ 0,
+ m_boundIndexBuffer,
+ m_boundIndexBufferOffset,
+ m_boundIndexBufferSize);
}
}
@@ -1822,7 +1923,10 @@ GLuint GLDevice::loadShader(GLenum stage, const char* source)
versionEnd = sourceBegin;
}
- enum { kMaxSourceStringCount = 16 };
+ enum
+ {
+ kMaxSourceStringCount = 16
+ };
const GLchar* sourceStrings[kMaxSourceStringCount];
GLint sourceStringLengths[kMaxSourceStringCount];
@@ -1831,7 +1935,8 @@ GLuint GLDevice::loadShader(GLenum stage, const char* source)
const char* stagePrelude = "\n";
switch (stage)
{
-#define CASE(NAME) case GL_##NAME##_SHADER: stagePrelude = "#define __GLSL_" #NAME "__ 1\n"; break
+#define CASE(NAME) \
+ case GL_##NAME##_SHADER: stagePrelude = "#define __GLSL_" #NAME "__ 1\n"; break
CASE(VERTEX);
CASE(TESS_CONTROL);
@@ -1843,19 +1948,15 @@ GLuint GLDevice::loadShader(GLenum stage, const char* source)
#undef CASE
}
- const char* prelude =
- "#define __GLSL__ 1\n"
- ;
+ const char* prelude = "#define __GLSL__ 1\n";
-#define ADD_SOURCE_STRING_SPAN(BEGIN, END) \
- sourceStrings[sourceStringCount] = BEGIN; \
- sourceStringLengths[sourceStringCount++] = GLint(END - BEGIN) \
- /* end */
+#define ADD_SOURCE_STRING_SPAN(BEGIN, END) \
+ sourceStrings[sourceStringCount] = BEGIN; \
+ sourceStringLengths[sourceStringCount++] = GLint(END - BEGIN) /* end */
-#define ADD_SOURCE_STRING(BEGIN) \
- sourceStrings[sourceStringCount] = BEGIN; \
- sourceStringLengths[sourceStringCount++] = GLint(strlen(BEGIN)) \
- /* end */
+#define ADD_SOURCE_STRING(BEGIN) \
+ sourceStrings[sourceStringCount] = BEGIN; \
+ sourceStringLengths[sourceStringCount++] = GLint(strlen(BEGIN)) /* end */
ADD_SOURCE_STRING_SPAN(versionBegin, versionEnd);
ADD_SOURCE_STRING(stagePrelude);
@@ -1864,11 +1965,7 @@ GLuint GLDevice::loadShader(GLenum stage, const char* source)
ADD_SOURCE_STRING_SPAN(versionEnd, sourceEnd);
auto shaderID = glCreateShader(stage);
- glShaderSource(
- shaderID,
- sourceStringCount,
- &sourceStrings[0],
- &sourceStringLengths[0]);
+ glShaderSource(shaderID, sourceStringCount, &sourceStrings[0], &sourceStringLengths[0]);
glCompileShader(shaderID);
GLint success = GL_FALSE;
@@ -1922,19 +2019,19 @@ WindowHandle createWindow()
}
HWND hwnd = CreateWindowEx(
- 0, // Optional window styles.
- className, // Window class
- L"GLWindow", // Window text
+ 0, // Optional window styles.
+ className, // Window class
+ L"GLWindow", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
- NULL, // Parent window
- NULL, // Menu
+ NULL, // Parent window
+ NULL, // Menu
hInstance, // Instance handle
- NULL // Additional application data
+ NULL // Additional application data
);
if (hwnd == NULL)
@@ -1953,7 +2050,10 @@ void destroyWindow(WindowHandle window)
#endif
}
-GLDevice::GLDevice() { m_weakRenderer = new WeakSink<GLDevice>(this); }
+GLDevice::GLDevice()
+{
+ m_weakRenderer = new WeakSink<GLDevice>(this);
+}
GLDevice::~GLDevice()
{
@@ -2013,8 +2113,7 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::initialize(const Desc& desc)
desc.extendedDescs,
SLANG_GLSL,
"glsl_440",
- makeArray(
- slang::PreprocessorMacroDesc{ "__GL__", "1" }).getView()));
+ makeArray(slang::PreprocessorMacroDesc{"__GL__", "1"}).getView()));
SLANG_RETURN_ON_FAIL(RendererBase::initialize(desc));
@@ -2033,7 +2132,7 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::initialize(const Desc& desc)
m_hdc = ::GetDC((HWND)m_windowHandle.handleValues[0]);
- PIXELFORMATDESCRIPTOR pixelFormatDesc = { sizeof(PIXELFORMATDESCRIPTOR) };
+ PIXELFORMATDESCRIPTOR pixelFormatDesc = {sizeof(PIXELFORMATDESCRIPTOR)};
pixelFormatDesc.nVersion = 1;
pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pixelFormatDesc.iPixelType = PFD_TYPE_RGBA;
@@ -2068,7 +2167,7 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::initialize(const Desc& desc)
// Load each of our extension functions by name
-#define LOAD_GL_EXTENSION_FUNC(NAME, TYPE) NAME = (TYPE) wglGetProcAddress(#NAME);
+#define LOAD_GL_EXTENSION_FUNC(NAME, TYPE) NAME = (TYPE)wglGetProcAddress(#NAME);
MAP_GL_EXTENSION_FUNCS(LOAD_GL_EXTENSION_FUNC)
MAP_WGL_EXTENSION_FUNCS(LOAD_GL_EXTENSION_FUNC)
#undef LOAD_GL_EXTENSION_FUNC
@@ -2141,7 +2240,9 @@ void GLDevice::clearFrame(uint32_t mask, bool clearDepth, bool clearStencil)
}
if (clearBuffers.getCount())
{
- glDrawBuffers((GLsizei)clearBuffers.getCount(), clearBuffers.getArrayView().getBuffer());
+ glDrawBuffers(
+ (GLsizei)clearBuffers.getCount(),
+ clearBuffers.getArrayView().getBuffer());
clearMask |= GL_COLOR_BUFFER_BIT;
}
glClear(clearMask);
@@ -2175,7 +2276,9 @@ void GLDevice::clearFrame(uint32_t mask, bool clearDepth, bool clearStencil)
}
SLANG_NO_THROW Result SLANG_MCALL GLDevice::createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain)
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain)
{
RefPtr<SwapchainImpl> swapchain = new SwapchainImpl();
SLANG_RETURN_ON_FAIL(swapchain->init(this, desc, window));
@@ -2185,7 +2288,8 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createSwapchain(
}
SLANG_NO_THROW Result SLANG_MCALL GLDevice::createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout)
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout)
{
RefPtr<FramebufferLayoutImpl> layout = new FramebufferLayoutImpl();
layout->m_renderTargets.setCount(desc.renderTargetCount);
@@ -2208,7 +2312,7 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createFramebufferLayout(
}
SLANG_NO_THROW Result SLANG_MCALL
- GLDevice::createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer)
+GLDevice::createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer)
{
RefPtr<FramebufferImpl> framebuffer = new FramebufferImpl(m_weakRenderer);
framebuffer->renderTargetViews.setCount(desc.renderTargetCount);
@@ -2249,7 +2353,11 @@ void GLDevice::copyBuffer(
}
SLANG_NO_THROW Result SLANG_MCALL GLDevice::readTextureResource(
- ITextureResource* texture, ResourceState state, ISlangBlob** outBlob, Size* outRowPitch, Size* outPixelSize)
+ ITextureResource* texture,
+ ResourceState state,
+ ISlangBlob** outBlob,
+ Size* outRowPitch,
+ Size* outPixelSize)
{
SLANG_UNUSED(state);
auto resource = static_cast<TextureResourceImpl*>(texture);
@@ -2319,7 +2427,7 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createTextureResource(
switch (srcDesc.type)
{
- case IResource::Type::Texture1D:
+ case IResource::Type::Texture1D:
{
if (srcDesc.arraySize > 0)
{
@@ -2364,8 +2472,8 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createTextureResource(
}
break;
}
- case IResource::Type::TextureCube:
- case IResource::Type::Texture2D:
+ case IResource::Type::TextureCube:
+ case IResource::Type::Texture2D:
{
if (srcDesc.arraySize > 0)
{
@@ -2445,7 +2553,7 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createTextureResource(
}
break;
}
- case IResource::Type::Texture3D:
+ case IResource::Type::Texture3D:
{
target = GL_TEXTURE_3D;
glBindTexture(target, handle);
@@ -2465,8 +2573,7 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createTextureResource(
}
break;
}
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
}
glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_REPEAT);
@@ -2488,10 +2595,8 @@ static GLenum _calcUsage(ResourceState state)
{
switch (state)
{
- case ResourceState::ConstantBuffer:
- return GL_DYNAMIC_DRAW;
- default:
- return GL_STATIC_READ;
+ case ResourceState::ConstantBuffer: return GL_DYNAMIC_DRAW;
+ default: return GL_STATIC_READ;
}
}
@@ -2499,10 +2604,8 @@ static GLenum _calcTarget(ResourceState state)
{
switch (state)
{
- case ResourceState::ConstantBuffer:
- return GL_UNIFORM_BUFFER;
- default:
- return GL_SHADER_STORAGE_BUFFER;
+ case ResourceState::ConstantBuffer: return GL_UNIFORM_BUFFER;
+ default: return GL_SHADER_STORAGE_BUFFER;
}
}
@@ -2522,13 +2625,14 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createBufferResource(
glBufferData(target, descIn.sizeInBytes, initData, usage);
- RefPtr<BufferResourceImpl> resourceImpl = new BufferResourceImpl(desc, m_weakRenderer, bufferID, target);
+ RefPtr<BufferResourceImpl> resourceImpl =
+ new BufferResourceImpl(desc, m_weakRenderer, bufferID, target);
returnComPtr(outResource, resourceImpl);
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL
- GLDevice::createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler)
+GLDevice::createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler)
{
GLuint samplerID;
glCreateSamplers(1, &samplerID);
@@ -2540,7 +2644,9 @@ SLANG_NO_THROW Result SLANG_MCALL
}
SLANG_NO_THROW Result SLANG_MCALL GLDevice::createTextureView(
- ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView)
+ ITextureResource* texture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView)
{
auto resourceImpl = static_cast<TextureResourceImpl*>(texture);
@@ -2578,7 +2684,7 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createBufferView(
IResourceView::Desc const& desc,
IResourceView** outView)
{
- auto resourceImpl = (BufferResourceImpl*) buffer;
+ auto resourceImpl = (BufferResourceImpl*)buffer;
// TODO: actually do something?
@@ -2592,8 +2698,8 @@ SLANG_NO_THROW Result SLANG_MCALL GLDevice::createBufferView(
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL GLDevice::createInputLayout(
- IInputLayout::Desc const& desc, IInputLayout** outLayout)
+SLANG_NO_THROW Result SLANG_MCALL
+GLDevice::createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout)
{
RefPtr<InputLayoutImpl> inputLayout = new InputLayoutImpl;
@@ -2625,18 +2731,14 @@ void* GLDevice::map(IBufferResource* bufferIn, MapFlavor flavor)
{
BufferResourceImpl* buffer = static_cast<BufferResourceImpl*>(bufferIn);
- //GLenum target = GL_UNIFORM_BUFFER;
+ // GLenum target = GL_UNIFORM_BUFFER;
GLuint access = 0;
switch (flavor)
{
- case MapFlavor::WriteDiscard:
- case MapFlavor::HostWrite:
- access = GL_WRITE_ONLY;
- break;
- case MapFlavor::HostRead:
- access = GL_READ_ONLY;
- break;
+ case MapFlavor::WriteDiscard:
+ case MapFlavor::HostWrite: access = GL_WRITE_ONLY; break;
+ case MapFlavor::HostRead: access = GL_READ_ONLY; break;
}
glBindBuffer(buffer->m_target, buffer->m_handle);
@@ -2657,7 +2759,8 @@ void GLDevice::setPrimitiveTopology(PrimitiveTopology topology)
GLenum glTopology = 0;
switch (topology)
{
-#define CASE(NAME, VALUE) case PrimitiveTopology::NAME: glTopology = VALUE; break
+#define CASE(NAME, VALUE) \
+ case PrimitiveTopology::NAME: glTopology = VALUE; break
CASE(TriangleList, GL_TRIANGLES);
@@ -2697,17 +2800,17 @@ void GLDevice::setViewports(GfxCount count, Viewport const* viewports)
assert(count == 1);
auto viewport = viewports[0];
glViewport(
- (GLint) viewport.originX,
- (GLint) viewport.originY,
- (GLsizei) viewport.extentX,
- (GLsizei) viewport.extentY);
+ (GLint)viewport.originX,
+ (GLint)viewport.originY,
+ (GLsizei)viewport.extentX,
+ (GLsizei)viewport.extentY);
glDepthRange(viewport.minZ, viewport.maxZ);
}
void GLDevice::setScissorRects(GfxCount count, ScissorRect const* rects)
{
assert(count <= 1);
- if( count )
+ if (count)
{
// TODO: this isn't goign to be quite right because of the
// flipped coordinate system in GL.
@@ -2758,7 +2861,7 @@ void GLDevice::drawIndexed(GfxCount indexCount, GfxIndex startIndex, GfxIndex ba
m_boundPrimitiveTopology,
(GLsizei)indexCount,
GL_UNSIGNED_INT,
- (GLvoid*)(startIndex*sizeof(uint32_t)),
+ (GLvoid*)(startIndex * sizeof(uint32_t)),
(GLint)baseVertex);
}
@@ -2787,7 +2890,9 @@ void GLDevice::dispatchCompute(int x, int y, int z)
}
Result GLDevice::createProgram(
- const IShaderProgram::Desc& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnosticBlob)
+ const IShaderProgram::Desc& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnosticBlob)
{
if (desc.slangGlobalScope->getSpecializationParamCount() != 0)
{
@@ -2805,8 +2910,12 @@ Result GLDevice::createProgram(
{
ComPtr<ISlangBlob> kernelCode;
ComPtr<ISlangBlob> diagnostics;
- auto compileResult = getEntryPointCodeFromShaderCache(desc.slangGlobalScope,
- i, 0, kernelCode.writeRef(), diagnostics.writeRef());
+ auto compileResult = getEntryPointCodeFromShaderCache(
+ desc.slangGlobalScope,
+ i,
+ 0,
+ kernelCode.writeRef(),
+ diagnostics.writeRef());
if (diagnostics)
{
getDebugCallback()->handleMessage(
@@ -2821,27 +2930,13 @@ Result GLDevice::createProgram(
auto stage = programLayout->getEntryPointByIndex(i)->getStage();
switch (stage)
{
- case SLANG_STAGE_COMPUTE:
- glShaderType = GL_COMPUTE_SHADER;
- break;
- case SLANG_STAGE_VERTEX:
- glShaderType = GL_VERTEX_SHADER;
- break;
- case SLANG_STAGE_FRAGMENT:
- glShaderType = GL_FRAGMENT_SHADER;
- break;
- case SLANG_STAGE_GEOMETRY:
- glShaderType = GL_GEOMETRY_SHADER;
- break;
- case SLANG_STAGE_DOMAIN:
- glShaderType = GL_TESS_CONTROL_SHADER;
- break;
- case SLANG_STAGE_HULL:
- glShaderType = GL_TESS_EVALUATION_SHADER;
- break;
- default:
- SLANG_ASSERT(!"unsupported shader type.");
- break;
+ case SLANG_STAGE_COMPUTE: glShaderType = GL_COMPUTE_SHADER; break;
+ case SLANG_STAGE_VERTEX: glShaderType = GL_VERTEX_SHADER; break;
+ case SLANG_STAGE_FRAGMENT: glShaderType = GL_FRAGMENT_SHADER; break;
+ case SLANG_STAGE_GEOMETRY: glShaderType = GL_GEOMETRY_SHADER; break;
+ case SLANG_STAGE_DOMAIN: glShaderType = GL_TESS_CONTROL_SHADER; break;
+ case SLANG_STAGE_HULL: glShaderType = GL_TESS_EVALUATION_SHADER; break;
+ default: SLANG_ASSERT(!"unsupported shader type."); break;
}
auto shaderID = loadShader(glShaderType, (char const*)kernelCode->getBufferPointer());
shaderIDs.add(shaderID);
@@ -2879,12 +2974,14 @@ Result GLDevice::createProgram(
return SLANG_OK;
}
-Result GLDevice::createGraphicsPipelineState(const GraphicsPipelineStateDesc& inDesc, IPipelineState** outState)
+Result GLDevice::createGraphicsPipelineState(
+ const GraphicsPipelineStateDesc& inDesc,
+ IPipelineState** outState)
{
GraphicsPipelineStateDesc desc = inDesc;
- auto programImpl = (ShaderProgramImpl*) desc.program;
- auto inputLayoutImpl = (InputLayoutImpl*) desc.inputLayout;
+ auto programImpl = (ShaderProgramImpl*)desc.program;
+ auto inputLayoutImpl = (InputLayoutImpl*)desc.inputLayout;
RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl();
pipelineStateImpl->m_inputLayout = inputLayoutImpl;
@@ -2893,11 +2990,13 @@ Result GLDevice::createGraphicsPipelineState(const GraphicsPipelineStateDesc& in
return SLANG_OK;
}
-Result GLDevice::createComputePipelineState(const ComputePipelineStateDesc& inDesc, IPipelineState** outState)
+Result GLDevice::createComputePipelineState(
+ const ComputePipelineStateDesc& inDesc,
+ IPipelineState** outState)
{
ComputePipelineStateDesc desc = inDesc;
- auto programImpl = (ShaderProgramImpl*) desc.program;
+ auto programImpl = (ShaderProgramImpl*)desc.program;
RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl();
pipelineStateImpl->m_program = programImpl;
@@ -2912,8 +3011,8 @@ Result GLDevice::createShaderObjectLayout(
ShaderObjectLayoutBase** outLayout)
{
RefPtr<ShaderObjectLayoutImpl> layout;
- SLANG_RETURN_ON_FAIL(ShaderObjectLayoutImpl::createForElementType(
- this, session, typeLayout, layout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ ShaderObjectLayoutImpl::createForElementType(this, session, typeLayout, layout.writeRef()));
returnRefPtrMove(outLayout, layout);
return SLANG_OK;
}
@@ -2921,13 +3020,17 @@ Result GLDevice::createShaderObjectLayout(
Result GLDevice::createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
{
RefPtr<ShaderObjectImpl> shaderObject;
- SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(this,
- static_cast<ShaderObjectLayoutImpl*>(layout), shaderObject.writeRef()));
+ SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(
+ this,
+ static_cast<ShaderObjectLayoutImpl*>(layout),
+ shaderObject.writeRef()));
returnComPtr(outObject, shaderObject);
return SLANG_OK;
}
-Result GLDevice::createMutableShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+Result GLDevice::createMutableShaderObject(
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject)
{
auto layoutImpl = static_cast<ShaderObjectLayoutImpl*>(layout);
@@ -2944,9 +3047,12 @@ Result GLDevice::createRootShaderObject(IShaderProgram* program, ShaderObjectBas
RefPtr<RootShaderObjectImpl> shaderObject;
RefPtr<RootShaderObjectLayoutImpl> rootLayout;
SLANG_RETURN_ON_FAIL(RootShaderObjectLayoutImpl::create(
- this, programImpl->slangGlobalScope, programImpl->slangGlobalScope->getLayout(), rootLayout.writeRef()));
- SLANG_RETURN_ON_FAIL(RootShaderObjectImpl::create(
- this, rootLayout.Ptr(), shaderObject.writeRef()));
+ this,
+ programImpl->slangGlobalScope,
+ programImpl->slangGlobalScope->getLayout(),
+ rootLayout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ RootShaderObjectImpl::create(this, rootLayout.Ptr(), shaderObject.writeRef()));
returnRefPtrMove(outObject, shaderObject);
return SLANG_OK;
}
@@ -2967,7 +3073,14 @@ void GLDevice::bindRootShaderObject(IShaderObject* shaderObject)
for (Index i = 0; i < m_rootBindingState.imageBindings.getCount(); i++)
{
auto binding = m_rootBindingState.imageBindings[i];
- glBindImageTexture((GLuint)i, binding->m_textureID, binding->level, binding->layered, binding->layer, binding->access, binding->format);
+ glBindImageTexture(
+ (GLuint)i,
+ binding->m_textureID,
+ binding->level,
+ binding->layered,
+ binding->layer,
+ binding->access,
+ binding->format);
}
for (Index i = 0; i < m_rootBindingState.textureBindings.getCount(); i++)
{
@@ -2979,7 +3092,10 @@ void GLDevice::bindRootShaderObject(IShaderObject* shaderObject)
}
for (Index i = 0; i < m_rootBindingState.storageBufferBindings.getCount(); i++)
{
- glBindBufferBase(GL_SHADER_STORAGE_BUFFER, (GLuint)i, m_rootBindingState.storageBufferBindings[i]);
+ glBindBufferBase(
+ GL_SHADER_STORAGE_BUFFER,
+ (GLuint)i,
+ m_rootBindingState.storageBufferBindings[i]);
}
for (Index i = 0; i < m_rootBindingState.uniformBufferBindings.getCount(); i++)
{
@@ -2995,16 +3111,16 @@ SlangResult SLANG_MCALL createGLDevice(const IDevice::Desc* desc, IDevice** outR
return SLANG_OK;
}
-} // gfx
+} // namespace gfx
#else
namespace gfx
{
- SlangResult SLANG_MCALL createGLDevice(const IDevice::Desc* desc, IDevice** outRenderer)
- {
- *outRenderer = nullptr;
- return SLANG_FAIL;
- }
+SlangResult SLANG_MCALL createGLDevice(const IDevice::Desc* desc, IDevice** outRenderer)
+{
+ *outRenderer = nullptr;
+ return SLANG_FAIL;
}
+} // namespace gfx
#endif
diff --git a/tools/gfx/open-gl/render-gl.h b/tools/gfx/open-gl/render-gl.h
index 8595e95d3..89232c088 100644
--- a/tools/gfx/open-gl/render-gl.h
+++ b/tools/gfx/open-gl/render-gl.h
@@ -3,8 +3,9 @@
#include "../renderer-shared.h"
-namespace gfx {
+namespace gfx
+{
SlangResult SLANG_MCALL createGLDevice(const IDevice::Desc* desc, IDevice** outDevice);
-} // gfx
+} // namespace gfx
diff --git a/tools/gfx/render.cpp b/tools/gfx/render.cpp
index 0dd1e5bf5..49d55acc8 100644
--- a/tools/gfx/render.cpp
+++ b/tools/gfx/render.cpp
@@ -1,13 +1,14 @@
// render.cpp
-#include "renderer-shared.h"
-#include "../../source/core/slang-math.h"
#include "../../source/core/slang-blob.h"
-#include "open-gl/render-gl.h"
+#include "../../source/core/slang-math.h"
#include "debug-layer/debug-device.h"
+#include "open-gl/render-gl.h"
+#include "renderer-shared.h"
#include <cstring>
-namespace gfx {
+namespace gfx
+{
using namespace Slang;
Result SLANG_MCALL createD3D11Device(const IDevice::Desc* desc, IDevice** outDevice);
@@ -26,16 +27,16 @@ Result SLANG_MCALL getCUDAAdapters(List<AdapterInfo>& outAdapters);
Result SLANG_MCALL reportD3DLiveObjects();
static bool debugLayerEnabled = false;
-bool isGfxDebugLayerEnabled() { return debugLayerEnabled; }
+bool isGfxDebugLayerEnabled()
+{
+ return debugLayerEnabled;
+}
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Global Renderer Functions !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
#define GFX_FORMAT_SIZE(name, blockSizeInBytes, pixelsPerBlock) {blockSizeInBytes, pixelsPerBlock},
-static const uint32_t s_formatSizeInfo[][2] =
-{
- GFX_FORMAT(GFX_FORMAT_SIZE)
-};
+static const uint32_t s_formatSizeInfo[][2] = {GFX_FORMAT(GFX_FORMAT_SIZE)};
static bool _checkFormat()
{
@@ -43,7 +44,8 @@ static bool _checkFormat()
Index count = 0;
// Check the values are in the same order
-#define GFX_FORMAT_CHECK(name, blockSizeInBytes, pixelsPerblock) count += Index(Index(Format::name) == value++);
+#define GFX_FORMAT_CHECK(name, blockSizeInBytes, pixelsPerblock) \
+ count += Index(Index(Format::name) == value++);
GFX_FORMAT(GFX_FORMAT_CHECK)
const bool r = (count == Index(Format::_Count));
@@ -170,7 +172,12 @@ struct FormatInfoMap
set(Format::BC7_UNORM_SRGB, SLANG_SCALAR_TYPE_FLOAT32, 4, 4, 4);
}
- void set(Format format, SlangScalarType type, Index channelCount, uint32_t blockWidth = 1, uint32_t blockHeight = 1)
+ void set(
+ Format format,
+ SlangScalarType type,
+ Index channelCount,
+ uint32_t blockWidth = 1,
+ uint32_t blockHeight = 1)
{
FormatInfo& info = m_infos[Index(format)];
info.channelCount = uint8_t(channelCount);
@@ -214,10 +221,8 @@ extern "C"
case Format::BC6H_UF16:
case Format::BC6H_SF16:
case Format::BC7_UNORM:
- case Format::BC7_UNORM_SRGB:
- return true;
- default:
- return false;
+ case Format::BC7_UNORM_SRGB: return true;
+ default: return false;
}
}
@@ -236,10 +241,8 @@ extern "C"
case Format::R8G8_TYPELESS:
case Format::R8_TYPELESS:
case Format::B8G8R8A8_TYPELESS:
- case Format::R10G10B10A2_TYPELESS:
- return true;
- default:
- return false;
+ case Format::R10G10B10A2_TYPELESS: return true;
+ default: return false;
}
}
@@ -249,48 +252,35 @@ extern "C"
return SLANG_OK;
}
- SLANG_GFX_API SlangResult SLANG_MCALL gfxGetAdapters(DeviceType type, ISlangBlob** outAdaptersBlob)
+ SLANG_GFX_API SlangResult SLANG_MCALL
+ gfxGetAdapters(DeviceType type, ISlangBlob** outAdaptersBlob)
{
List<AdapterInfo> adapters;
switch (type)
{
#if SLANG_ENABLE_DIRECTX
- case DeviceType::DirectX11:
- SLANG_RETURN_ON_FAIL(getD3D11Adapters(adapters));
- break;
- case DeviceType::DirectX12:
- SLANG_RETURN_ON_FAIL(getD3D12Adapters(adapters));
- break;
+ case DeviceType::DirectX11: SLANG_RETURN_ON_FAIL(getD3D11Adapters(adapters)); break;
+ case DeviceType::DirectX12: SLANG_RETURN_ON_FAIL(getD3D12Adapters(adapters)); break;
#endif
#if SLANG_WINDOWS_FAMILY
- case DeviceType::OpenGl:
- return SLANG_E_NOT_IMPLEMENTED;
+ case DeviceType::OpenGl: return SLANG_E_NOT_IMPLEMENTED;
#endif
#if SLANG_WINDOWS_FAMILY || SLANG_LINUX_FAMILY
// Assume no Vulkan or CUDA on MacOS or Cygwin
- case DeviceType::Vulkan:
- SLANG_RETURN_ON_FAIL(getVKAdapters(adapters));
- break;
- case DeviceType::CUDA:
- SLANG_RETURN_ON_FAIL(getCUDAAdapters(adapters));
- break;
+ case DeviceType::Vulkan: SLANG_RETURN_ON_FAIL(getVKAdapters(adapters)); break;
+ case DeviceType::CUDA: SLANG_RETURN_ON_FAIL(getCUDAAdapters(adapters)); break;
#endif
#if SLANG_APPLE_FAMILY
- case DeviceType::Vulkan:
- SLANG_RETURN_ON_FAIL(getVKAdapters(adapters));
- break;
- case DeviceType::Metal:
- SLANG_RETURN_ON_FAIL(getMetalAdapters(adapters));
- break;
+ case DeviceType::Vulkan: SLANG_RETURN_ON_FAIL(getVKAdapters(adapters)); break;
+ case DeviceType::Metal: SLANG_RETURN_ON_FAIL(getMetalAdapters(adapters)); break;
#endif
- case DeviceType::CPU:
- return SLANG_E_NOT_IMPLEMENTED;
- default:
- return SLANG_E_INVALID_ARG;
+ case DeviceType::CPU: return SLANG_E_NOT_IMPLEMENTED;
+ default: return SLANG_E_INVALID_ARG;
}
- auto adaptersBlob = RawBlob::create(adapters.getBuffer(), adapters.getCount() * sizeof(AdapterInfo));
+ auto adaptersBlob =
+ RawBlob::create(adapters.getBuffer(), adapters.getCount() * sizeof(AdapterInfo));
if (outAdaptersBlob)
returnComPtr(outAdaptersBlob, adaptersBlob);
@@ -340,37 +330,37 @@ extern "C"
break;
#elif SLANG_APPLE_FAMILY
case DeviceType::Vulkan:
- {
- return createVKDevice(desc, outDevice);
- }
+ {
+ return createVKDevice(desc, outDevice);
+ }
case DeviceType::Metal:
- {
- return createMetalDevice(desc, outDevice);
- }
+ {
+ return createMetalDevice(desc, outDevice);
+ }
case DeviceType::Default:
- {
- IDevice::Desc newDesc = *desc;
- newDesc.deviceType = DeviceType::Metal;
- if (_createDevice(&newDesc, outDevice) == SLANG_OK)
- return SLANG_OK;
- newDesc.deviceType = DeviceType::Vulkan;
- if (_createDevice(&newDesc, outDevice) == SLANG_OK)
- return SLANG_OK;
- return SLANG_FAIL;
- }
+ {
+ IDevice::Desc newDesc = *desc;
+ newDesc.deviceType = DeviceType::Metal;
+ if (_createDevice(&newDesc, outDevice) == SLANG_OK)
+ return SLANG_OK;
+ newDesc.deviceType = DeviceType::Vulkan;
+ if (_createDevice(&newDesc, outDevice) == SLANG_OK)
+ return SLANG_OK;
+ return SLANG_FAIL;
+ }
#elif SLANG_LINUX_FAMILY && !defined(__CYGWIN__)
case DeviceType::Vulkan:
- {
- return createVKDevice(desc, outDevice);
- }
+ {
+ return createVKDevice(desc, outDevice);
+ }
case DeviceType::Default:
- {
- IDevice::Desc newDesc = *desc;
- newDesc.deviceType = DeviceType::Vulkan;
- if (_createDevice(&newDesc, outDevice) == SLANG_OK)
- return SLANG_OK;
- return SLANG_FAIL;
- }
+ {
+ IDevice::Desc newDesc = *desc;
+ newDesc.deviceType = DeviceType::Vulkan;
+ if (_createDevice(&newDesc, outDevice) == SLANG_OK)
+ return SLANG_OK;
+ return SLANG_FAIL;
+ }
#endif
case DeviceType::CUDA:
{
@@ -382,13 +372,12 @@ extern "C"
}
break;
- default:
- return SLANG_FAIL;
+ default: return SLANG_FAIL;
}
}
SLANG_GFX_API SlangResult SLANG_MCALL
- gfxCreateDevice(const IDevice::Desc* desc, IDevice** outDevice)
+ gfxCreateDevice(const IDevice::Desc* desc, IDevice** outDevice)
{
ComPtr<IDevice> innerDevice;
auto resultCode = _createDevice(desc, innerDevice.writeRef());
@@ -405,8 +394,7 @@ extern "C"
return resultCode;
}
- SLANG_GFX_API SlangResult SLANG_MCALL
- gfxReportLiveObjects()
+ SLANG_GFX_API SlangResult SLANG_MCALL gfxReportLiveObjects()
{
#if SLANG_ENABLE_DIRECTX
SLANG_RETURN_ON_FAIL(reportD3DLiveObjects());
@@ -429,26 +417,16 @@ extern "C"
{
switch (type)
{
- case gfx::DeviceType::Unknown:
- return "Unknown";
- case gfx::DeviceType::Default:
- return "Default";
- case gfx::DeviceType::DirectX11:
- return "DirectX11";
- case gfx::DeviceType::DirectX12:
- return "DirectX12";
- case gfx::DeviceType::OpenGl:
- return "OpenGL";
- case gfx::DeviceType::Vulkan:
- return "Vulkan";
- case gfx::DeviceType::Metal:
- return "Metal";
- case gfx::DeviceType::CPU:
- return "CPU";
- case gfx::DeviceType::CUDA:
- return "CUDA";
- default:
- return "?";
+ case gfx::DeviceType::Unknown: return "Unknown";
+ case gfx::DeviceType::Default: return "Default";
+ case gfx::DeviceType::DirectX11: return "DirectX11";
+ case gfx::DeviceType::DirectX12: return "DirectX12";
+ case gfx::DeviceType::OpenGl: return "OpenGL";
+ case gfx::DeviceType::Vulkan: return "Vulkan";
+ case gfx::DeviceType::Metal: return "Metal";
+ case gfx::DeviceType::CPU: return "CPU";
+ case gfx::DeviceType::CUDA: return "CUDA";
+ default: return "?";
}
}
@@ -478,4 +456,4 @@ extern "C"
}
}
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/renderer-shared.cpp b/tools/gfx/renderer-shared.cpp
index 65a14c8cb..5a7aa4b64 100644
--- a/tools/gfx/renderer-shared.cpp
+++ b/tools/gfx/renderer-shared.cpp
@@ -1,11 +1,10 @@
#include "renderer-shared.h"
-#include "mutable-shader-object.h"
-#include "core/slang-io.h"
-#include "core/slang-token-reader.h"
-#include "../../source/core/slang-stable-hash.h"
#include "../../source/core/slang-file-system.h"
-
+#include "../../source/core/slang-stable-hash.h"
+#include "core/slang-io.h"
+#include "core/slang-token-reader.h"
+#include "mutable-shader-object.h"
#include "slang.h"
using namespace Slang;
@@ -45,8 +44,10 @@ const Slang::Guid GfxGUID::IID_IQueryPool = SLANG_UUID_IQueryPool;
const Slang::Guid GfxGUID::IID_IAccelerationStructure = SLANG_UUID_IAccelerationStructure;
const Slang::Guid GfxGUID::IID_IFence = SLANG_UUID_IFence;
const Slang::Guid GfxGUID::IID_IShaderTable = SLANG_UUID_IShaderTable;
-const Slang::Guid GfxGUID::IID_IPipelineCreationAPIDispatcher = SLANG_UUID_IPipelineCreationAPIDispatcher;
-const Slang::Guid GfxGUID::IID_IVulkanPipelineCreationAPIDispatcher = SLANG_UUID_IVulkanPipelineCreationAPIDispatcher;
+const Slang::Guid GfxGUID::IID_IPipelineCreationAPIDispatcher =
+ SLANG_UUID_IPipelineCreationAPIDispatcher;
+const Slang::Guid GfxGUID::IID_IVulkanPipelineCreationAPIDispatcher =
+ SLANG_UUID_IVulkanPipelineCreationAPIDispatcher;
const Slang::Guid GfxGUID::IID_ITransientResourceHeapD3D12 = SLANG_UUID_ITransientResourceHeapD3D12;
@@ -54,13 +55,10 @@ StageType translateStage(SlangStage slangStage)
{
switch (slangStage)
{
- default:
- SLANG_ASSERT(!"unhandled case");
- return gfx::StageType::Unknown;
+ default: SLANG_ASSERT(!"unhandled case"); return gfx::StageType::Unknown;
-#define CASE(FROM, TO) \
-case SLANG_STAGE_##FROM: \
-return gfx::StageType::TO
+#define CASE(FROM, TO) \
+ case SLANG_STAGE_##FROM: return gfx::StageType::TO
CASE(VERTEX, Vertex);
CASE(HULL, Hull);
@@ -96,8 +94,14 @@ IResource* BufferResource::getInterface(const Slang::Guid& guid)
return nullptr;
}
-SLANG_NO_THROW IResource::Type SLANG_MCALL BufferResource::getType() { return m_type; }
-SLANG_NO_THROW IBufferResource::Desc* SLANG_MCALL BufferResource::getDesc() { return &m_desc; }
+SLANG_NO_THROW IResource::Type SLANG_MCALL BufferResource::getType()
+{
+ return m_type;
+}
+SLANG_NO_THROW IBufferResource::Desc* SLANG_MCALL BufferResource::getDesc()
+{
+ return &m_desc;
+}
Result BufferResource::getNativeResourceHandle(InteropHandle* outHandle)
{
@@ -121,8 +125,14 @@ IResource* TextureResource::getInterface(const Slang::Guid& guid)
return nullptr;
}
-SLANG_NO_THROW IResource::Type SLANG_MCALL TextureResource::getType() { return m_type; }
-SLANG_NO_THROW ITextureResource::Desc* SLANG_MCALL TextureResource::getDesc() { return &m_desc; }
+SLANG_NO_THROW IResource::Type SLANG_MCALL TextureResource::getType()
+{
+ return m_type;
+}
+SLANG_NO_THROW ITextureResource::Desc* SLANG_MCALL TextureResource::getDesc()
+{
+ return &m_desc;
+}
Result TextureResource::getNativeResourceHandle(InteropHandle* outHandle)
{
@@ -140,25 +150,24 @@ Result TextureResource::getSharedHandle(InteropHandle* outHandle)
StageType mapStage(SlangStage stage)
{
- switch( stage )
+ switch (stage)
{
- default:
- return StageType::Unknown;
-
- case SLANG_STAGE_AMPLIFICATION: return gfx::StageType::Amplification;
- case SLANG_STAGE_ANY_HIT: return gfx::StageType::AnyHit;
- case SLANG_STAGE_CALLABLE: return gfx::StageType::Callable;
- case SLANG_STAGE_CLOSEST_HIT: return gfx::StageType::ClosestHit;
- case SLANG_STAGE_COMPUTE: return gfx::StageType::Compute;
- case SLANG_STAGE_DOMAIN: return gfx::StageType::Domain;
- case SLANG_STAGE_FRAGMENT: return gfx::StageType::Fragment;
- case SLANG_STAGE_GEOMETRY: return gfx::StageType::Geometry;
- case SLANG_STAGE_HULL: return gfx::StageType::Hull;
- case SLANG_STAGE_INTERSECTION: return gfx::StageType::Intersection;
- case SLANG_STAGE_MESH: return gfx::StageType::Mesh;
- case SLANG_STAGE_MISS: return gfx::StageType::Miss;
- case SLANG_STAGE_RAY_GENERATION: return gfx::StageType::RayGeneration;
- case SLANG_STAGE_VERTEX: return gfx::StageType::Vertex;
+ default: return StageType::Unknown;
+
+ case SLANG_STAGE_AMPLIFICATION: return gfx::StageType::Amplification;
+ case SLANG_STAGE_ANY_HIT: return gfx::StageType::AnyHit;
+ case SLANG_STAGE_CALLABLE: return gfx::StageType::Callable;
+ case SLANG_STAGE_CLOSEST_HIT: return gfx::StageType::ClosestHit;
+ case SLANG_STAGE_COMPUTE: return gfx::StageType::Compute;
+ case SLANG_STAGE_DOMAIN: return gfx::StageType::Domain;
+ case SLANG_STAGE_FRAGMENT: return gfx::StageType::Fragment;
+ case SLANG_STAGE_GEOMETRY: return gfx::StageType::Geometry;
+ case SLANG_STAGE_HULL: return gfx::StageType::Hull;
+ case SLANG_STAGE_INTERSECTION: return gfx::StageType::Intersection;
+ case SLANG_STAGE_MESH: return gfx::StageType::Mesh;
+ case SLANG_STAGE_MISS: return gfx::StageType::Miss;
+ case SLANG_STAGE_RAY_GENERATION: return gfx::StageType::RayGeneration;
+ case SLANG_STAGE_VERTEX: return gfx::StageType::Vertex;
}
}
@@ -199,8 +208,8 @@ IAccelerationStructure* AccelerationStructureBase::getInterface(const Slang::Gui
}
bool _doesValueFitInExistentialPayload(
- slang::TypeLayoutReflection* concreteTypeLayout,
- slang::TypeLayoutReflection* existentialTypeLayout)
+ slang::TypeLayoutReflection* concreteTypeLayout,
+ slang::TypeLayoutReflection* existentialTypeLayout)
{
// Our task here is to figure out if a value of `concreteTypeLayout`
// can fit into an existential value using `existentialTypelayout`.
@@ -220,7 +229,7 @@ bool _doesValueFitInExistentialPayload(
// If the concrete type consumes more ordinary bytes than we have in the payload,
// it cannot possibly fit.
//
- if(concreteValueSize > existentialPayloadSize)
+ if (concreteValueSize > existentialPayloadSize)
return false;
// It is possible that the ordinary bytes of `concreteTypeLayout` can fit
@@ -229,25 +238,24 @@ bool _doesValueFitInExistentialPayload(
// data can't fit in the payload at all.
//
auto categoryCount = concreteTypeLayout->getCategoryCount();
- for(unsigned int i = 0; i < categoryCount; ++i)
+ for (unsigned int i = 0; i < categoryCount; ++i)
{
auto category = concreteTypeLayout->getCategoryByIndex(i);
- switch(category)
+ switch (category)
{
// We want to ignore any ordinary/uniform data usage, since that
// was already checked above.
//
- case slang::ParameterCategory::Uniform:
- break;
+ case slang::ParameterCategory::Uniform: break;
// Any other kind of data consumed means the value cannot possibly fit.
default:
return false;
- // TODO: Are there any cases of resource usage that need to be ignored here?
- // E.g., if the sub-object contains its own existential-type fields (which
- // get reflected as consuming "existential value" storage) should that be
- // ignored?
+ // TODO: Are there any cases of resource usage that need to be ignored here?
+ // E.g., if the sub-object contains its own existential-type fields (which
+ // get reflected as consuming "existential value" storage) should that be
+ // ignored?
}
}
@@ -356,7 +364,11 @@ Result RendererBase::getEntryPointCodeFromShaderCache(
if (persistentShaderCache->readEntry(cacheKey, codeBlob.writeRef()) != SLANG_OK)
{
// No cached entry found. Generate the code and add it to the cache.
- SLANG_RETURN_ON_FAIL(program->getEntryPointCode(entryPointIndex, targetIndex, codeBlob.writeRef(), outDiagnostics));
+ SLANG_RETURN_ON_FAIL(program->getEntryPointCode(
+ entryPointIndex,
+ targetIndex,
+ codeBlob.writeRef(),
+ outDiagnostics));
persistentShaderCache->writeEntry(cacheKey, codeBlob);
}
@@ -419,8 +431,8 @@ SLANG_NO_THROW Result SLANG_MCALL RendererBase::getNativeDeviceHandles(InteropHa
return SLANG_OK;
}
-SLANG_NO_THROW Result SLANG_MCALL RendererBase::getFeatures(
- const char** outFeatures, Size bufferSize, GfxCount* outFeatureCount)
+SLANG_NO_THROW Result SLANG_MCALL
+RendererBase::getFeatures(const char** outFeatures, Size bufferSize, GfxCount* outFeatureCount)
{
if (bufferSize >= (UInt)m_features.getCount())
{
@@ -534,7 +546,8 @@ SLANG_NO_THROW Result SLANG_MCALL RendererBase::createShaderObject2(
IShaderObject** outObject)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
- SLANG_RETURN_ON_FAIL(getShaderObjectLayout(slangSession, type, container, shaderObjectLayout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ getShaderObjectLayout(slangSession, type, container, shaderObjectLayout.writeRef()));
return createShaderObject(shaderObjectLayout, outObject);
}
@@ -553,7 +566,8 @@ SLANG_NO_THROW Result SLANG_MCALL RendererBase::createMutableShaderObject2(
IShaderObject** outObject)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
- SLANG_RETURN_ON_FAIL(getShaderObjectLayout(slangSession, type, containerType, shaderObjectLayout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ getShaderObjectLayout(slangSession, type, containerType, shaderObjectLayout.writeRef()));
return createMutableShaderObject(shaderObjectLayout, outObject);
}
@@ -567,7 +581,7 @@ Result RendererBase::createProgram2(
ComPtr<slang::IBlob> diagnosticsBlob;
switch (desc.sourceType)
{
- case ShaderModuleSourceType::SlangSourceFile:
+ case ShaderModuleSourceType::SlangSourceFile:
{
auto fileName = (char*)desc.sourceData;
module = slangSession->loadModule(fileName, diagnosticsBlob.writeRef());
@@ -575,18 +589,21 @@ Result RendererBase::createProgram2(
return SLANG_FAIL;
break;
}
- case ShaderModuleSourceType::SlangSource:
+ case ShaderModuleSourceType::SlangSource:
{
auto hash = getStableHashCode32((char*)desc.sourceData, desc.sourceDataSize);
auto hashStr = String(hash);
auto srcBlob = UnownedRawBlob::create(desc.sourceData, desc.sourceDataSize);
- module = slangSession->loadModuleFromSource(hashStr.getBuffer(), hashStr.getBuffer(), srcBlob, diagnosticsBlob.writeRef());
+ module = slangSession->loadModuleFromSource(
+ hashStr.getBuffer(),
+ hashStr.getBuffer(),
+ srcBlob,
+ diagnosticsBlob.writeRef());
if (!module)
return SLANG_FAIL;
break;
}
- default:
- SLANG_RELEASE_ASSERT(false);
+ default: SLANG_RELEASE_ASSERT(false);
}
Slang::List<ComPtr<slang::IComponentType>> componentTypes;
@@ -606,7 +623,8 @@ Result RendererBase::createProgram2(
for (GfxCount i = 0; i < desc.entryPointCount; i++)
{
ComPtr<slang::IEntryPoint> entryPoint;
- SLANG_RETURN_ON_FAIL(module->findEntryPointByName(desc.entryPointNames[i], entryPoint.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ module->findEntryPointByName(desc.entryPointNames[i], entryPoint.writeRef()));
componentTypes.add(ComPtr<slang::IComponentType>(entryPoint.get()));
}
}
@@ -631,18 +649,22 @@ Result RendererBase::createProgram2(
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createShaderObjectFromTypeLayout(
- slang::TypeLayoutReflection* typeLayout, IShaderObject** outObject)
+ slang::TypeLayoutReflection* typeLayout,
+ IShaderObject** outObject)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
- SLANG_RETURN_ON_FAIL(getShaderObjectLayout(slangContext.session, typeLayout, shaderObjectLayout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ getShaderObjectLayout(slangContext.session, typeLayout, shaderObjectLayout.writeRef()));
return createShaderObject(shaderObjectLayout, outObject);
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createMutableShaderObjectFromTypeLayout(
- slang::TypeLayoutReflection* typeLayout, IShaderObject** outObject)
+ slang::TypeLayoutReflection* typeLayout,
+ IShaderObject** outObject)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
- SLANG_RETURN_ON_FAIL(getShaderObjectLayout(slangContext.session, typeLayout, shaderObjectLayout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ getShaderObjectLayout(slangContext.session, typeLayout, shaderObjectLayout.writeRef()));
return createMutableShaderObject(shaderObjectLayout, outObject);
}
@@ -671,7 +693,9 @@ Result RendererBase::createShaderTable(const IShaderTable::Desc& desc, IShaderTa
return SLANG_E_NOT_AVAILABLE;
}
-Result RendererBase::createRayTracingPipelineState(const RayTracingPipelineStateDesc& desc, IPipelineState** outState)
+Result RendererBase::createRayTracingPipelineState(
+ const RayTracingPipelineStateDesc& desc,
+ IPipelineState** outState)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outState);
@@ -679,7 +703,8 @@ Result RendererBase::createRayTracingPipelineState(const RayTracingPipelineState
}
Result RendererBase::createMutableRootShaderObject(
- IShaderProgram* program, IShaderObject** outObject)
+ IShaderProgram* program,
+ IShaderObject** outObject)
{
SLANG_UNUSED(program);
SLANG_UNUSED(outObject);
@@ -694,7 +719,11 @@ Result RendererBase::createFence(const IFence::Desc& desc, IFence** outFence)
}
Result RendererBase::waitForFences(
- GfxCount fenceCount, IFence** fences, uint64_t* fenceValues, bool waitForAll, uint64_t timeout)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* fenceValues,
+ bool waitForAll,
+ uint64_t timeout)
{
SLANG_UNUSED(fenceCount);
SLANG_UNUSED(fences);
@@ -705,7 +734,9 @@ Result RendererBase::waitForFences(
}
Result RendererBase::getTextureAllocationInfo(
- const ITextureResource::Desc& desc, Size* outSize, Size* outAlignment)
+ const ITextureResource::Desc& desc,
+ Size* outSize,
+ Size* outAlignment)
{
SLANG_UNUSED(desc);
*outSize = 0;
@@ -733,8 +764,7 @@ Result RendererBase::getShaderObjectLayout(
case ShaderObjectContainerType::Array:
type = session->getContainerType(type, slang::ContainerType::UnsizedArray);
break;
- default:
- break;
+ default: break;
}
auto typeLayout = session->getTypeLayout(type);
@@ -751,7 +781,8 @@ Result RendererBase::getShaderObjectLayout(
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
if (!m_shaderObjectLayoutCache.tryGetValue(typeLayout, shaderObjectLayout))
{
- SLANG_RETURN_ON_FAIL(createShaderObjectLayout(session, typeLayout, shaderObjectLayout.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ createShaderObjectLayout(session, typeLayout, shaderObjectLayout.writeRef()));
m_shaderObjectLayoutCache.add(typeLayout, shaderObjectLayout);
}
*outLayout = shaderObjectLayout.detach();
@@ -799,16 +830,17 @@ ShaderComponentID ShaderCache::getComponentId(slang::TypeReflection* type)
StringBuilder builder;
builder.append(UnownedTerminatedStringSlice(baseType->getName()));
- auto rawType = (SlangReflectionType*) type;
+ auto rawType = (SlangReflectionType*)type;
builder.appendChar('<');
SlangInt argCount = spReflectionType_getSpecializedTypeArgCount(rawType);
- for(SlangInt a = 0; a < argCount; ++a)
+ for (SlangInt a = 0; a < argCount; ++a)
{
- if(a != 0) builder.appendChar(',');
- if(auto rawArgType = spReflectionType_getSpecializedTypeArgType(rawType, a))
+ if (a != 0)
+ builder.appendChar(',');
+ if (auto rawArgType = spReflectionType_getSpecializedTypeArgType(rawType, a))
{
- auto argType = (slang::TypeReflection*) rawArgType;
+ auto argType = (slang::TypeReflection*)rawArgType;
builder.append(argType->getName());
}
}
@@ -819,8 +851,7 @@ ShaderComponentID ShaderCache::getComponentId(slang::TypeReflection* type)
}
// TODO: collect specialization arguments and append them to `key`.
SLANG_UNIMPLEMENTED_X("specialized type");
- default:
- break;
+ default: break;
}
key.updateHash();
return getComponentId(key);
@@ -848,12 +879,17 @@ ShaderComponentID ShaderCache::getComponentId(ComponentKey key)
return resultId;
}
-void ShaderCache::addSpecializedPipeline(PipelineKey key, Slang::RefPtr<PipelineStateBase> specializedPipeline)
+void ShaderCache::addSpecializedPipeline(
+ PipelineKey key,
+ Slang::RefPtr<PipelineStateBase> specializedPipeline)
{
specializedPipelines[key] = specializedPipeline;
}
-void ShaderObjectLayoutBase::initBase(RendererBase* renderer, slang::ISession* session, slang::TypeLayoutReflection* elementTypeLayout)
+void ShaderObjectLayoutBase::initBase(
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::TypeLayoutReflection* elementTypeLayout)
{
m_renderer = renderer;
m_slangSession = session;
@@ -861,8 +897,9 @@ void ShaderObjectLayoutBase::initBase(RendererBase* renderer, slang::ISession* s
m_componentID = m_renderer->shaderCache.getComponentId(m_elementTypeLayout->getType());
}
-// Get the final type this shader object represents. If the shader object's type has existential fields,
-// this function will return a specialized type using the bound sub-objects' type as specialization argument.
+// Get the final type this shader object represents. If the shader object's type has existential
+// fields, this function will return a specialized type using the bound sub-objects' type as
+// specialization argument.
Result ShaderObjectBase::getSpecializedShaderObjectType(ExtendedShaderObjectType* outType)
{
return _getSpecializedShaderObjectType(outType);
@@ -883,8 +920,10 @@ Result ShaderObjectBase::_getSpecializedShaderObjectType(ExtendedShaderObjectTyp
{
shaderObjectType.slangType = getRenderer()->slangContext.session->specializeType(
_getElementTypeLayout()->getType(),
- specializationArgs.components.getArrayView().getBuffer(), specializationArgs.getCount());
- shaderObjectType.componentID = getRenderer()->shaderCache.getComponentId(shaderObjectType.slangType);
+ specializationArgs.components.getArrayView().getBuffer(),
+ specializationArgs.getCount());
+ shaderObjectType.componentID =
+ getRenderer()->shaderCache.getComponentId(shaderObjectType.slangType);
}
*outType = shaderObjectType;
return SLANG_OK;
@@ -917,7 +956,9 @@ Result ShaderObjectBase::setExistentialHeader(
//
uint32_t conformanceID = 0xFFFFFFFF;
SLANG_RETURN_ON_FAIL(getLayoutBase()->m_slangSession->getTypeConformanceWitnessSequentialID(
- concreteType, existentialType, &conformanceID));
+ concreteType,
+ existentialType,
+ &conformanceID));
//
// Once we have the conformance ID, then we can write it into the object
// at the required offset.
@@ -945,7 +986,9 @@ ResourceViewBase* SimpleShaderObjectData::getResourceView(
desc.sizeInBytes = (Size)m_ordinaryData.getCount();
ComPtr<IBufferResource> bufferResource;
SLANG_RETURN_NULL_ON_FAIL(device->createBufferResource(
- desc, m_ordinaryData.getBuffer(), bufferResource.writeRef()));
+ desc,
+ m_ordinaryData.getBuffer(),
+ bufferResource.writeRef()));
m_structuredBuffer = static_cast<BufferResource*>(bufferResource.get());
// Create read-only (shader-resource) and mutable (unordered access) views.
@@ -954,24 +997,25 @@ ResourceViewBase* SimpleShaderObjectData::getResourceView(
viewDesc.format = Format::Unknown;
viewDesc.type = IResourceView::Type::ShaderResource;
SLANG_RETURN_NULL_ON_FAIL(device->createBufferView(
- bufferResource.get(), nullptr, viewDesc, resourceView.writeRef()));
+ bufferResource.get(),
+ nullptr,
+ viewDesc,
+ resourceView.writeRef()));
m_structuredBufferView = static_cast<ResourceViewBase*>(resourceView.get());
viewDesc.type = IResourceView::Type::UnorderedAccess;
- SLANG_RETURN_NULL_ON_FAIL(
- device->createBufferView(
- bufferResource.get(), nullptr, viewDesc, resourceView.writeRef()));
+ SLANG_RETURN_NULL_ON_FAIL(device->createBufferView(
+ bufferResource.get(),
+ nullptr,
+ viewDesc,
+ resourceView.writeRef()));
m_rwStructuredBufferView = static_cast<ResourceViewBase*>(resourceView.get());
}
switch (bindingType)
{
- case slang::BindingType::RawBuffer:
- return m_structuredBufferView.Ptr();
- case slang::BindingType::MutableRawBuffer:
- return m_rwStructuredBufferView.Ptr();
- default:
- SLANG_ASSERT(false && "Invalid binding type.");
- return nullptr;
+ case slang::BindingType::RawBuffer: return m_structuredBufferView.Ptr();
+ case slang::BindingType::MutableRawBuffer: return m_rwStructuredBufferView.Ptr();
+ default: SLANG_ASSERT(false && "Invalid binding type."); return nullptr;
}
}
@@ -1002,7 +1046,9 @@ void ShaderProgramBase::init(const IShaderProgram::Desc& inDesc)
components.add(desc.slangEntryPoints[i]);
}
session->createCompositeComponentType(
- components.getBuffer(), components.getCount(), linkedProgram.writeRef());
+ components.getBuffer(),
+ components.getCount(),
+ linkedProgram.writeRef());
}
else
{
@@ -1011,10 +1057,13 @@ void ShaderProgramBase::init(const IShaderProgram::Desc& inDesc)
if (desc.slangGlobalScope)
{
slang::IComponentType* entryPointComponents[2] = {
- desc.slangGlobalScope, desc.slangEntryPoints[i]};
+ desc.slangGlobalScope,
+ desc.slangEntryPoints[i]};
ComPtr<slang::IComponentType> linkedEntryPoint;
session->createCompositeComponentType(
- entryPointComponents, 2, linkedEntryPoint.writeRef());
+ entryPointComponents,
+ 2,
+ linkedEntryPoint.writeRef());
linkedEntryPoints.add(linkedEntryPoint);
}
else
@@ -1036,8 +1085,12 @@ Result ShaderProgramBase::compileShaders(RendererBase* device)
auto stage = entryPointInfo->getStage();
ComPtr<ISlangBlob> kernelCode;
ComPtr<ISlangBlob> diagnostics;
- auto compileResult = device->getEntryPointCodeFromShaderCache(entryPointComponent,
- entryPointIndex, 0, kernelCode.writeRef(), diagnostics.writeRef());
+ auto compileResult = device->getEntryPointCodeFromShaderCache(
+ entryPointComponent,
+ entryPointIndex,
+ 0,
+ kernelCode.writeRef(),
+ diagnostics.writeRef());
if (diagnostics)
{
DebugMessageType msgType = DebugMessageType::Warning;
@@ -1061,7 +1114,9 @@ Result ShaderProgramBase::compileShaders(RendererBase* device)
for (SlangUInt i = 0; i < programReflection->getEntryPointCount(); i++)
{
SLANG_RETURN_ON_FAIL(compileShader(
- programReflection->getEntryPointByIndex(i), linkedProgram, (SlangInt)i));
+ programReflection->getEntryPointByIndex(i),
+ linkedProgram,
+ (SlangInt)i));
}
}
else
@@ -1078,7 +1133,8 @@ Result ShaderProgramBase::compileShaders(RendererBase* device)
}
Result ShaderProgramBase::createShaderModule(
- slang::EntryPointReflection* entryPointInfo, ComPtr<ISlangBlob> kernelCode)
+ slang::EntryPointReflection* entryPointInfo,
+ ComPtr<ISlangBlob> kernelCode)
{
SLANG_UNUSED(entryPointInfo);
SLANG_UNUSED(kernelCode);
@@ -1089,17 +1145,17 @@ bool ShaderProgramBase::isMeshShaderProgram() const
{
// Similar to above, interrogate either explicity specified entry point
// componenets or the ones in the linked program entry point array
- if(linkedEntryPoints.getCount())
+ if (linkedEntryPoints.getCount())
{
- for(const auto& e : linkedEntryPoints)
- if(e->getLayout()->getEntryPointByIndex(0)->getStage() == SLANG_STAGE_MESH)
+ for (const auto& e : linkedEntryPoints)
+ if (e->getLayout()->getEntryPointByIndex(0)->getStage() == SLANG_STAGE_MESH)
return true;
}
else
{
const auto programReflection = linkedProgram->getLayout();
- for(SlangUInt i = 0; i < programReflection->getEntryPointCount(); ++i)
- if(programReflection->getEntryPointByIndex(i)->getStage() == SLANG_STAGE_MESH)
+ for (SlangUInt i = 0; i < programReflection->getEntryPointCount(); ++i)
+ if (programReflection->getEntryPointByIndex(i)->getStage() == SLANG_STAGE_MESH)
return true;
}
return false;
@@ -1111,11 +1167,12 @@ Result RendererBase::maybeSpecializePipeline(
RefPtr<PipelineStateBase>& outNewPipeline)
{
outNewPipeline = static_cast<PipelineStateBase*>(currentPipeline);
-
+
auto pipelineType = currentPipeline->desc.type;
if (currentPipeline->unspecializedPipelineState)
currentPipeline = currentPipeline->unspecializedPipelineState;
- // If the currently bound pipeline is specializable, we need to specialize it based on bound shader objects.
+ // If the currently bound pipeline is specializable, we need to specialize it based on bound
+ // shader objects.
if (currentPipeline->isSpecializable)
{
specializationArgs.clear();
@@ -1127,13 +1184,14 @@ Result RendererBase::maybeSpecializePipeline(
pipelineKey.specializationArgs.addRange(specializationArgs.componentIDs);
pipelineKey.updateHash();
- RefPtr<PipelineStateBase> specializedPipelineState = shaderCache.getSpecializedPipelineState(pipelineKey);
+ RefPtr<PipelineStateBase> specializedPipelineState =
+ shaderCache.getSpecializedPipelineState(pipelineKey);
// Try to find specialized pipeline from shader cache.
if (!specializedPipelineState)
{
- auto unspecializedProgram = static_cast<ShaderProgramBase*>(pipelineType == PipelineType::Compute
- ? currentPipeline->desc.compute.program
- : currentPipeline->desc.graphics.program);
+ auto unspecializedProgram = static_cast<ShaderProgramBase*>(
+ pipelineType == PipelineType::Compute ? currentPipeline->desc.compute.program
+ : currentPipeline->desc.graphics.program);
auto unspecializedProgramLayout = unspecializedProgram->linkedProgram->getLayout();
ComPtr<slang::IComponentType> specializedComponentType;
@@ -1159,50 +1217,56 @@ Result RendererBase::maybeSpecializePipeline(
if (specializedProgramDesc.linkingStyle == IShaderProgram::LinkingStyle::SingleProgram)
{
- // When linking style is GraphicsCompute, the specialized global scope already contains
- // entry-points, so we do not need to supply them again when creating the specialized
- // pipeline.
+ // When linking style is GraphicsCompute, the specialized global scope already
+ // contains entry-points, so we do not need to supply them again when creating the
+ // specialized pipeline.
specializedProgramDesc.entryPointCount = 0;
}
- SLANG_RETURN_ON_FAIL(createProgram(specializedProgramDesc, specializedProgram.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ createProgram(specializedProgramDesc, specializedProgram.writeRef()));
// Create specialized pipeline state.
ComPtr<IPipelineState> specializedPipelineComPtr;
switch (pipelineType)
{
case PipelineType::Compute:
- {
- auto pipelineDesc = currentPipeline->desc.compute;
- pipelineDesc.program = specializedProgram;
- SLANG_RETURN_ON_FAIL(
- createComputePipelineState(pipelineDesc, specializedPipelineComPtr.writeRef()));
- break;
- }
+ {
+ auto pipelineDesc = currentPipeline->desc.compute;
+ pipelineDesc.program = specializedProgram;
+ SLANG_RETURN_ON_FAIL(createComputePipelineState(
+ pipelineDesc,
+ specializedPipelineComPtr.writeRef()));
+ break;
+ }
case PipelineType::Graphics:
- {
- auto pipelineDesc = currentPipeline->desc.graphics;
- pipelineDesc.program = static_cast<ShaderProgramBase*>(specializedProgram.get());
- SLANG_RETURN_ON_FAIL(createGraphicsPipelineState(
- pipelineDesc, specializedPipelineComPtr.writeRef()));
- break;
- }
+ {
+ auto pipelineDesc = currentPipeline->desc.graphics;
+ pipelineDesc.program =
+ static_cast<ShaderProgramBase*>(specializedProgram.get());
+ SLANG_RETURN_ON_FAIL(createGraphicsPipelineState(
+ pipelineDesc,
+ specializedPipelineComPtr.writeRef()));
+ break;
+ }
case PipelineType::RayTracing:
- {
- auto pipelineDesc = currentPipeline->desc.rayTracing;
- pipelineDesc.program = static_cast<ShaderProgramBase*>(specializedProgram.get());
- SLANG_RETURN_ON_FAIL(createRayTracingPipelineState(
- pipelineDesc.get(), specializedPipelineComPtr.writeRef()));
- break;
- }
- default:
- break;
+ {
+ auto pipelineDesc = currentPipeline->desc.rayTracing;
+ pipelineDesc.program =
+ static_cast<ShaderProgramBase*>(specializedProgram.get());
+ SLANG_RETURN_ON_FAIL(createRayTracingPipelineState(
+ pipelineDesc.get(),
+ specializedPipelineComPtr.writeRef()));
+ break;
+ }
+ default: break;
}
specializedPipelineState =
static_cast<PipelineStateBase*>(specializedPipelineComPtr.get());
specializedPipelineState->unspecializedPipelineState = currentPipeline;
shaderCache.addSpecializedPipeline(pipelineKey, specializedPipelineState);
}
- auto specializedPipelineStateBase = static_cast<PipelineStateBase*>(specializedPipelineState.Ptr());
+ auto specializedPipelineStateBase =
+ static_cast<PipelineStateBase*>(specializedPipelineState.Ptr());
outNewPipeline = specializedPipelineStateBase;
}
return SLANG_OK;
@@ -1218,7 +1282,7 @@ class NullDebugCallback : public IDebugCallback
{
public:
virtual SLANG_NO_THROW void SLANG_MCALL
- handleMessage(DebugMessageType type, DebugMessageSource source, const char* message) override
+ handleMessage(DebugMessageType type, DebugMessageSource source, const char* message) override
{
SLANG_UNUSED(type);
SLANG_UNUSED(source);
@@ -1235,7 +1299,10 @@ Result ShaderObjectBase::copyFrom(IShaderObject* object, ITransientResourceHeap*
{
if (auto srcObj = dynamic_cast<MutableRootShaderObject*>(object))
{
- setData(gfx::ShaderOffset(), srcObj->m_data.begin(), (size_t)srcObj->m_data.getCount()); // TODO: Change size_t to Count?
+ setData(
+ gfx::ShaderOffset(),
+ srcObj->m_data.begin(),
+ (size_t)srcObj->m_data.getCount()); // TODO: Change size_t to Count?
for (auto& kv : srcObj->m_objects)
{
ComPtr<IShaderObject> subObject;
@@ -1265,8 +1332,12 @@ Result ShaderTableBase::init(const IShaderTable::Desc& desc)
m_missShaderCount = desc.missShaderCount;
m_hitGroupCount = desc.hitGroupCount;
m_callableShaderCount = desc.callableShaderCount;
- m_shaderGroupNames.reserve(desc.hitGroupCount + desc.missShaderCount + desc.rayGenShaderCount + desc.callableShaderCount);
- m_recordOverwrites.reserve(desc.hitGroupCount + desc.missShaderCount + desc.rayGenShaderCount + desc.callableShaderCount);
+ m_shaderGroupNames.reserve(
+ desc.hitGroupCount + desc.missShaderCount + desc.rayGenShaderCount +
+ desc.callableShaderCount);
+ m_recordOverwrites.reserve(
+ desc.hitGroupCount + desc.missShaderCount + desc.rayGenShaderCount +
+ desc.callableShaderCount);
for (GfxIndex i = 0; i < desc.rayGenShaderCount; i++)
{
m_shaderGroupNames.add(desc.rayGenShaderEntryPointNames[i]);
@@ -1324,10 +1395,8 @@ bool isDepthFormat(Format format)
{
case Format::D16_UNORM:
case Format::D32_FLOAT:
- case Format::D32_FLOAT_S8_UINT:
- return true;
- default:
- return false;
+ case Format::D32_FLOAT_S8_UINT: return true;
+ default: return false;
}
}
@@ -1335,12 +1404,9 @@ bool isStencilFormat(Format format)
{
switch (format)
{
- case Format::D32_FLOAT_S8_UINT:
- return true;
- default:
- return false;
+ case Format::D32_FLOAT_S8_UINT: return true;
+ default: return false;
}
}
} // namespace gfx
-
diff --git a/tools/gfx/renderer-shared.h b/tools/gfx/renderer-shared.h
index 952beb2c1..72b35d8fa 100644
--- a/tools/gfx/renderer-shared.h
+++ b/tools/gfx/renderer-shared.h
@@ -1,12 +1,11 @@
#pragma once
-#include "slang-gfx.h"
-#include "slang-context.h"
#include "core/slang-basic.h"
#include "core/slang-com-object.h"
#include "core/slang-persistent-cache.h"
-
#include "resource-desc-utils.h"
+#include "slang-context.h"
+#include "slang-gfx.h"
namespace gfx
{
@@ -64,7 +63,7 @@ bool isGfxDebugLayerEnabled();
// If we know there is a cyclic reference between an API object and the device/pool that creates it,
// we can break the cycle when there is no longer any public references that come from `ComPtr`s to
// the API object, by turning the reference to the device object from the API object to a weak
-// reference.
+// reference.
// The following example illustrate how this mechanism works:
// Suppose we have
// ```
@@ -80,24 +79,25 @@ bool isGfxDebugLayerEnabled();
// device->m_currentResource = res;
// ```
// This setup is robust to any destruction ordering. If user releases reference to `device` first,
-// then the device object will not be freed yet, since there is still a strong reference to the device
-// implementation via `res->m_device`. Next when the user releases reference to `res`, the public
-// reference count to `res` via `ComPtr`s will go to 0, therefore triggering the call to
-// `res->m_device.breakStrongReference()`, releasing the remaining reference to device. This will cause
-// `device` to start destruction, which will release its strong reference to `res` during execution of
-// its destructor. Finally, this will triger the actual destruction of `res`.
-// On the other hand, if the user releases reference to `res` first, then the strong reference to `device`
-// will be broken immediately, but the actual destruction of `res` will not start. Next when the user
-// releases `device`, there will no longer be any other references to `device`, so the destruction of
-// `device` will start, causing the release of the internal reference to `res`, leading to its destruction.
-// Note that the above logic only works if it is known that there is a cyclic reference. If there are no
-// such cyclic reference, then it will be incorrect to break the strong reference to `IDevice` upon
-// public reference counter dropping to 0. This is because the actual destructor of `res` take place
-// after breaking the cycle, but if the resource's strong reference to the device is already the last reference,
-// turning that reference to weak reference will immediately trigger destruction of `device`, after which
-// we can no longer destruct `res` if the destructor needs `device`. Therefore we need to be careful
-// when using `BreakableReference`, and make sure we only call `breakStrongReference` only when it is known
-// that there is a cyclic reference. Luckily for all scenarios so far this is statically known.
+// then the device object will not be freed yet, since there is still a strong reference to the
+// device implementation via `res->m_device`. Next when the user releases reference to `res`, the
+// public reference count to `res` via `ComPtr`s will go to 0, therefore triggering the call to
+// `res->m_device.breakStrongReference()`, releasing the remaining reference to device. This will
+// cause `device` to start destruction, which will release its strong reference to `res` during
+// execution of its destructor. Finally, this will triger the actual destruction of `res`. On the
+// other hand, if the user releases reference to `res` first, then the strong reference to `device`
+// will be broken immediately, but the actual destruction of `res` will not start. Next when the
+// user releases `device`, there will no longer be any other references to `device`, so the
+// destruction of `device` will start, causing the release of the internal reference to `res`,
+// leading to its destruction. Note that the above logic only works if it is known that there is a
+// cyclic reference. If there are no such cyclic reference, then it will be incorrect to break the
+// strong reference to `IDevice` upon public reference counter dropping to 0. This is because the
+// actual destructor of `res` take place after breaking the cycle, but if the resource's strong
+// reference to the device is already the last reference, turning that reference to weak reference
+// will immediately trigger destruction of `device`, after which we can no longer destruct `res` if
+// the destructor needs `device`. Therefore we need to be careful when using `BreakableReference`,
+// and make sure we only call `breakStrongReference` only when it is known that there is a cyclic
+// reference. Luckily for all scenarios so far this is statically known.
template<typename T>
class BreakableReference
{
@@ -112,7 +112,11 @@ public:
BreakableReference(Slang::RefPtr<T> const& p) { *this = p; }
- void setWeakReference(T* p) { m_weakPtr = p; m_strongPtr = nullptr; }
+ void setWeakReference(T* p)
+ {
+ m_weakPtr = p;
+ m_strongPtr = nullptr;
+ }
T& operator*() const { return *get(); }
@@ -150,7 +154,7 @@ void returnComPtr(TInterface** outInterface, TImpl* rawPtr)
*outInterface = rawPtr;
}
-template <typename TInterface, typename TImpl>
+template<typename TInterface, typename TImpl>
void returnComPtr(TInterface** outInterface, const Slang::RefPtr<TImpl>& refPtr)
{
static_assert(
@@ -160,7 +164,7 @@ void returnComPtr(TInterface** outInterface, const Slang::RefPtr<TImpl>& refPtr)
*outInterface = refPtr.Ptr();
}
-template <typename TInterface, typename TImpl>
+template<typename TInterface, typename TImpl>
void returnComPtr(TInterface** outInterface, Slang::ComPtr<TImpl>& comPtr)
{
static_assert(
@@ -170,24 +174,28 @@ void returnComPtr(TInterface** outInterface, Slang::ComPtr<TImpl>& comPtr)
}
// Helpers for returning an object implementation as RefPtr.
-template <typename TDest, typename TImpl>
+template<typename TDest, typename TImpl>
void returnRefPtr(TDest** outPtr, Slang::RefPtr<TImpl>& refPtr)
{
static_assert(
- std::is_base_of<Slang::RefObject, TDest>::value, "TDest must be a non-interface type.");
+ std::is_base_of<Slang::RefObject, TDest>::value,
+ "TDest must be a non-interface type.");
static_assert(
- std::is_base_of<Slang::RefObject, TImpl>::value, "TImpl must be a non-interface type.");
+ std::is_base_of<Slang::RefObject, TImpl>::value,
+ "TImpl must be a non-interface type.");
*outPtr = refPtr.Ptr();
refPtr->addReference();
}
-template <typename TDest, typename TImpl>
+template<typename TDest, typename TImpl>
void returnRefPtrMove(TDest** outPtr, Slang::RefPtr<TImpl>& refPtr)
{
static_assert(
- std::is_base_of<Slang::RefObject, TDest>::value, "TDest must be a non-interface type.");
+ std::is_base_of<Slang::RefObject, TDest>::value,
+ "TDest must be a non-interface type.");
static_assert(
- std::is_base_of<Slang::RefObject, TImpl>::value, "TImpl must be a non-interface type.");
+ std::is_base_of<Slang::RefObject, TImpl>::value,
+ "TImpl must be a non-interface type.");
*outPtr = refPtr.detach();
}
@@ -199,6 +207,7 @@ class FenceBase : public IFence, public Slang::ComObject
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
IFence* getInterface(const Slang::Guid& guid);
+
protected:
InteropHandle sharedHandle = {};
};
@@ -209,13 +218,18 @@ public:
/// Get the type
SLANG_FORCE_INLINE IResource::Type getType() const { return m_type; }
/// True if it's a texture derived type
- SLANG_FORCE_INLINE bool isTexture() const { return int(m_type) >= int(IResource::Type::Texture1D); }
+ SLANG_FORCE_INLINE bool isTexture() const
+ {
+ return int(m_type) >= int(IResource::Type::Texture1D);
+ }
/// True if it's a buffer derived type
SLANG_FORCE_INLINE bool isBuffer() const { return m_type == IResource::Type::Buffer; }
+
protected:
Resource(IResource::Type type)
: m_type(type)
- {}
+ {
+ }
IResource::Type m_type;
InteropHandle sharedHandle = {};
@@ -233,14 +247,16 @@ public:
/// Ctor
BufferResource(const Desc& desc)
- : Parent(Type::Buffer)
- , m_desc(desc)
- {}
+ : Parent(Type::Buffer), m_desc(desc)
+ {
+ }
virtual SLANG_NO_THROW IResource::Type SLANG_MCALL getType() SLANG_OVERRIDE;
virtual SLANG_NO_THROW IBufferResource::Desc* SLANG_MCALL getDesc() SLANG_OVERRIDE;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle) SLANG_OVERRIDE;
- virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle)
+ SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle)
+ SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL setDebugName(const char* name) override
{
@@ -267,14 +283,16 @@ public:
/// Ctor
TextureResource(const Desc& desc)
- : Parent(desc.type)
- , m_desc(desc)
- {}
+ : Parent(desc.type), m_desc(desc)
+ {
+ }
virtual SLANG_NO_THROW IResource::Type SLANG_MCALL getType() SLANG_OVERRIDE;
virtual SLANG_NO_THROW ITextureResource::Desc* SLANG_MCALL getDesc() SLANG_OVERRIDE;
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle) SLANG_OVERRIDE;
- virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW Result SLANG_MCALL getNativeResourceHandle(InteropHandle* outHandle)
+ SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle)
+ SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL setDebugName(const char* name) override
{
@@ -291,11 +309,10 @@ protected:
};
class ResourceViewInternalBase : public Slang::ComObject
-{};
+{
+};
-class ResourceViewBase
- : public IResourceView
- , public ResourceViewInternalBase
+class ResourceViewBase : public IResourceView, public ResourceViewInternalBase
{
public:
Desc m_desc = {};
@@ -313,9 +330,7 @@ public:
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outHandle) override;
};
-class AccelerationStructureBase
- : public IAccelerationStructure
- , public ResourceViewInternalBase
+class AccelerationStructureBase : public IAccelerationStructure, public ResourceViewInternalBase
{
public:
IResourceView::Desc m_desc = {};
@@ -343,7 +358,8 @@ struct ExtendedShaderObjectTypeList
void add(const ExtendedShaderObjectType& component)
{
componentIDs.add(component.componentID);
- components.add(slang::SpecializationArg{ slang::SpecializationArg::Kind::Type, {component.slangType} });
+ components.add(
+ slang::SpecializationArg{slang::SpecializationArg::Kind::Type, {component.slangType}});
}
void addRange(const ExtendedShaderObjectTypeList& list)
{
@@ -364,16 +380,13 @@ struct ExtendedShaderObjectTypeList
componentIDs.clear();
components.clear();
}
- Slang::Index getCount() const
- {
- return componentIDs.getCount();
- }
+ Slang::Index getCount() const { return componentIDs.getCount(); }
};
-struct ExtendedShaderObjectTypeListObject
- : public ExtendedShaderObjectTypeList
- , public Slang::RefObject
-{};
+struct ExtendedShaderObjectTypeListObject : public ExtendedShaderObjectTypeList,
+ public Slang::RefObject
+{
+};
class ShaderObjectLayoutBase : public Slang::RefObject
{
@@ -426,8 +439,7 @@ public:
case slang::TypeReflection::Kind::ParameterBlock:
typeLayout = typeLayout->getElementTypeLayout();
continue;
- default:
- return typeLayout;
+ default: return typeLayout;
}
}
}
@@ -436,17 +448,14 @@ public:
public:
RendererBase* getDevice() { return m_renderer; }
- slang::TypeLayoutReflection* getElementTypeLayout()
- {
- return m_elementTypeLayout;
- }
+ slang::TypeLayoutReflection* getElementTypeLayout() { return m_elementTypeLayout; }
- ShaderComponentID getComponentID()
- {
- return m_componentID;
- }
+ ShaderComponentID getComponentID() { return m_componentID; }
- void initBase(RendererBase* renderer, slang::ISession* session, slang::TypeLayoutReflection* elementTypeLayout);
+ void initBase(
+ RendererBase* renderer,
+ slang::ISession* session,
+ slang::TypeLayoutReflection* elementTypeLayout);
};
class SimpleShaderObjectData
@@ -473,8 +482,8 @@ public:
};
bool _doesValueFitInExistentialPayload(
- slang::TypeLayoutReflection* concreteTypeLayout,
- slang::TypeLayoutReflection* existentialFieldLayout);
+ slang::TypeLayoutReflection* concreteTypeLayout,
+ slang::TypeLayoutReflection* existentialFieldLayout);
class ShaderObjectBase : public IShaderObject, public Slang::ComObject
{
@@ -483,9 +492,10 @@ public:
IShaderObject* getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IShaderObject)
- return static_cast<IShaderObject *>(this);
+ return static_cast<IShaderObject*>(this);
return nullptr;
}
+
protected:
// A strong reference to `IDevice` to make sure the weak device reference in
// `ShaderObjectLayout`s are valid whenever they might be used.
@@ -495,23 +505,23 @@ protected:
Slang::RefPtr<ShaderObjectLayoutBase> m_layout = nullptr;
// The specialized shader object type.
- ExtendedShaderObjectType shaderObjectType = { nullptr, kInvalidComponentID };
+ ExtendedShaderObjectType shaderObjectType = {nullptr, kInvalidComponentID};
Result _getSpecializedShaderObjectType(ExtendedShaderObjectType* outType);
slang::TypeLayoutReflection* _getElementTypeLayout()
{
return m_layout->getElementTypeLayout();
}
+
public:
void breakStrongReferenceToDevice() { m_device.breakStrongReference(); }
+
public:
- ShaderComponentID getComponentID()
- {
- return shaderObjectType.componentID;
- }
+ ShaderComponentID getComponentID() { return shaderObjectType.componentID; }
- // Get the final type this shader object represents. If the shader object's type has existential fields,
- // this function will return a specialized type using the bound sub-objects' type as specialization argument.
+ // Get the final type this shader object represents. If the shader object's type has existential
+ // fields, this function will return a specialized type using the bound sub-objects' type as
+ // specialization argument.
virtual Result getSpecializedShaderObjectType(ExtendedShaderObjectType* outType);
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) = 0;
@@ -546,22 +556,20 @@ public:
return m_layout->getContainerType();
}
- virtual SLANG_NO_THROW Result SLANG_MCALL getCurrentVersion(
- ITransientResourceHeap* transientHeap, IShaderObject** outObject) override
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ getCurrentVersion(ITransientResourceHeap* transientHeap, IShaderObject** outObject) override
{
returnComPtr(outObject, this);
return SLANG_OK;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- copyFrom(IShaderObject* object, ITransientResourceHeap* transientHeap);
+ copyFrom(IShaderObject* object, ITransientResourceHeap* transientHeap);
- virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override
- {
- return nullptr;
- }
+ virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override { return nullptr; }
- virtual SLANG_NO_THROW Result SLANG_MCALL setConstantBufferOverride(IBufferResource* outBuffer) override
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ setConstantBufferOverride(IBufferResource* outBuffer) override
{
return SLANG_E_NOT_AVAILABLE;
}
@@ -588,7 +596,7 @@ public:
size_t getBufferSize() { return (size_t)m_data.getCount(); } // TODO: Change size_t to Count?
virtual SLANG_NO_THROW Result SLANG_MCALL
- getObject(ShaderOffset const& offset, IShaderObject** outObject) SLANG_OVERRIDE
+ getObject(ShaderOffset const& offset, IShaderObject** outObject) SLANG_OVERRIDE
{
SLANG_ASSERT(outObject);
if (offset.bindingRangeIndex < 0)
@@ -612,7 +620,7 @@ public:
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- setObject(ShaderOffset const& offset, IShaderObject* object) SLANG_OVERRIDE
+ setObject(ShaderOffset const& offset, IShaderObject* object) SLANG_OVERRIDE
{
auto layout = getLayout();
auto subObject = static_cast<TShaderObjectImpl*>(object);
@@ -741,7 +749,9 @@ public:
// its bytes into that area.
//
setData(
- payloadOffset, subObject->m_data.getBuffer(), subObject->m_data.getCount());
+ payloadOffset,
+ subObject->m_data.getBuffer(),
+ subObject->m_data.getCount());
}
else
{
@@ -816,7 +826,9 @@ public:
m_userProvidedSpecializationArgs[objectIndex]->clear();
}
SLANG_RETURN_ON_FAIL(getExtendedShaderTypeListFromSpecializationArgs(
- *m_userProvidedSpecializationArgs[objectIndex], args, count));
+ *m_userProvidedSpecializationArgs[objectIndex],
+ args,
+ count));
return SLANG_OK;
}
@@ -863,47 +875,40 @@ public:
Slang::Result compileShaders(RendererBase* device);
virtual Slang::Result createShaderModule(
- slang::EntryPointReflection* entryPointInfo, Slang::ComPtr<ISlangBlob> kernelCode);
+ slang::EntryPointReflection* entryPointInfo,
+ Slang::ComPtr<ISlangBlob> kernelCode);
- virtual SLANG_NO_THROW slang::TypeReflection* SLANG_MCALL findTypeByName(const char* name) override
+ virtual SLANG_NO_THROW slang::TypeReflection* SLANG_MCALL
+ findTypeByName(const char* name) override
{
return linkedProgram->getLayout()->findTypeByName(name);
}
bool isMeshShaderProgram() const;
-
};
-class InputLayoutBase
- : public IInputLayout
- , public Slang::ComObject
+class InputLayoutBase : public IInputLayout, public Slang::ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
IInputLayout* getInterface(const Slang::Guid& guid);
};
-class FramebufferLayoutBase
- : public IFramebufferLayout
- , public Slang::ComObject
+class FramebufferLayoutBase : public IFramebufferLayout, public Slang::ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
IFramebufferLayout* getInterface(const Slang::Guid& guid);
};
-class FramebufferBase
- : public IFramebuffer
- , public Slang::ComObject
+class FramebufferBase : public IFramebuffer, public Slang::ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
IFramebuffer* getInterface(const Slang::Guid& guid);
};
-class QueryPoolBase
- : public IQueryPool
- , public Slang::ComObject
+class QueryPoolBase : public IQueryPool, public Slang::ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -988,9 +993,7 @@ struct OwnedRayTracingPipelineStateDesc
}
};
-class PipelineStateBase
- : public IPipelineState
- , public Slang::ComObject
+class PipelineStateBase : public IPipelineState, public Slang::ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -1006,10 +1009,8 @@ public:
{
switch (type)
{
- case PipelineType::Compute:
- return static_cast<ShaderProgramBase*>(compute.program);
- case PipelineType::Graphics:
- return static_cast<ShaderProgramBase*>(graphics.program);
+ case PipelineType::Compute: return static_cast<ShaderProgramBase*>(compute.program);
+ case PipelineType::Graphics: return static_cast<ShaderProgramBase*>(graphics.program);
case PipelineType::RayTracing:
return static_cast<ShaderProgramBase*>(rayTracing.program);
}
@@ -1030,7 +1031,8 @@ public:
// pipeline cannot be used directly and must be specialized first.
bool isSpecializable = false;
Slang::RefPtr<ShaderProgramBase> m_program;
- template <typename TProgram> TProgram* getProgram()
+ template<typename TProgram>
+ TProgram* getProgram()
{
return static_cast<TProgram*>(m_program.Ptr());
}
@@ -1047,10 +1049,7 @@ struct ComponentKey
Slang::UnownedStringSlice typeName;
Slang::ShortList<ShaderComponentID> specializationArgs;
Slang::HashCode hash;
- Slang::HashCode getHashCode() const
- {
- return hash;
- }
+ Slang::HashCode getHashCode() const { return hash; }
void updateHash()
{
hash = typeName.getHashCode();
@@ -1064,10 +1063,7 @@ struct PipelineKey
PipelineStateBase* pipeline;
Slang::ShortList<ShaderComponentID> specializationArgs;
Slang::HashCode hash;
- Slang::HashCode getHashCode() const
- {
- return hash;
- }
+ Slang::HashCode getHashCode() const { return hash; }
void updateHash()
{
hash = Slang::getHashCode(pipeline);
@@ -1094,10 +1090,7 @@ struct OwningComponentKey
Slang::String typeName;
Slang::ShortList<ShaderComponentID> specializationArgs;
Slang::HashCode hash;
- Slang::HashCode getHashCode() const
- {
- return hash;
- }
+ Slang::HashCode getHashCode() const { return hash; }
template<typename KeyType>
bool operator==(const KeyType& other) const
{
@@ -1153,11 +1146,9 @@ public:
static uint64_t version = 1;
return version;
}
- TransientResourceHeapBase()
- {
- m_version = getVersionCounter()++;
- }
+ TransientResourceHeapBase() { m_version = getVersionCounter()++; }
virtual ~TransientResourceHeapBase() {}
+
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
ITransientResourceHeap* getInterface(const Slang::Guid& guid)
@@ -1172,9 +1163,7 @@ public:
static const int kRayGenRecordSize = 64; // D3D12_RAYTRACING_SHADER_TABLE_BYTE_ALIGNMENT;
-class ShaderTableBase
- : public IShaderTable
- , public Slang::ComObject
+class ShaderTableBase : public IShaderTable, public Slang::ComObject
{
public:
Slang::List<Slang::String> m_shaderGroupNames;
@@ -1222,19 +1211,24 @@ public:
class RendererBase : public IDevice, public IShaderCache, public Slang::ComObject
{
friend class ShaderObjectBase;
+
public:
SLANG_COM_OBJECT_IUNKNOWN_ADD_REF
SLANG_COM_OBJECT_IUNKNOWN_RELEASE
- virtual SLANG_NO_THROW Result SLANG_MCALL getNativeDeviceHandles(InteropHandles* outHandles) SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW Result SLANG_MCALL getNativeDeviceHandles(InteropHandles* outHandles)
+ SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL getFeatures(
- const char** outFeatures, Size bufferSize, GfxCount* outFeatureCount) SLANG_OVERRIDE;
+ const char** outFeatures,
+ Size bufferSize,
+ GfxCount* outFeatureCount) SLANG_OVERRIDE;
virtual SLANG_NO_THROW bool SLANG_MCALL hasFeature(const char* featureName) SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL getSlangSession(slang::ISession** outSlangSession) SLANG_OVERRIDE;
+ getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL getSlangSession(slang::ISession** outSlangSession)
+ SLANG_OVERRIDE;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL
- queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE;
+ queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE;
IDevice* getInterface(const Slang::Guid& guid);
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureFromNativeHandle(
@@ -1286,10 +1280,12 @@ public:
IShaderObject** outObject) SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL createShaderObjectFromTypeLayout(
- slang::TypeLayoutReflection* typeLayout, IShaderObject** outObject) override;
+ slang::TypeLayoutReflection* typeLayout,
+ IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createMutableShaderObjectFromTypeLayout(
- slang::TypeLayoutReflection* typeLayout, IShaderObject** outObject) override;
+ slang::TypeLayoutReflection* typeLayout,
+ IShaderObject** outObject) override;
// Provides a default implementation that returns SLANG_E_NOT_AVAILABLE for platforms
// without ray tracing support.
@@ -1306,28 +1302,35 @@ public:
// Provides a default implementation that returns SLANG_E_NOT_AVAILABLE for platforms
// without ray tracing support.
virtual SLANG_NO_THROW Result SLANG_MCALL
- createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outTable) override;
+ createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outTable) override;
// Provides a default implementation that returns SLANG_E_NOT_AVAILABLE for platforms
// without ray tracing support.
virtual SLANG_NO_THROW Result SLANG_MCALL createRayTracingPipelineState(
- const RayTracingPipelineStateDesc& desc, IPipelineState** outState) override;
+ const RayTracingPipelineStateDesc& desc,
+ IPipelineState** outState) override;
// Provides a default implementation that returns SLANG_E_NOT_AVAILABLE.
virtual SLANG_NO_THROW Result SLANG_MCALL
- createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
+ createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
// Provides a default implementation that returns SLANG_E_NOT_AVAILABLE.
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFence(const IFence::Desc& desc, IFence** outFence) override;
+ createFence(const IFence::Desc& desc, IFence** outFence) override;
// Provides a default implementation that returns SLANG_E_NOT_AVAILABLE.
- virtual SLANG_NO_THROW Result SLANG_MCALL
- waitForFences(GfxCount fenceCount, IFence** fences, uint64_t* fenceValues, bool waitForAll, uint64_t timeout) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL waitForFences(
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* fenceValues,
+ bool waitForAll,
+ uint64_t timeout) override;
// Provides a default implementation that returns SLANG_E_NOT_AVAILABLE.
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureAllocationInfo(
- const ITextureResource::Desc& desc, Size* outSize, Size* outAlignment) override;
+ const ITextureResource::Desc& desc,
+ Size* outSize,
+ Size* outAlignment) override;
// Provides a default implementation that returns SLANG_E_NOT_AVAILABLE.
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureRowAlignment(size_t* outAlignment) override;
@@ -1340,10 +1343,10 @@ public:
slang::IBlob** outDiagnostics = nullptr);
Result getShaderObjectLayout(
- slang::ISession* session,
- slang::TypeReflection* type,
- ShaderObjectContainerType container,
- ShaderObjectLayoutBase** outLayout);
+ slang::ISession* session,
+ slang::TypeReflection* type,
+ ShaderObjectContainerType container,
+ ShaderObjectLayoutBase** outLayout);
Result getShaderObjectLayout(
slang::ISession* session,
@@ -1352,9 +1355,9 @@ public:
public:
ExtendedShaderObjectTypeList specializationArgs;
- // Given current pipeline and root shader object binding, generate and bind a specialized pipeline if necessary.
- // The newly specialized pipeline is held alive by the pipeline cache so users of `outNewPipeline` do not
- // need to maintain its lifespan.
+ // Given current pipeline and root shader object binding, generate and bind a specialized
+ // pipeline if necessary. The newly specialized pipeline is held alive by the pipeline cache so
+ // users of `outNewPipeline` do not need to maintain its lifespan.
Result maybeSpecializePipeline(
PipelineStateBase* currentPipeline,
ShaderObjectBase* rootObject,
@@ -1368,29 +1371,33 @@ public:
virtual Result createShaderObject(
ShaderObjectLayoutBase* layout,
- IShaderObject** outObject) = 0;
+ IShaderObject** outObject) = 0;
virtual Result createMutableShaderObject(
ShaderObjectLayoutBase* layout,
IShaderObject** outObject) = 0;
- public:
+public:
// IShaderCache interface
virtual SLANG_NO_THROW Result SLANG_MCALL clearShaderCache() SLANG_OVERRIDE;
- virtual SLANG_NO_THROW Result SLANG_MCALL getShaderCacheStats(ShaderCacheStats* outStats) SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW Result SLANG_MCALL getShaderCacheStats(ShaderCacheStats* outStats)
+ SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL resetShaderCacheStats() SLANG_OVERRIDE;
protected:
virtual SLANG_NO_THROW SlangResult SLANG_MCALL initialize(const Desc& desc);
+
protected:
Slang::List<Slang::String> m_features;
+
public:
SlangContext slangContext;
ShaderCache shaderCache;
Slang::RefPtr<Slang::PersistentCache> persistentShaderCache;
- Slang::Dictionary<slang::TypeLayoutReflection*, Slang::RefPtr<ShaderObjectLayoutBase>> m_shaderObjectLayoutCache;
+ Slang::Dictionary<slang::TypeLayoutReflection*, Slang::RefPtr<ShaderObjectLayoutBase>>
+ m_shaderObjectLayoutCache;
Slang::ComPtr<IPipelineCreationAPIDispatcher> m_pipelineCreationAPIDispatcher;
};
@@ -1416,7 +1423,8 @@ inline IDebugCallback* getDebugCallback()
//--------------------------------------------------------------------------------
template<typename TShaderObjectImpl, typename TShaderObjectLayoutImpl, typename TShaderObjectData>
-void ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderObjectData>::setSpecializationArgsForContainerElement(ExtendedShaderObjectTypeList& specializationArgs)
+void ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderObjectData>::
+ setSpecializationArgsForContainerElement(ExtendedShaderObjectTypeList& specializationArgs)
{
// Compute specialization args for the structured buffer object.
// If we haven't filled anything to `m_structuredBufferSpecializationArgs` yet,
@@ -1451,10 +1459,11 @@ void ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderObj
//--------------------------------------------------------------------------------
template<typename TShaderObjectImpl, typename TShaderObjectLayoutImpl, typename TShaderObjectData>
-Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderObjectData>::getExtendedShaderTypeListFromSpecializationArgs(
- ExtendedShaderObjectTypeList& list,
- const slang::SpecializationArg* args,
- uint32_t count)
+Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderObjectData>::
+ getExtendedShaderTypeListFromSpecializationArgs(
+ ExtendedShaderObjectTypeList& list,
+ const slang::SpecializationArg* args,
+ uint32_t count)
{
auto device = getRenderer();
for (uint32_t i = 0; i < count; i++)
@@ -1462,13 +1471,13 @@ Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderO
gfx::ExtendedShaderObjectType extendedType;
switch (args[i].kind)
{
- case slang::SpecializationArg::Kind::Type:
- extendedType.slangType = args[i].type;
- extendedType.componentID = device->shaderCache.getComponentId(args[i].type);
- break;
- default:
- SLANG_ASSERT(false && "Unexpected specialization argument kind.");
- return SLANG_FAIL;
+ case slang::SpecializationArg::Kind::Type:
+ extendedType.slangType = args[i].type;
+ extendedType.componentID = device->shaderCache.getComponentId(args[i].type);
+ break;
+ default:
+ SLANG_ASSERT(false && "Unexpected specialization argument kind.");
+ return SLANG_FAIL;
}
list.add(extendedType);
}
@@ -1477,7 +1486,8 @@ Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderO
//--------------------------------------------------------------------------------
template<typename TShaderObjectImpl, typename TShaderObjectLayoutImpl, typename TShaderObjectData>
-Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderObjectData>::collectSpecializationArgs(ExtendedShaderObjectTypeList& args)
+Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderObjectData>::
+ collectSpecializationArgs(ExtendedShaderObjectTypeList& args)
{
if (m_layout->getContainerType() != ShaderObjectContainerType::None)
{
@@ -1494,18 +1504,17 @@ Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderO
Slang::Index subObjectRangeCount = subObjectRanges.getCount();
for (Slang::Index subObjectRangeIndex = 0; subObjectRangeIndex < subObjectRangeCount;
- subObjectRangeIndex++)
+ subObjectRangeIndex++)
{
auto const& subObjectRange = subObjectRanges[subObjectRangeIndex];
- auto const& bindingRange =
- getLayout()->getBindingRange(subObjectRange.bindingRangeIndex);
+ auto const& bindingRange = getLayout()->getBindingRange(subObjectRange.bindingRangeIndex);
Slang::Index oldArgsCount = args.getCount();
Slang::Index count = bindingRange.count;
for (Slang::Index subObjectIndexInRange = 0; subObjectIndexInRange < count;
- subObjectIndexInRange++)
+ subObjectIndexInRange++)
{
ExtendedShaderObjectTypeList typeArgs;
Slang::Index objectIndex = bindingRange.subObjectIndex + subObjectIndexInRange;
@@ -1523,7 +1532,7 @@ Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderO
switch (bindingRange.bindingType)
{
- case slang::BindingType::ExistentialValue:
+ case slang::BindingType::ExistentialValue:
{
// A binding type of `ExistentialValue` means the sub-object represents a
// interface-typed field. In this case the specialization argument for this
@@ -1539,25 +1548,26 @@ Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderO
typeArgs.add(specializedSubObjType);
break;
}
- case slang::BindingType::ParameterBlock:
- case slang::BindingType::ConstantBuffer:
- case slang::BindingType::RawBuffer:
- case slang::BindingType::MutableRawBuffer:
- // If the field's type is `ParameterBlock<IFoo>`, we want to pull in the type argument
- // from the sub object for specialization.
- if (bindingRange.isSpecializable)
- {
- ExtendedShaderObjectType specializedSubObjType;
- SLANG_RETURN_ON_FAIL(
- subObject->getSpecializedShaderObjectType(&specializedSubObjType));
- typeArgs.add(specializedSubObjType);
- }
+ case slang::BindingType::ParameterBlock:
+ case slang::BindingType::ConstantBuffer:
+ case slang::BindingType::RawBuffer:
+ case slang::BindingType::MutableRawBuffer:
+ // If the field's type is `ParameterBlock<IFoo>`, we want to pull in the type
+ // argument from the sub object for specialization.
+ if (bindingRange.isSpecializable)
+ {
+ ExtendedShaderObjectType specializedSubObjType;
+ SLANG_RETURN_ON_FAIL(
+ subObject->getSpecializedShaderObjectType(&specializedSubObjType));
+ typeArgs.add(specializedSubObjType);
+ }
- // If field's type is `ParameterBlock<SomeStruct>` or `ConstantBuffer<SomeStruct>`, where
- // `SomeStruct` is a struct type (not directly an interface type), we need to recursively
- // collect the specialization arguments from the bound sub object.
- SLANG_RETURN_ON_FAIL(subObject->collectSpecializationArgs(typeArgs));
- break;
+ // If field's type is `ParameterBlock<SomeStruct>` or
+ // `ConstantBuffer<SomeStruct>`, where `SomeStruct` is a struct type (not
+ // directly an interface type), we need to recursively collect the
+ // specialization arguments from the bound sub object.
+ SLANG_RETURN_ON_FAIL(subObject->collectSpecializationArgs(typeArgs));
+ break;
}
auto addedTypeArgCountForCurrentRange = args.getCount() - oldArgsCount;
@@ -1586,4 +1596,4 @@ Result ShaderObjectBaseImpl<TShaderObjectImpl, TShaderObjectLayoutImpl, TShaderO
}
return SLANG_OK;
}
-}
+} // namespace gfx
diff --git a/tools/gfx/resource-desc-utils.cpp b/tools/gfx/resource-desc-utils.cpp
index b36e765e5..ab20c78a8 100644
--- a/tools/gfx/resource-desc-utils.cpp
+++ b/tools/gfx/resource-desc-utils.cpp
@@ -22,22 +22,14 @@ Format srgbToLinearFormat(Format format)
{
switch (format)
{
- case Format::BC1_UNORM_SRGB:
- return Format::BC1_UNORM;
- case Format::BC2_UNORM_SRGB:
- return Format::BC2_UNORM;
- case Format::BC3_UNORM_SRGB:
- return Format::BC3_UNORM;
- case Format::BC7_UNORM_SRGB:
- return Format::BC7_UNORM;
- case Format::B8G8R8A8_UNORM_SRGB:
- return Format::B8G8R8A8_UNORM;
- case Format::B8G8R8X8_UNORM_SRGB:
- return Format::B8G8R8X8_UNORM;
- case Format::R8G8B8A8_UNORM_SRGB:
- return Format::R8G8B8A8_UNORM;
- default:
- return format;
+ case Format::BC1_UNORM_SRGB: return Format::BC1_UNORM;
+ case Format::BC2_UNORM_SRGB: return Format::BC2_UNORM;
+ case Format::BC3_UNORM_SRGB: return Format::BC3_UNORM;
+ case Format::BC7_UNORM_SRGB: return Format::BC7_UNORM;
+ case Format::B8G8R8A8_UNORM_SRGB: return Format::B8G8R8A8_UNORM;
+ case Format::B8G8R8X8_UNORM_SRGB: return Format::B8G8R8X8_UNORM;
+ case Format::R8G8B8A8_UNORM_SRGB: return Format::R8G8B8A8_UNORM;
+ default: return format;
}
}
-}
+} // namespace gfx
diff --git a/tools/gfx/resource-desc-utils.h b/tools/gfx/resource-desc-utils.h
index 25dcc43b6..cdfeb4c25 100644
--- a/tools/gfx/resource-desc-utils.h
+++ b/tools/gfx/resource-desc-utils.h
@@ -1,7 +1,7 @@
#pragma once
-#include "slang-gfx.h"
#include "core/slang-math.h"
+#include "slang-gfx.h"
namespace gfx
{
@@ -35,12 +35,9 @@ inline int calcEffectiveArraySize(const ITextureResource::Desc& desc)
{
return arrSize;
}
- case IResource::Type::TextureCube:
- return arrSize * 6;
- case IResource::Type::Texture3D:
- return 1;
- default:
- return 0;
+ case IResource::Type::TextureCube: return arrSize * 6;
+ case IResource::Type::Texture3D: return 1;
+ default: return 0;
}
}
@@ -49,8 +46,7 @@ inline int calcMaxDimension(ITextureResource::Extents size, IResource::Type type
{
switch (type)
{
- case IResource::Type::Texture1D:
- return size.width;
+ case IResource::Type::Texture1D: return size.width;
case IResource::Type::Texture3D:
return Slang::Math::Max(Slang::Math::Max(size.width, size.height), size.depth);
case IResource::Type::TextureCube: // fallthru
@@ -58,8 +54,7 @@ inline int calcMaxDimension(ITextureResource::Extents size, IResource::Type type
{
return Slang::Math::Max(size.width, size.height);
}
- default:
- return 0;
+ default: return 0;
}
}
@@ -89,8 +84,7 @@ inline int calcNumSubResources(const ITextureResource::Desc& desc)
// There are 6 faces to a cubemap
return numMipMaps * arrSize * 6;
}
- default:
- return 0;
+ default: return 0;
}
}
@@ -99,4 +93,4 @@ ITextureResource::Desc fixupTextureDesc(const ITextureResource::Desc& desc);
Format srgbToLinearFormat(Format format);
-}
+} // namespace gfx
diff --git a/tools/gfx/simple-render-pass-layout.h b/tools/gfx/simple-render-pass-layout.h
index ae3ef1166..8ac41de0c 100644
--- a/tools/gfx/simple-render-pass-layout.h
+++ b/tools/gfx/simple-render-pass-layout.h
@@ -5,16 +5,14 @@
// desc value. Used by targets that does not expose an API object for the render pass
// concept.
-#include "slang-gfx.h"
-#include "core/slang-com-object.h"
#include "core/slang-basic.h"
+#include "core/slang-com-object.h"
+#include "slang-gfx.h"
namespace gfx
{
-class SimpleRenderPassLayout
- : public IRenderPassLayout
- , public Slang::ComObject
+class SimpleRenderPassLayout : public IRenderPassLayout, public Slang::ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -27,4 +25,4 @@ public:
void init(const IRenderPassLayout::Desc& desc);
};
-}
+} // namespace gfx
diff --git a/tools/gfx/simple-transient-resource-heap.h b/tools/gfx/simple-transient-resource-heap.h
index 4e3a04094..1a7261481 100644
--- a/tools/gfx/simple-transient-resource-heap.h
+++ b/tools/gfx/simple-transient-resource-heap.h
@@ -22,7 +22,8 @@ public:
m_device = device;
IBufferResource::Desc bufferDesc = {};
bufferDesc.type = IResource::Type::Buffer;
- bufferDesc.allowedStates = ResourceStateSet(ResourceState::ConstantBuffer, ResourceState::CopyDestination);
+ bufferDesc.allowedStates =
+ ResourceStateSet(ResourceState::ConstantBuffer, ResourceState::CopyDestination);
bufferDesc.defaultState = ResourceState::ConstantBuffer;
bufferDesc.sizeInBytes = desc.constantBufferSize;
bufferDesc.memoryType = MemoryType::Upload;
@@ -31,7 +32,7 @@ public:
return SLANG_OK;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandBuffer(ICommandBuffer** outCommandBuffer) override
+ createCommandBuffer(ICommandBuffer** outCommandBuffer) override
{
Slang::RefPtr<TCommandBuffer> newCmdBuffer = new TCommandBuffer();
newCmdBuffer->init(m_device, this);
@@ -45,4 +46,4 @@ public:
return SLANG_OK;
}
};
-}
+} // namespace gfx
diff --git a/tools/gfx/slang-context.h b/tools/gfx/slang-context.h
index 79f39c3e6..719c70b50 100644
--- a/tools/gfx/slang-context.h
+++ b/tools/gfx/slang-context.h
@@ -1,67 +1,69 @@
#pragma once
-#include "slang-gfx.h"
#include "core/slang-basic.h"
+#include "slang-gfx.h"
namespace gfx
{
- class SlangContext
+class SlangContext
+{
+public:
+ Slang::ComPtr<slang::IGlobalSession> globalSession;
+ Slang::ComPtr<slang::ISession> session;
+ Result initialize(
+ const gfx::IDevice::SlangDesc& desc,
+ uint32_t extendedDescCount,
+ void** extendedDescs,
+ SlangCompileTarget compileTarget,
+ const char* defaultProfileName,
+ Slang::ConstArrayView<slang::PreprocessorMacroDesc> additionalMacros)
{
- public:
- Slang::ComPtr<slang::IGlobalSession> globalSession;
- Slang::ComPtr<slang::ISession> session;
- Result initialize(const gfx::IDevice::SlangDesc& desc,
- uint32_t extendedDescCount,
- void** extendedDescs,
- SlangCompileTarget compileTarget,
- const char* defaultProfileName,
- Slang::ConstArrayView<slang::PreprocessorMacroDesc> additionalMacros)
+ if (desc.slangGlobalSession)
{
- if (desc.slangGlobalSession)
- {
- globalSession = desc.slangGlobalSession;
- }
- else
- {
- SLANG_RETURN_ON_FAIL(slang::createGlobalSession(globalSession.writeRef()));
- }
+ globalSession = desc.slangGlobalSession;
+ }
+ else
+ {
+ SLANG_RETURN_ON_FAIL(slang::createGlobalSession(globalSession.writeRef()));
+ }
- slang::SessionDesc slangSessionDesc = {};
- slangSessionDesc.defaultMatrixLayoutMode = desc.defaultMatrixLayoutMode;
- slangSessionDesc.searchPathCount = desc.searchPathCount;
- slangSessionDesc.searchPaths = desc.searchPaths;
- slangSessionDesc.preprocessorMacroCount = desc.preprocessorMacroCount + additionalMacros.getCount();
- Slang::List<slang::PreprocessorMacroDesc> macros;
- macros.addRange(desc.preprocessorMacros, desc.preprocessorMacroCount);
- macros.addRange(additionalMacros.getBuffer(), additionalMacros.getCount());
- slangSessionDesc.preprocessorMacros = macros.getBuffer();
- slang::TargetDesc targetDesc = {};
- targetDesc.format = compileTarget;
- auto targetProfile = desc.targetProfile;
- if (targetProfile == nullptr)
- targetProfile = defaultProfileName;
- targetDesc.profile = globalSession->findProfile(targetProfile);
- targetDesc.floatingPointMode = desc.floatingPointMode;
- targetDesc.lineDirectiveMode = desc.lineDirectiveMode;
- targetDesc.flags = desc.targetFlags;
- targetDesc.forceGLSLScalarBufferLayout = true;
+ slang::SessionDesc slangSessionDesc = {};
+ slangSessionDesc.defaultMatrixLayoutMode = desc.defaultMatrixLayoutMode;
+ slangSessionDesc.searchPathCount = desc.searchPathCount;
+ slangSessionDesc.searchPaths = desc.searchPaths;
+ slangSessionDesc.preprocessorMacroCount =
+ desc.preprocessorMacroCount + additionalMacros.getCount();
+ Slang::List<slang::PreprocessorMacroDesc> macros;
+ macros.addRange(desc.preprocessorMacros, desc.preprocessorMacroCount);
+ macros.addRange(additionalMacros.getBuffer(), additionalMacros.getCount());
+ slangSessionDesc.preprocessorMacros = macros.getBuffer();
+ slang::TargetDesc targetDesc = {};
+ targetDesc.format = compileTarget;
+ auto targetProfile = desc.targetProfile;
+ if (targetProfile == nullptr)
+ targetProfile = defaultProfileName;
+ targetDesc.profile = globalSession->findProfile(targetProfile);
+ targetDesc.floatingPointMode = desc.floatingPointMode;
+ targetDesc.lineDirectiveMode = desc.lineDirectiveMode;
+ targetDesc.flags = desc.targetFlags;
+ targetDesc.forceGLSLScalarBufferLayout = true;
- slangSessionDesc.targets = &targetDesc;
- slangSessionDesc.targetCount = 1;
+ slangSessionDesc.targets = &targetDesc;
+ slangSessionDesc.targetCount = 1;
- for (uint32_t i = 0; i < extendedDescCount; i++)
+ for (uint32_t i = 0; i < extendedDescCount; i++)
+ {
+ if ((*(StructType*)extendedDescs[i]) == StructType::SlangSessionExtendedDesc)
{
- if ((*(StructType*)extendedDescs[i]) == StructType::SlangSessionExtendedDesc)
- {
- auto extDesc = (SlangSessionExtendedDesc*)extendedDescs[i];
- slangSessionDesc.compilerOptionEntryCount = extDesc->compilerOptionEntryCount;
- slangSessionDesc.compilerOptionEntries = extDesc->compilerOptionEntries;
- break;
- }
+ auto extDesc = (SlangSessionExtendedDesc*)extendedDescs[i];
+ slangSessionDesc.compilerOptionEntryCount = extDesc->compilerOptionEntryCount;
+ slangSessionDesc.compilerOptionEntries = extDesc->compilerOptionEntries;
+ break;
}
-
- SLANG_RETURN_ON_FAIL(globalSession->createSession(slangSessionDesc, session.writeRef()));
- return SLANG_OK;
}
- };
-}
+
+ SLANG_RETURN_ON_FAIL(globalSession->createSession(slangSessionDesc, session.writeRef()));
+ return SLANG_OK;
+ }
+};
+} // namespace gfx
diff --git a/tools/gfx/transient-resource-heap-base.h b/tools/gfx/transient-resource-heap-base.h
index 1b86b983c..9d7cb165a 100644
--- a/tools/gfx/transient-resource-heap-base.h
+++ b/tools/gfx/transient-resource-heap-base.h
@@ -32,7 +32,11 @@ public:
const size_t kStagingBufferDefaultPageSize = 16 * 1024 * 1024;
- void init(TDevice* device, MemoryType memoryType, uint32_t alignment, ResourceStateSet allowedStates)
+ void init(
+ TDevice* device,
+ MemoryType memoryType,
+ uint32_t alignment,
+ ResourceStateSet allowedStates)
{
m_device = device;
m_memoryType = memoryType;
@@ -129,7 +133,7 @@ public:
}
};
-template <typename TDevice, typename TBufferResource>
+template<typename TDevice, typename TBufferResource>
class TransientResourceHeapBaseImpl : public TransientResourceHeapBase
{
public:
@@ -158,11 +162,9 @@ public:
device,
MemoryType::Upload,
256,
- ResourceStateSet(
- ResourceState::CopySource,
- ResourceState::CopyDestination));
+ ResourceStateSet(ResourceState::CopySource, ResourceState::CopyDestination));
- m_readbackBufferPool.init(
+ m_readbackBufferPool.init(
device,
MemoryType::ReadBack,
256,
@@ -173,7 +175,12 @@ public:
return SLANG_OK;
}
- Result allocateStagingBuffer(size_t size, IBufferResource*& outBufferWeakPtr, size_t& offset, MemoryType memoryType, bool forceLargePage = false)
+ Result allocateStagingBuffer(
+ size_t size,
+ IBufferResource*& outBufferWeakPtr,
+ size_t& offset,
+ MemoryType memoryType,
+ bool forceLargePage = false)
{
switch (memoryType)
{
diff --git a/tools/gfx/vulkan/vk-api.cpp b/tools/gfx/vulkan/vk-api.cpp
index 8f5e4235b..3d2042a8d 100644
--- a/tools/gfx/vulkan/vk-api.cpp
+++ b/tools/gfx/vulkan/vk-api.cpp
@@ -3,22 +3,23 @@
#include "core/slang-list.h"
-namespace gfx {
+namespace gfx
+{
using namespace Slang;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! VulkanApi !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-#define VK_API_CHECK_FUNCTION(x) && (x != nullptr)
-#define VK_API_CHECK_FUNCTIONS(FUNCTION_LIST) true FUNCTION_LIST(VK_API_CHECK_FUNCTION)
+#define VK_API_CHECK_FUNCTION(x) &&(x != nullptr)
+#define VK_API_CHECK_FUNCTIONS(FUNCTION_LIST) true FUNCTION_LIST(VK_API_CHECK_FUNCTION)
bool VulkanApi::areDefined(ProcType type) const
{
switch (type)
{
- case ProcType::Global: return VK_API_CHECK_FUNCTIONS(VK_API_ALL_GLOBAL_PROCS);
- case ProcType::Instance: return VK_API_CHECK_FUNCTIONS(VK_API_ALL_INSTANCE_PROCS);
- case ProcType::Device: return VK_API_CHECK_FUNCTIONS(VK_API_DEVICE_PROCS);
- default:
+ case ProcType::Global: return VK_API_CHECK_FUNCTIONS(VK_API_ALL_GLOBAL_PROCS);
+ case ProcType::Instance: return VK_API_CHECK_FUNCTIONS(VK_API_ALL_INSTANCE_PROCS);
+ case ProcType::Device: return VK_API_CHECK_FUNCTIONS(VK_API_DEVICE_PROCS);
+ default:
{
assert(!"Unhandled type");
return false;
@@ -49,7 +50,7 @@ Slang::Result VulkanApi::initInstanceProcs(VkInstance instance)
VK_API_ALL_INSTANCE_PROCS(VK_API_GET_INSTANCE_PROC)
- // Get optional
+ // Get optional
VK_API_INSTANCE_PROCS_OPT(VK_API_GET_INSTANCE_PROC)
if (!areDefined(ProcType::Instance))
@@ -108,7 +109,7 @@ int VulkanApi::findMemoryTypeIndex(uint32_t typeBits, VkMemoryPropertyFlags prop
// bit holds current test bit against typeBits. Ie bit == 1 << typeBits
uint32_t bit = 1;
- for (int i = 0; i < numMemoryTypes; ++i, bit += bit)
+ for (int i = 0; i < numMemoryTypes; ++i, bit += bit)
{
auto const& memoryType = m_deviceMemoryProperties.memoryTypes[i];
if ((typeBits & bit) && (memoryType.propertyFlags & properties) == properties)
@@ -117,7 +118,7 @@ int VulkanApi::findMemoryTypeIndex(uint32_t typeBits, VkMemoryPropertyFlags prop
}
}
- //assert(!"failed to find a usable memory type");
+ // assert(!"failed to find a usable memory type");
return -1;
}
@@ -130,10 +131,13 @@ int VulkanApi::findQueue(VkQueueFlags reqFlags) const
Slang::List<VkQueueFamilyProperties> queueFamilies;
queueFamilies.setCount(numQueueFamilies);
- vkGetPhysicalDeviceQueueFamilyProperties(m_physicalDevice, &numQueueFamilies, queueFamilies.getBuffer());
+ vkGetPhysicalDeviceQueueFamilyProperties(
+ m_physicalDevice,
+ &numQueueFamilies,
+ queueFamilies.getBuffer());
// Find a queue that can service our needs
- //VkQueueFlags reqQueueFlags = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
+ // VkQueueFlags reqQueueFlags = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
int queueFamilyIndex = -1;
for (int i = 0; i < int(numQueueFamilies); ++i)
@@ -147,4 +151,4 @@ int VulkanApi::findQueue(VkQueueFlags reqFlags) const
return -1;
}
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-api.h b/tools/gfx/vulkan/vk-api.h
index 04744369a..8b86bc281 100644
--- a/tools/gfx/vulkan/vk-api.h
+++ b/tools/gfx/vulkan/vk-api.h
@@ -3,7 +3,8 @@
#include "vk-module.h"
-namespace gfx {
+namespace gfx
+{
// clang-format off
#define VK_API_GLOBAL_PROCS(x) \
@@ -242,86 +243,66 @@ struct VulkanExtendedFeatureProperties
{
// 16 bit storage features
VkPhysicalDevice16BitStorageFeatures storage16BitFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR};
// Atomic Float features
VkPhysicalDeviceShaderAtomicFloatFeaturesEXT atomicFloatFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT};
VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT atomicFloat2Features = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_2_FEATURES_EXT
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_2_FEATURES_EXT};
// Image int64 atomic features
VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT imageInt64AtomicFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT};
// Extended dynamic state features
VkPhysicalDeviceExtendedDynamicStateFeaturesEXT extendedDynamicStateFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT};
// Acceleration structure features
VkPhysicalDeviceAccelerationStructureFeaturesKHR accelerationStructureFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR};
// Ray tracing pipeline features
VkPhysicalDeviceRayTracingPipelineFeaturesKHR rayTracingPipelineFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR};
// Ray query (inline ray-tracing) features
VkPhysicalDeviceRayQueryFeaturesKHR rayQueryFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR};
// Inline uniform block features
VkPhysicalDeviceInlineUniformBlockFeaturesEXT inlineUniformBlockFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT};
// Robustness2 features
VkPhysicalDeviceRobustness2FeaturesEXT robustness2Features = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT};
VkPhysicalDeviceRayTracingInvocationReorderFeaturesNV rayTracingInvocationReorderFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_INVOCATION_REORDER_FEATURES_NV
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_INVOCATION_REORDER_FEATURES_NV};
VkPhysicalDeviceVariablePointerFeaturesKHR variablePointersFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR};
VkPhysicalDeviceComputeShaderDerivativesFeaturesNV computeShaderDerivativeFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV};
// Clock features
- VkPhysicalDeviceShaderClockFeaturesKHR clockFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR
- };
+ VkPhysicalDeviceShaderClockFeaturesKHR clockFeatures = {
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR};
// Mesh shader features
VkPhysicalDeviceMeshShaderFeaturesEXT meshShaderFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
// Multiview features
VkPhysicalDeviceMultiviewFeaturesKHR multiviewFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHR
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHR};
// Fragment shading rate features
VkPhysicalDeviceFragmentShadingRateFeaturesKHR fragmentShadingRateFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR};
// Vulkan 1.2 features.
VkPhysicalDeviceVulkan12Features vulkan12Features = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES
- };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
// Ray tracing validation features
VkPhysicalDeviceRayTracingValidationFeaturesNV rayTracingValidationFeatures = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_VALIDATION_FEATURES_NV
- };
-
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_VALIDATION_FEATURES_NV};
};
struct VulkanApi
@@ -335,38 +316,38 @@ struct VulkanApi
Device,
};
- /// Returns true if all the functions in the class are defined
+ /// Returns true if all the functions in the class are defined
bool areDefined(ProcType type) const;
- /// Sets up global parameters
+ /// Sets up global parameters
Slang::Result initGlobalProcs(const VulkanModule& module);
- /// Initialize the instance functions
+ /// Initialize the instance functions
Slang::Result initInstanceProcs(VkInstance instance);
- /// Called before initDevice
+ /// Called before initDevice
Slang::Result initPhysicalDevice(VkPhysicalDevice physicalDevice);
- /// Initialize the device functions
+ /// Initialize the device functions
Slang::Result initDeviceProcs(VkDevice device);
- /// Type bits control which indices are tested against bit 0 for testing at index 0
- /// properties - a memory type must have all the bits set as passed in
- /// Returns -1 if couldn't find an appropriate memory type index
+ /// Type bits control which indices are tested against bit 0 for testing at index 0
+ /// properties - a memory type must have all the bits set as passed in
+ /// Returns -1 if couldn't find an appropriate memory type index
int findMemoryTypeIndex(uint32_t typeBits, VkMemoryPropertyFlags properties) const;
- /// Given queue required flags, finds a queue
+ /// Given queue required flags, finds a queue
int findQueue(VkQueueFlags reqFlags) const;
- const VulkanModule* m_module = nullptr; ///< Module this was all loaded from
+ const VulkanModule* m_module = nullptr; ///< Module this was all loaded from
VkInstance m_instance = VK_NULL_HANDLE;
VkDevice m_device = VK_NULL_HANDLE;
VkPhysicalDevice m_physicalDevice = VK_NULL_HANDLE;
- VkPhysicalDeviceProperties m_deviceProperties;
- VkPhysicalDeviceRayTracingPipelinePropertiesKHR m_rtProperties;
- VkPhysicalDeviceFeatures m_deviceFeatures;
- VkPhysicalDeviceMemoryProperties m_deviceMemoryProperties;
- VulkanExtendedFeatureProperties m_extendedFeatures;
+ VkPhysicalDeviceProperties m_deviceProperties;
+ VkPhysicalDeviceRayTracingPipelinePropertiesKHR m_rtProperties;
+ VkPhysicalDeviceFeatures m_deviceFeatures;
+ VkPhysicalDeviceMemoryProperties m_deviceMemoryProperties;
+ VulkanExtendedFeatureProperties m_extendedFeatures;
};
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-base.h b/tools/gfx/vulkan/vk-base.h
index 3d765b42f..0e36c4454 100644
--- a/tools/gfx/vulkan/vk-base.h
+++ b/tools/gfx/vulkan/vk-base.h
@@ -16,41 +16,41 @@ namespace gfx
namespace vk
{
- class DeviceImpl;
- class InputLayoutImpl;
- class BufferResourceImpl;
- class FenceImpl;
- class TextureResourceImpl;
- class SamplerStateImpl;
- class ResourceViewImpl;
- class TextureResourceViewImpl;
- class TexelBufferResourceViewImpl;
- class PlainBufferResourceViewImpl;
- class AccelerationStructureImpl;
- class FramebufferLayoutImpl;
- class RenderPassLayoutImpl;
- class FramebufferImpl;
- class PipelineStateImpl;
- class RayTracingPipelineStateImpl;
- class ShaderObjectLayoutImpl;
- class EntryPointLayout;
- class RootShaderObjectLayout;
- class ShaderProgramImpl;
- class PipelineCommandEncoder;
- class ShaderObjectImpl;
- class MutableShaderObjectImpl;
- class RootShaderObjectImpl;
- class MutableRootShaderObjectImpl;
- class ShaderTableImpl;
- class ResourceCommandEncoder;
- class RenderCommandEncoder;
- class ComputeCommandEncoder;
- class RayTracingCommandEncoder;
- class CommandBufferImpl;
- class CommandQueueImpl;
- class TransientResourceHeapImpl;
- class QueryPoolImpl;
- class SwapchainImpl;
+class DeviceImpl;
+class InputLayoutImpl;
+class BufferResourceImpl;
+class FenceImpl;
+class TextureResourceImpl;
+class SamplerStateImpl;
+class ResourceViewImpl;
+class TextureResourceViewImpl;
+class TexelBufferResourceViewImpl;
+class PlainBufferResourceViewImpl;
+class AccelerationStructureImpl;
+class FramebufferLayoutImpl;
+class RenderPassLayoutImpl;
+class FramebufferImpl;
+class PipelineStateImpl;
+class RayTracingPipelineStateImpl;
+class ShaderObjectLayoutImpl;
+class EntryPointLayout;
+class RootShaderObjectLayout;
+class ShaderProgramImpl;
+class PipelineCommandEncoder;
+class ShaderObjectImpl;
+class MutableShaderObjectImpl;
+class RootShaderObjectImpl;
+class MutableRootShaderObjectImpl;
+class ShaderTableImpl;
+class ResourceCommandEncoder;
+class RenderCommandEncoder;
+class ComputeCommandEncoder;
+class RayTracingCommandEncoder;
+class CommandBufferImpl;
+class CommandQueueImpl;
+class TransientResourceHeapImpl;
+class QueryPoolImpl;
+class SwapchainImpl;
} // namespace vk
} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-buffer.cpp b/tools/gfx/vulkan/vk-buffer.cpp
index 721886d9f..76e64c32f 100644
--- a/tools/gfx/vulkan/vk-buffer.cpp
+++ b/tools/gfx/vulkan/vk-buffer.cpp
@@ -3,7 +3,7 @@
#include "vk-util.h"
#if SLANG_WINDOWS_FAMILY
-# include <dxgi1_2.h>
+#include <dxgi1_2.h>
#endif
namespace gfx
@@ -28,20 +28,21 @@ Result VKBufferHandleRAII::init(
m_memory = VK_NULL_HANDLE;
m_buffer = VK_NULL_HANDLE;
- VkBufferCreateInfo bufferCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
+ VkBufferCreateInfo bufferCreateInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
bufferCreateInfo.size = bufferSize;
bufferCreateInfo.usage = usage;
bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkExternalMemoryBufferCreateInfo externalMemoryBufferCreateInfo = {
- VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO };
+ VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO};
if (isShared)
{
externalMemoryBufferCreateInfo.handleTypes = extMemHandleType;
bufferCreateInfo.pNext = &externalMemoryBufferCreateInfo;
}
- SLANG_VK_RETURN_ON_FAIL(api.vkCreateBuffer(api.m_device, &bufferCreateInfo, nullptr, &m_buffer));
+ SLANG_VK_RETURN_ON_FAIL(
+ api.vkCreateBuffer(api.m_device, &bufferCreateInfo, nullptr, &m_buffer));
VkMemoryRequirements memoryReqs = {};
api.vkGetBufferMemoryRequirements(api.m_device, m_buffer, &memoryReqs);
@@ -51,15 +52,15 @@ Result VKBufferHandleRAII::init(
VkMemoryPropertyFlags actualMemoryProperites =
api.m_deviceMemoryProperties.memoryTypes[memoryTypeIndex].propertyFlags;
- VkMemoryAllocateInfo allocateInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
+ VkMemoryAllocateInfo allocateInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocateInfo.allocationSize = memoryReqs.size;
allocateInfo.memoryTypeIndex = memoryTypeIndex;
#if SLANG_WINDOWS_FAMILY
VkExportMemoryWin32HandleInfoKHR exportMemoryWin32HandleInfo = {
- VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR };
+ VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR};
#endif
VkExportMemoryAllocateInfoKHR exportMemoryAllocateInfo = {
- VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR };
+ VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR};
if (isShared)
{
#if SLANG_WINDOWS_FAMILY
@@ -71,13 +72,13 @@ Result VKBufferHandleRAII::init(
exportMemoryAllocateInfo.pNext =
extMemHandleType & VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR
- ? &exportMemoryWin32HandleInfo
- : nullptr;
+ ? &exportMemoryWin32HandleInfo
+ : nullptr;
#endif
exportMemoryAllocateInfo.handleTypes = extMemHandleType;
allocateInfo.pNext = &exportMemoryAllocateInfo;
}
- VkMemoryAllocateFlagsInfo flagInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO };
+ VkMemoryAllocateFlagsInfo flagInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
if (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT)
{
flagInfo.deviceMask = 1;
@@ -94,8 +95,7 @@ Result VKBufferHandleRAII::init(
}
BufferResourceImpl::BufferResourceImpl(const IBufferResource::Desc& desc, DeviceImpl* renderer)
- : Parent(desc)
- , m_renderer(renderer)
+ : Parent(desc), m_renderer(renderer)
{
assert(renderer);
}
diff --git a/tools/gfx/vulkan/vk-buffer.h b/tools/gfx/vulkan/vk-buffer.h
index c824f3529..cc82cef90 100644
--- a/tools/gfx/vulkan/vk-buffer.h
+++ b/tools/gfx/vulkan/vk-buffer.h
@@ -29,7 +29,8 @@ public:
VKBufferHandleRAII()
: m_api(nullptr)
- {}
+ {
+ }
~VKBufferHandleRAII()
{
@@ -61,12 +62,12 @@ public:
virtual SLANG_NO_THROW DeviceAddress SLANG_MCALL getDeviceAddress() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeResourceHandle(InteropHandle* outHandle) override;
+ getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- map(MemoryRange* rangeToRead, void** outPointer) override;
+ map(MemoryRange* rangeToRead, void** outPointer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL unmap(MemoryRange* writtenRange) override;
diff --git a/tools/gfx/vulkan/vk-command-buffer.cpp b/tools/gfx/vulkan/vk-command-buffer.cpp
index 8e0b35750..320212c9a 100644
--- a/tools/gfx/vulkan/vk-command-buffer.cpp
+++ b/tools/gfx/vulkan/vk-command-buffer.cpp
@@ -24,10 +24,15 @@ ICommandBuffer* CommandBufferImpl::getInterface(const Guid& guid)
return nullptr;
}
-void CommandBufferImpl::comFree() { m_transientHeap.breakStrongReference(); }
+void CommandBufferImpl::comFree()
+{
+ m_transientHeap.breakStrongReference();
+}
Result CommandBufferImpl::init(
- DeviceImpl* renderer, VkCommandPool pool, TransientResourceHeapImpl* transientHeap)
+ DeviceImpl* renderer,
+ VkCommandPool pool,
+ TransientResourceHeapImpl* transientHeap)
{
m_renderer = renderer;
m_transientHeap = transientHeap;
@@ -89,7 +94,9 @@ VkCommandBuffer CommandBufferImpl::getPreCommandBuffer()
}
void CommandBufferImpl::encodeRenderCommands(
- IRenderPassLayout* renderPass, IFramebuffer* framebuffer, IRenderCommandEncoder** outEncoder)
+ IRenderPassLayout* renderPass,
+ IFramebuffer* framebuffer,
+ IRenderCommandEncoder** outEncoder)
{
if (!m_renderCommandEncoder)
{
diff --git a/tools/gfx/vulkan/vk-command-buffer.h b/tools/gfx/vulkan/vk-command-buffer.h
index 1c1c76ebd..aa45fc56e 100644
--- a/tools/gfx/vulkan/vk-command-buffer.h
+++ b/tools/gfx/vulkan/vk-command-buffer.h
@@ -14,9 +14,7 @@ using namespace Slang;
namespace vk
{
-class CommandBufferImpl
- : public ICommandBuffer
- , public ComObject
+class CommandBufferImpl : public ICommandBuffer, public ComObject
{
public:
// There are a pair of cyclic references between a `TransientResourceHeap` and
@@ -59,11 +57,11 @@ public:
IFramebuffer* framebuffer,
IRenderCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
+ encodeComputeCommands(IComputeCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
+ encodeResourceCommands(IResourceCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
+ encodeRayTracingCommands(IRayTracingCommandEncoder** outEncoder) override;
virtual SLANG_NO_THROW void SLANG_MCALL close() override;
virtual SLANG_NO_THROW Result SLANG_MCALL getNativeHandle(InteropHandle* outHandle) override;
};
diff --git a/tools/gfx/vulkan/vk-command-encoder.cpp b/tools/gfx/vulkan/vk-command-encoder.cpp
index 7f3110ea5..f9caff437 100644
--- a/tools/gfx/vulkan/vk-command-encoder.cpp
+++ b/tools/gfx/vulkan/vk-command-encoder.cpp
@@ -3,6 +3,7 @@
#include "vk-buffer.h"
#include "vk-command-buffer.h"
+#include "vk-helper-functions.h"
#include "vk-query.h"
#include "vk-render-pass.h"
#include "vk-resource-views.h"
@@ -12,8 +13,6 @@
#include "vk-texture.h"
#include "vk-transient-heap.h"
-#include "vk-helper-functions.h"
-
namespace gfx
{
@@ -26,15 +25,10 @@ int PipelineCommandEncoder::getBindPointIndex(VkPipelineBindPoint bindPoint)
{
switch (bindPoint)
{
- case VK_PIPELINE_BIND_POINT_GRAPHICS:
- return 0;
- case VK_PIPELINE_BIND_POINT_COMPUTE:
- return 1;
- case VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR:
- return 2;
- default:
- assert(!"unknown pipeline type.");
- return -1;
+ case VK_PIPELINE_BIND_POINT_GRAPHICS: return 0;
+ case VK_PIPELINE_BIND_POINT_COMPUTE: return 1;
+ case VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR: return 2;
+ default: assert(!"unknown pipeline type."); return -1;
}
}
@@ -63,8 +57,8 @@ void PipelineCommandEncoder::_uploadBufferData(
auto& api = buffer->m_renderer->m_api;
IBufferResource* stagingBuffer = nullptr;
Offset stagingBufferOffset = 0;
- transientHeap->allocateStagingBuffer(
- size, stagingBuffer, stagingBufferOffset, MemoryType::Upload);
+ transientHeap
+ ->allocateStagingBuffer(size, stagingBuffer, stagingBufferOffset, MemoryType::Upload);
BufferResourceImpl* stagingBufferImpl = static_cast<BufferResourceImpl*>(stagingBuffer);
@@ -93,7 +87,10 @@ void PipelineCommandEncoder::_uploadBufferData(
}
void PipelineCommandEncoder::uploadBufferDataImpl(
- IBufferResource* buffer, Offset offset, Size size, void* data)
+ IBufferResource* buffer,
+ Offset offset,
+ Size size,
+ void* data)
{
m_vkPreCommandBuffer = m_commandBuffer->getPreCommandBuffer();
_uploadBufferData(
@@ -105,7 +102,9 @@ void PipelineCommandEncoder::uploadBufferDataImpl(
data);
}
-Result PipelineCommandEncoder::bindRootShaderObjectImpl(RootShaderObjectImpl* rootShaderObject, VkPipelineBindPoint bindPoint)
+Result PipelineCommandEncoder::bindRootShaderObjectImpl(
+ RootShaderObjectImpl* rootShaderObject,
+ VkPipelineBindPoint bindPoint)
{
// Obtain specialized root layout.
auto specializedLayout = rootShaderObject->getSpecializedLayout();
@@ -162,7 +161,8 @@ Result PipelineCommandEncoder::bindRootShaderObjectImpl(RootShaderObjectImpl* ro
}
Result PipelineCommandEncoder::setPipelineStateImpl(
- IPipelineState* state, IShaderObject** outRootObject)
+ IPipelineState* state,
+ IShaderObject** outRootObject)
{
m_currentPipeline = static_cast<PipelineStateImpl*>(state);
m_commandBuffer->m_mutableRootShaderObject = nullptr;
@@ -174,10 +174,12 @@ Result PipelineCommandEncoder::setPipelineStateImpl(
}
Result PipelineCommandEncoder::setPipelineStateWithRootObjectImpl(
- IPipelineState* state, IShaderObject* rootObject)
+ IPipelineState* state,
+ IShaderObject* rootObject)
{
m_currentPipeline = static_cast<PipelineStateImpl*>(state);
- m_commandBuffer->m_mutableRootShaderObject = static_cast<MutableRootShaderObjectImpl*>(rootObject);
+ m_commandBuffer->m_mutableRootShaderObject =
+ static_cast<MutableRootShaderObjectImpl*>(rootObject);
return SLANG_OK;
}
@@ -188,11 +190,11 @@ Result PipelineCommandEncoder::bindRenderState(VkPipelineBindPoint pipelineBindP
// Get specialized pipeline state and bind it.
//
RootShaderObjectImpl* rootObjectImpl = m_commandBuffer->m_mutableRootShaderObject
- ? m_commandBuffer->m_mutableRootShaderObject.Ptr()
- : &m_commandBuffer->m_rootObject;
+ ? m_commandBuffer->m_mutableRootShaderObject.Ptr()
+ : &m_commandBuffer->m_rootObject;
RefPtr<PipelineStateBase> newPipeline;
- SLANG_RETURN_ON_FAIL(m_device->maybeSpecializePipeline(
- m_currentPipeline, rootObjectImpl, newPipeline));
+ SLANG_RETURN_ON_FAIL(
+ m_device->maybeSpecializePipeline(m_currentPipeline, rootObjectImpl, newPipeline));
PipelineStateImpl* newPipelineImpl = static_cast<PipelineStateImpl*>(newPipeline.Ptr());
SLANG_RETURN_ON_FAIL(newPipelineImpl->ensureAPIPipelineStateCreated());
@@ -206,12 +208,16 @@ Result PipelineCommandEncoder::bindRenderState(VkPipelineBindPoint pipelineBindP
api.vkCmdBindPipeline(m_vkCommandBuffer, pipelineBindPoint, newPipelineImpl->m_pipeline);
m_boundPipelines[pipelineBindPointId] = newPipelineImpl->m_pipeline;
}
-
+
return SLANG_OK;
}
void ResourceCommandEncoder::copyBuffer(
- IBufferResource* dst, Offset dstOffset, IBufferResource* src, Offset srcOffset, Size size)
+ IBufferResource* dst,
+ Offset dstOffset,
+ IBufferResource* src,
+ Offset srcOffset,
+ Size size)
{
auto& vkAPI = m_commandBuffer->m_renderer->m_api;
@@ -236,7 +242,10 @@ void ResourceCommandEncoder::copyBuffer(
}
void ResourceCommandEncoder::uploadBufferData(
- IBufferResource* buffer, Offset offset, Size size, void* data)
+ IBufferResource* buffer,
+ Offset offset,
+ Size size,
+ void* data)
{
PipelineCommandEncoder::_uploadBufferData(
m_commandBuffer->m_commandBuffer,
@@ -248,7 +257,10 @@ void ResourceCommandEncoder::uploadBufferData(
}
void ResourceCommandEncoder::textureBarrier(
- GfxCount count, ITextureResource* const* textures, ResourceState src, ResourceState dst)
+ GfxCount count,
+ ITextureResource* const* textures,
+ ResourceState src,
+ ResourceState dst)
{
ShortList<VkImageMemoryBarrier, 16> barriers;
@@ -262,7 +274,8 @@ void ResourceCommandEncoder::textureBarrier(
barrier.image = image->m_image;
barrier.oldLayout = translateImageLayout(src);
barrier.newLayout = translateImageLayout(dst);
- barrier.subresourceRange.aspectMask = getAspectMaskFromFormat(VulkanUtil::getVkFormat(desc->format));
+ barrier.subresourceRange.aspectMask =
+ getAspectMaskFromFormat(VulkanUtil::getVkFormat(desc->format));
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
@@ -291,7 +304,10 @@ void ResourceCommandEncoder::textureBarrier(
// TODO: Change size_t to Count?
void ResourceCommandEncoder::bufferBarrier(
- GfxCount count, IBufferResource* const* buffers, ResourceState src, ResourceState dst)
+ GfxCount count,
+ IBufferResource* const* buffers,
+ ResourceState src,
+ ResourceState dst)
{
List<VkBufferMemoryBarrier> barriers;
barriers.reserve(count);
@@ -352,7 +368,10 @@ void ResourceCommandEncoder::endEncoding()
void ResourceCommandEncoder::writeTimestamp(IQueryPool* queryPool, GfxIndex index)
{
_writeTimestamp(
- &m_commandBuffer->m_renderer->m_api, m_commandBuffer->m_commandBuffer, queryPool, index);
+ &m_commandBuffer->m_renderer->m_api,
+ m_commandBuffer->m_commandBuffer,
+ queryPool,
+ index);
}
void ResourceCommandEncoder::copyTexture(
@@ -389,12 +408,14 @@ void ResourceCommandEncoder::copyTexture(
srcSubresource.mipLevelCount = dstDesc->numMipLevels;
}
VkImageCopy region = {};
- region.srcSubresource.aspectMask = VulkanUtil::getAspectMask(srcSubresource.aspectMask, srcImage->m_vkformat);
+ region.srcSubresource.aspectMask =
+ VulkanUtil::getAspectMask(srcSubresource.aspectMask, srcImage->m_vkformat);
region.srcSubresource.baseArrayLayer = srcSubresource.baseArrayLayer;
region.srcSubresource.mipLevel = srcSubresource.mipLevel;
region.srcSubresource.layerCount = srcSubresource.layerCount;
region.srcOffset = {(int32_t)srcOffset.x, (int32_t)srcOffset.y, (int32_t)srcOffset.z};
- region.dstSubresource.aspectMask = VulkanUtil::getAspectMask(dstSubresource.aspectMask, dstImage->m_vkformat);
+ region.dstSubresource.aspectMask =
+ VulkanUtil::getAspectMask(dstSubresource.aspectMask, dstImage->m_vkformat);
region.dstSubresource.baseArrayLayer = dstSubresource.baseArrayLayer;
region.dstSubresource.mipLevel = dstSubresource.mipLevel;
region.dstSubresource.layerCount = dstSubresource.layerCount;
@@ -450,8 +471,8 @@ void ResourceCommandEncoder::uploadTextureData(
IBufferResource* uploadBuffer = nullptr;
Offset uploadBufferOffset = 0;
- m_commandBuffer->m_transientHeap->allocateStagingBuffer(
- bufferSize, uploadBuffer, uploadBufferOffset, MemoryType::Upload);
+ m_commandBuffer->m_transientHeap
+ ->allocateStagingBuffer(bufferSize, uploadBuffer, uploadBufferOffset, MemoryType::Upload);
// Copy into upload buffer
{
@@ -535,7 +556,9 @@ void ResourceCommandEncoder::uploadTextureData(
region.imageSubresource.layerCount = 1;
region.imageOffset = {0, 0, 0};
region.imageExtent = {
- uint32_t(mipSize.width), uint32_t(mipSize.height), uint32_t(mipSize.depth)};
+ uint32_t(mipSize.width),
+ uint32_t(mipSize.height),
+ uint32_t(mipSize.depth)};
// Do the copy (do all depths in a single go)
vkApi.vkCmdCopyBufferToImage(
@@ -554,7 +577,8 @@ void ResourceCommandEncoder::uploadTextureData(
}
void ResourceCommandEncoder::_clearColorImage(
- TextureResourceViewImpl* viewImpl, ClearValue* clearValue)
+ TextureResourceViewImpl* viewImpl,
+ ClearValue* clearValue)
{
auto& api = m_commandBuffer->m_renderer->m_api;
auto layout = viewImpl->m_layout;
@@ -601,7 +625,9 @@ void ResourceCommandEncoder::_clearColorImage(
}
void ResourceCommandEncoder::_clearDepthImage(
- TextureResourceViewImpl* viewImpl, ClearValue* clearValue, ClearResourceViewFlags::Enum flags)
+ TextureResourceViewImpl* viewImpl,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags)
{
auto& api = m_commandBuffer->m_renderer->m_api;
auto layout = viewImpl->m_layout;
@@ -662,17 +688,26 @@ void ResourceCommandEncoder::_clearDepthImage(
}
void ResourceCommandEncoder::_clearBuffer(
- VkBuffer buffer, uint64_t bufferSize, const IResourceView::Desc& desc, uint32_t clearValue)
+ VkBuffer buffer,
+ uint64_t bufferSize,
+ const IResourceView::Desc& desc,
+ uint32_t clearValue)
{
auto& api = m_commandBuffer->m_renderer->m_api;
auto clearOffset = desc.bufferRange.offset;
auto clearSize = desc.bufferRange.size == 0 ? bufferSize - clearOffset : desc.bufferRange.size;
api.vkCmdFillBuffer(
- m_commandBuffer->m_commandBuffer, buffer, clearOffset, clearSize, clearValue);
+ m_commandBuffer->m_commandBuffer,
+ buffer,
+ clearOffset,
+ clearSize,
+ clearValue);
}
void ResourceCommandEncoder::clearResourceView(
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags)
+ IResourceView* view,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags)
{
auto& api = m_commandBuffer->m_renderer->m_api;
switch (view->getViewDesc()->type)
@@ -770,18 +805,22 @@ void ResourceCommandEncoder::resolveResource(
for (GfxIndex mip = 0; mip < sourceRange.mipLevelCount; ++mip)
{
VkImageResolve region = {};
- region.srcSubresource.aspectMask = VulkanUtil::getAspectMask(sourceRange.aspectMask, srcTexture->m_vkformat);
+ region.srcSubresource.aspectMask =
+ VulkanUtil::getAspectMask(sourceRange.aspectMask, srcTexture->m_vkformat);
region.srcSubresource.baseArrayLayer = layer + sourceRange.baseArrayLayer;
region.srcSubresource.layerCount = 1;
region.srcSubresource.mipLevel = mip + sourceRange.mipLevel;
region.srcOffset = {0, 0, 0};
- region.dstSubresource.aspectMask = VulkanUtil::getAspectMask(destRange.aspectMask, dstTexture->m_vkformat);
+ region.dstSubresource.aspectMask =
+ VulkanUtil::getAspectMask(destRange.aspectMask, dstTexture->m_vkformat);
region.dstSubresource.baseArrayLayer = layer + destRange.baseArrayLayer;
region.dstSubresource.layerCount = 1;
region.dstSubresource.mipLevel = mip + destRange.mipLevel;
region.dstOffset = {0, 0, 0};
region.extent = {
- (uint32_t)srcExtent.width, (uint32_t)srcExtent.height, (uint32_t)srcExtent.depth};
+ (uint32_t)srcExtent.width,
+ (uint32_t)srcExtent.height,
+ (uint32_t)srcExtent.depth};
auto& vkApi = m_commandBuffer->m_renderer->m_api;
vkApi.vkCmdResolveImage(
@@ -797,7 +836,11 @@ void ResourceCommandEncoder::resolveResource(
}
void ResourceCommandEncoder::resolveQuery(
- IQueryPool* queryPool, GfxIndex index, GfxCount count, IBufferResource* buffer, Offset offset)
+ IQueryPool* queryPool,
+ GfxIndex index,
+ GfxCount count,
+ IBufferResource* buffer,
+ Offset offset)
{
auto& vkApi = m_commandBuffer->m_renderer->m_api;
auto poolImpl = static_cast<QueryPoolImpl*>(queryPool);
@@ -835,7 +878,8 @@ void ResourceCommandEncoder::copyTextureToBuffer(
region.bufferOffset = dstOffset;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
- region.imageSubresource.aspectMask = VulkanUtil::getAspectMask(srcSubresource.aspectMask, image->m_vkformat);
+ region.imageSubresource.aspectMask =
+ VulkanUtil::getAspectMask(srcSubresource.aspectMask, image->m_vkformat);
region.imageSubresource.mipLevel = srcSubresource.mipLevel;
region.imageSubresource.baseArrayLayer = srcSubresource.baseArrayLayer;
region.imageSubresource.layerCount = srcSubresource.layerCount;
@@ -867,7 +911,8 @@ void ResourceCommandEncoder::textureSubresourceBarrier(
barrier.image = image->m_image;
barrier.oldLayout = translateImageLayout(src);
barrier.newLayout = translateImageLayout(dst);
- barrier.subresourceRange.aspectMask = VulkanUtil::getAspectMask(subresourceRange.aspectMask, image->m_vkformat);
+ barrier.subresourceRange.aspectMask =
+ VulkanUtil::getAspectMask(subresourceRange.aspectMask, image->m_vkformat);
barrier.subresourceRange.baseArrayLayer = subresourceRange.baseArrayLayer;
barrier.subresourceRange.baseMipLevel = subresourceRange.mipLevel;
barrier.subresourceRange.layerCount = subresourceRange.layerCount;
@@ -948,13 +993,15 @@ void RenderCommandEncoder::endEncoding()
}
Result RenderCommandEncoder::bindPipeline(
- IPipelineState* pipelineState, IShaderObject** outRootObject)
+ IPipelineState* pipelineState,
+ IShaderObject** outRootObject)
{
return setPipelineStateImpl(pipelineState, outRootObject);
}
Result RenderCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject)
+ IPipelineState* pipelineState,
+ IShaderObject* rootObject)
{
return setPipelineStateWithRootObjectImpl(pipelineState, rootObject);
}
@@ -1009,14 +1056,14 @@ void RenderCommandEncoder::setPrimitiveTopology(PrimitiveTopology topology)
if (api.vkCmdSetPrimitiveTopologyEXT)
{
api.vkCmdSetPrimitiveTopologyEXT(
- m_vkCommandBuffer, VulkanUtil::getVkPrimitiveTopology(topology));
+ m_vkCommandBuffer,
+ VulkanUtil::getVkPrimitiveTopology(topology));
}
else
{
switch (topology)
{
- case PrimitiveTopology::TriangleList:
- break;
+ case PrimitiveTopology::TriangleList: break;
default:
// We are using a non-list topology, but we don't have dynmaic state
// extension, error out.
@@ -1043,31 +1090,35 @@ void RenderCommandEncoder::setVertexBuffers(
VkDeviceSize offset = VkDeviceSize(offsets[i]);
m_api->vkCmdBindVertexBuffers(
- m_vkCommandBuffer, (uint32_t)slotIndex, 1, vertexBuffers, &offset);
+ m_vkCommandBuffer,
+ (uint32_t)slotIndex,
+ 1,
+ vertexBuffers,
+ &offset);
}
}
}
void RenderCommandEncoder::setIndexBuffer(
- IBufferResource* buffer, Format indexFormat, Offset offset)
+ IBufferResource* buffer,
+ Format indexFormat,
+ Offset offset)
{
VkIndexType indexType = VK_INDEX_TYPE_UINT16;
switch (indexFormat)
{
- case Format::R16_UINT:
- indexType = VK_INDEX_TYPE_UINT16;
- break;
- case Format::R32_UINT:
- indexType = VK_INDEX_TYPE_UINT32;
- break;
- default:
- assert(!"unsupported index format");
+ case Format::R16_UINT: indexType = VK_INDEX_TYPE_UINT16; break;
+ case Format::R32_UINT: indexType = VK_INDEX_TYPE_UINT32; break;
+ default: assert(!"unsupported index format");
}
BufferResourceImpl* bufferImpl = static_cast<BufferResourceImpl*>(buffer);
m_api->vkCmdBindIndexBuffer(
- m_vkCommandBuffer, bufferImpl->m_buffer.m_buffer, (VkDeviceSize)offset, indexType);
+ m_vkCommandBuffer,
+ bufferImpl->m_buffer.m_buffer,
+ (VkDeviceSize)offset,
+ indexType);
}
Result RenderCommandEncoder::prepareDraw()
@@ -1090,7 +1141,9 @@ Result RenderCommandEncoder::draw(GfxCount vertexCount, GfxIndex startVertex)
}
Result RenderCommandEncoder::drawIndexed(
- GfxCount indexCount, GfxIndex startIndex, GfxIndex baseVertex)
+ GfxCount indexCount,
+ GfxIndex startIndex,
+ GfxIndex baseVertex)
{
SLANG_RETURN_ON_FAIL(prepareDraw());
auto& api = *m_api;
@@ -1152,7 +1205,9 @@ Result RenderCommandEncoder::drawIndexedIndirect(
}
Result RenderCommandEncoder::setSamplePositions(
- GfxCount samplesPerPixel, GfxCount pixelCount, const SamplePosition* samplePositions)
+ GfxCount samplesPerPixel,
+ GfxCount pixelCount,
+ const SamplePosition* samplePositions)
{
if (m_api->vkCmdSetSampleLocationsEXT)
{
@@ -1175,7 +1230,11 @@ Result RenderCommandEncoder::drawInstanced(
SLANG_RETURN_ON_FAIL(prepareDraw());
auto& api = *m_api;
api.vkCmdDraw(
- m_vkCommandBuffer, vertexCount, instanceCount, startVertex, startInstanceLocation);
+ m_vkCommandBuffer,
+ vertexCount,
+ instanceCount,
+ startVertex,
+ startInstanceLocation);
return SLANG_OK;
}
@@ -1206,16 +1265,21 @@ Result RenderCommandEncoder::drawMeshTasks(int x, int y, int z)
return SLANG_OK;
}
-void ComputeCommandEncoder::endEncoding() { endEncodingImpl(); }
+void ComputeCommandEncoder::endEncoding()
+{
+ endEncodingImpl();
+}
Result ComputeCommandEncoder::bindPipeline(
- IPipelineState* pipelineState, IShaderObject** outRootObject)
+ IPipelineState* pipelineState,
+ IShaderObject** outRootObject)
{
return setPipelineStateImpl(pipelineState, outRootObject);
}
Result ComputeCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject)
+ IPipelineState* pipelineState,
+ IShaderObject* rootObject)
{
return setPipelineStateWithRootObjectImpl(pipelineState, rootObject);
}
@@ -1303,8 +1367,7 @@ void RayTracingCommandEncoder::_queryAccelerationStructureProperties(
case QueryType::AccelerationStructureSerializedSize:
queryType = VK_QUERY_TYPE_ACCELERATION_STRUCTURE_SERIALIZATION_SIZE_KHR;
break;
- case QueryType::AccelerationStructureCurrentSize:
- continue;
+ case QueryType::AccelerationStructureCurrentSize: continue;
default:
getDebugCallback()->handleMessage(
DebugMessageType::Error,
@@ -1362,7 +1425,10 @@ void RayTracingCommandEncoder::buildAccelerationStructure(
auto rangeInfoPtr = rangeInfos.getBuffer();
m_commandBuffer->m_renderer->m_api.vkCmdBuildAccelerationStructuresKHR(
- m_commandBuffer->m_commandBuffer, 1, &geomInfoBuilder.buildInfo, &rangeInfoPtr);
+ m_commandBuffer->m_commandBuffer,
+ 1,
+ &geomInfoBuilder.buildInfo,
+ &rangeInfoPtr);
if (propertyQueryCount)
{
@@ -1372,7 +1438,9 @@ void RayTracingCommandEncoder::buildAccelerationStructure(
}
void RayTracingCommandEncoder::copyAccelerationStructure(
- IAccelerationStructure* dest, IAccelerationStructure* src, AccelerationStructureCopyMode mode)
+ IAccelerationStructure* dest,
+ IAccelerationStructure* src,
+ AccelerationStructureCopyMode mode)
{
VkCopyAccelerationStructureInfoKHR copyInfo = {
VK_STRUCTURE_TYPE_COPY_ACCELERATION_STRUCTURE_INFO_KHR};
@@ -1394,7 +1462,8 @@ void RayTracingCommandEncoder::copyAccelerationStructure(
return;
}
m_commandBuffer->m_renderer->m_api.vkCmdCopyAccelerationStructureKHR(
- m_commandBuffer->m_commandBuffer, &copyInfo);
+ m_commandBuffer->m_commandBuffer,
+ &copyInfo);
}
void RayTracingCommandEncoder::queryAccelerationStructureProperties(
@@ -1404,11 +1473,15 @@ void RayTracingCommandEncoder::queryAccelerationStructureProperties(
AccelerationStructureQueryDesc* queryDescs)
{
_queryAccelerationStructureProperties(
- accelerationStructureCount, accelerationStructures, queryCount, queryDescs);
+ accelerationStructureCount,
+ accelerationStructures,
+ queryCount,
+ queryDescs);
}
void RayTracingCommandEncoder::serializeAccelerationStructure(
- DeviceAddress dest, IAccelerationStructure* source)
+ DeviceAddress dest,
+ IAccelerationStructure* source)
{
VkCopyAccelerationStructureToMemoryInfoKHR copyInfo = {
VK_STRUCTURE_TYPE_COPY_ACCELERATION_STRUCTURE_TO_MEMORY_INFO_KHR};
@@ -1416,11 +1489,13 @@ void RayTracingCommandEncoder::serializeAccelerationStructure(
copyInfo.dst.deviceAddress = dest;
copyInfo.mode = VK_COPY_ACCELERATION_STRUCTURE_MODE_SERIALIZE_KHR;
m_commandBuffer->m_renderer->m_api.vkCmdCopyAccelerationStructureToMemoryKHR(
- m_commandBuffer->m_commandBuffer, &copyInfo);
+ m_commandBuffer->m_commandBuffer,
+ &copyInfo);
}
void RayTracingCommandEncoder::deserializeAccelerationStructure(
- IAccelerationStructure* dest, DeviceAddress source)
+ IAccelerationStructure* dest,
+ DeviceAddress source)
{
VkCopyMemoryToAccelerationStructureInfoKHR copyInfo = {
VK_STRUCTURE_TYPE_COPY_MEMORY_TO_ACCELERATION_STRUCTURE_INFO_KHR};
@@ -1428,16 +1503,20 @@ void RayTracingCommandEncoder::deserializeAccelerationStructure(
copyInfo.dst = static_cast<AccelerationStructureImpl*>(dest)->m_vkHandle;
copyInfo.mode = VK_COPY_ACCELERATION_STRUCTURE_MODE_DESERIALIZE_KHR;
m_commandBuffer->m_renderer->m_api.vkCmdCopyMemoryToAccelerationStructureKHR(
- m_commandBuffer->m_commandBuffer, &copyInfo);
+ m_commandBuffer->m_commandBuffer,
+ &copyInfo);
}
-Result RayTracingCommandEncoder::bindPipeline(IPipelineState* pipeline, IShaderObject** outRootObject)
+Result RayTracingCommandEncoder::bindPipeline(
+ IPipelineState* pipeline,
+ IShaderObject** outRootObject)
{
return setPipelineStateImpl(pipeline, outRootObject);
}
Result RayTracingCommandEncoder::bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject)
+ IPipelineState* pipelineState,
+ IShaderObject* rootObject)
{
return setPipelineStateWithRootObjectImpl(pipelineState, rootObject);
}
@@ -1498,7 +1577,10 @@ Result RayTracingCommandEncoder::dispatchRays(
return SLANG_OK;
}
-void RayTracingCommandEncoder::endEncoding() { endEncodingImpl(); }
+void RayTracingCommandEncoder::endEncoding()
+{
+ endEncodingImpl();
+}
} // namespace vk
} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-command-encoder.h b/tools/gfx/vulkan/vk-command-encoder.h
index 05c47920e..ec9854b30 100644
--- a/tools/gfx/vulkan/vk-command-encoder.h
+++ b/tools/gfx/vulkan/vk-command-encoder.h
@@ -40,7 +40,9 @@ public:
void uploadBufferDataImpl(IBufferResource* buffer, Offset offset, Size size, void* data);
- Result bindRootShaderObjectImpl(RootShaderObjectImpl* rootShaderObject, VkPipelineBindPoint bindPoint);
+ Result bindRootShaderObjectImpl(
+ RootShaderObjectImpl* rootShaderObject,
+ VkPipelineBindPoint bindPoint);
Result setPipelineStateImpl(IPipelineState* state, IShaderObject** outRootObject);
@@ -49,9 +51,7 @@ public:
Result bindRenderState(VkPipelineBindPoint pipelineBindPoint);
};
-class ResourceCommandEncoder
- : public IResourceCommandEncoder
- , public PipelineCommandEncoder
+class ResourceCommandEncoder : public IResourceCommandEncoder, public PipelineCommandEncoder
{
public:
virtual void* getInterface(SlangUUID const& guid)
@@ -61,7 +61,7 @@ public:
return nullptr;
}
virtual SLANG_NO_THROW SlangResult SLANG_MCALL
- queryInterface(SlangUUID const& uuid, void** outObject) override
+ queryInterface(SlangUUID const& uuid, void** outObject) override
{
if (auto ptr = getInterface(uuid))
{
@@ -80,7 +80,7 @@ public:
Offset srcOffset,
Size size) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- uploadBufferData(IBufferResource* buffer, Offset offset, Size size, void* data) override;
+ uploadBufferData(IBufferResource* buffer, Offset offset, Size size, void* data) override;
virtual SLANG_NO_THROW void SLANG_MCALL textureBarrier(
GfxCount count,
ITextureResource* const* textures,
@@ -94,7 +94,7 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW void SLANG_MCALL
- writeTimestamp(IQueryPool* queryPool, GfxIndex index) override;
+ writeTimestamp(IQueryPool* queryPool, GfxIndex index) override;
virtual SLANG_NO_THROW void SLANG_MCALL copyTexture(
ITextureResource* dst,
@@ -123,10 +123,15 @@ public:
ClearResourceViewFlags::Enum flags);
void _clearBuffer(
- VkBuffer buffer, uint64_t bufferSize, const IResourceView::Desc& desc, uint32_t clearValue);
+ VkBuffer buffer,
+ uint64_t bufferSize,
+ const IResourceView::Desc& desc,
+ uint32_t clearValue);
virtual SLANG_NO_THROW void SLANG_MCALL clearResourceView(
- IResourceView* view, ClearValue* clearValue, ClearResourceViewFlags::Enum flags) override;
+ IResourceView* view,
+ ClearValue* clearValue,
+ ClearResourceViewFlags::Enum flags) override;
virtual SLANG_NO_THROW void SLANG_MCALL resolveResource(
ITextureResource* source,
@@ -161,18 +166,17 @@ public:
ResourceState dst) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- beginDebugEvent(const char* name, float rgbColor[3]) override;
+ beginDebugEvent(const char* name, float rgbColor[3]) override;
virtual SLANG_NO_THROW void SLANG_MCALL endDebugEvent() override;
};
-class RenderCommandEncoder
- : public IRenderCommandEncoder
- , public ResourceCommandEncoder
+class RenderCommandEncoder : public IRenderCommandEncoder, public ResourceCommandEncoder
{
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoder)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IRenderCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
@@ -189,19 +193,19 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* pipelineState, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* pipelineState, IShaderObject** outRootObject) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ bindPipelineWithRootObject(IPipelineState* pipelineState, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setViewports(GfxCount count, const Viewport* viewports) override;
+ setViewports(GfxCount count, const Viewport* viewports) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setScissorRects(GfxCount count, const ScissorRect* rects) override;
+ setScissorRects(GfxCount count, const ScissorRect* rects) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setPrimitiveTopology(PrimitiveTopology topology) override;
+ setPrimitiveTopology(PrimitiveTopology topology) override;
virtual SLANG_NO_THROW void SLANG_MCALL setVertexBuffers(
GfxIndex startSlot,
@@ -210,14 +214,14 @@ public:
const Offset* offsets) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) override;
+ setIndexBuffer(IBufferResource* buffer, Format indexFormat, Offset offset = 0) override;
Result prepareDraw();
virtual SLANG_NO_THROW Result SLANG_MCALL
- draw(GfxCount vertexCount, GfxIndex startVertex = 0) override;
+ draw(GfxCount vertexCount, GfxIndex startVertex = 0) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override;
+ drawIndexed(GfxCount indexCount, GfxIndex startIndex = 0, GfxIndex baseVertex = 0) override;
virtual SLANG_NO_THROW void SLANG_MCALL setStencilReference(uint32_t referenceValue) override;
@@ -253,19 +257,17 @@ public:
GfxIndex baseVertexLocation,
GfxIndex startInstanceLocation) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL
- drawMeshTasks(int x, int y, int z) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL drawMeshTasks(int x, int y, int z) override;
};
-class ComputeCommandEncoder
- : public IComputeCommandEncoder
- , public ResourceCommandEncoder
+class ComputeCommandEncoder : public IComputeCommandEncoder, public ResourceCommandEncoder
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoder)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IComputeCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
@@ -275,33 +277,32 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* pipelineState, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* pipelineState, IShaderObject** outRootObject) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ bindPipelineWithRootObject(IPipelineState* pipelineState, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL dispatchCompute(int x, int y, int z) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override;
+ dispatchComputeIndirect(IBufferResource* argBuffer, Offset offset) override;
};
-class RayTracingCommandEncoder
- : public IRayTracingCommandEncoder
- , public ResourceCommandEncoder
+class RayTracingCommandEncoder : public IRayTracingCommandEncoder, public ResourceCommandEncoder
{
public:
SLANG_GFX_FORWARD_RESOURCE_COMMAND_ENCODER_IMPL(ResourceCommandEncoder)
virtual void* getInterface(SlangUUID const& uuid) override
{
- if (uuid == GfxGUID::IID_IResourceCommandEncoder || uuid == GfxGUID::IID_IRayTracingCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
+ if (uuid == GfxGUID::IID_IResourceCommandEncoder ||
+ uuid == GfxGUID::IID_IRayTracingCommandEncoder || uuid == ISlangUnknown::getTypeGuid())
{
return this;
}
return nullptr;
}
-public:
+public:
void _memoryBarrier(
int count,
IAccelerationStructure* const* structures,
@@ -331,16 +332,16 @@ public:
AccelerationStructureQueryDesc* queryDescs) override;
virtual SLANG_NO_THROW void SLANG_MCALL
- serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure* source) override;
+ serializeAccelerationStructure(DeviceAddress dest, IAccelerationStructure* source) override;
- virtual SLANG_NO_THROW void SLANG_MCALL deserializeAccelerationStructure(
- IAccelerationStructure* dest, DeviceAddress source) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ deserializeAccelerationStructure(IAccelerationStructure* dest, DeviceAddress source) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- bindPipeline(IPipelineState* pipeline, IShaderObject** outRootObject) override;
+ bindPipeline(IPipelineState* pipeline, IShaderObject** outRootObject) override;
- virtual SLANG_NO_THROW Result SLANG_MCALL bindPipelineWithRootObject(
- IPipelineState* pipelineState, IShaderObject* rootObject) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ bindPipelineWithRootObject(IPipelineState* pipelineState, IShaderObject* rootObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL dispatchRays(
GfxIndex raygenShaderIndex,
diff --git a/tools/gfx/vulkan/vk-command-queue.cpp b/tools/gfx/vulkan/vk-command-queue.cpp
index 58d4fa972..232e7f0b1 100644
--- a/tools/gfx/vulkan/vk-command-queue.cpp
+++ b/tools/gfx/vulkan/vk-command-queue.cpp
@@ -36,8 +36,8 @@ void CommandQueueImpl::init(DeviceImpl* renderer, VkQueue queue, uint32_t queueF
VkSemaphoreCreateInfo semaphoreCreateInfo = {};
semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphoreCreateInfo.flags = 0;
- m_renderer->m_api.vkCreateSemaphore(
- m_renderer->m_api.m_device, &semaphoreCreateInfo, nullptr, &m_semaphore);
+ m_renderer->m_api
+ .vkCreateSemaphore(m_renderer->m_api.m_device, &semaphoreCreateInfo, nullptr, &m_semaphore);
}
void CommandQueueImpl::waitOnHost()
@@ -53,10 +53,15 @@ Result CommandQueueImpl::getNativeHandle(InteropHandle* outHandle)
return SLANG_OK;
}
-const CommandQueueImpl::Desc& CommandQueueImpl::getDesc() { return m_desc; }
+const CommandQueueImpl::Desc& CommandQueueImpl::getDesc()
+{
+ return m_desc;
+}
Result CommandQueueImpl::waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* waitValues)
{
for (GfxIndex i = 0; i < fenceCount; ++i)
{
@@ -69,7 +74,10 @@ Result CommandQueueImpl::waitForFenceValuesOnDevice(
}
void CommandQueueImpl::queueSubmitImpl(
- uint32_t count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal)
+ uint32_t count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal)
{
auto& vkAPI = m_renderer->m_api;
m_submitCommandBuffers.clear();
@@ -89,7 +97,8 @@ void CommandQueueImpl::queueSubmitImpl(
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags stageFlag[] = {
- VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT};
+ VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
+ VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT};
submitInfo.pWaitDstStageMask = stageFlag;
submitInfo.commandBufferCount = (uint32_t)m_submitCommandBuffers.getCount();
submitInfo.pCommandBuffers = m_submitCommandBuffers.getBuffer();
@@ -144,7 +153,10 @@ void CommandQueueImpl::queueSubmitImpl(
}
void CommandQueueImpl::executeCommandBuffers(
- GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal)
+ GfxCount count,
+ ICommandBuffer* const* commandBuffers,
+ IFence* fence,
+ uint64_t valueToSignal)
{
if (count == 0 && fence == nullptr)
return;
diff --git a/tools/gfx/vulkan/vk-command-queue.h b/tools/gfx/vulkan/vk-command-queue.h
index c7d4e3eb4..07b3e14e6 100644
--- a/tools/gfx/vulkan/vk-command-queue.h
+++ b/tools/gfx/vulkan/vk-command-queue.h
@@ -12,9 +12,7 @@ using namespace Slang;
namespace vk
{
-class CommandQueueImpl
- : public ICommandQueue
- , public ComObject
+class CommandQueueImpl : public ICommandQueue, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -44,8 +42,8 @@ public:
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override;
- virtual SLANG_NO_THROW Result SLANG_MCALL waitForFenceValuesOnDevice(
- GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
+ virtual SLANG_NO_THROW Result SLANG_MCALL
+ waitForFenceValuesOnDevice(GfxCount fenceCount, IFence** fences, uint64_t* waitValues) override;
void queueSubmitImpl(
uint32_t count,
diff --git a/tools/gfx/vulkan/vk-descriptor-allocator.cpp b/tools/gfx/vulkan/vk-descriptor-allocator.cpp
index 49199091d..afaa836ca 100644
--- a/tools/gfx/vulkan/vk-descriptor-allocator.cpp
+++ b/tools/gfx/vulkan/vk-descriptor-allocator.cpp
@@ -1,4 +1,5 @@
#include "vk-descriptor-allocator.h"
+
#include "vk-util.h"
namespace gfx
@@ -31,13 +32,17 @@ VkDescriptorPool DescriptorSetAllocator::newPool()
descriptorPoolInfo.pPoolSizes = poolSizes.getBuffer();
descriptorPoolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
- VkDescriptorPoolInlineUniformBlockCreateInfo inlineUniformBlockInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_INLINE_UNIFORM_BLOCK_CREATE_INFO };
+ VkDescriptorPoolInlineUniformBlockCreateInfo inlineUniformBlockInfo = {
+ VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_INLINE_UNIFORM_BLOCK_CREATE_INFO};
inlineUniformBlockInfo.maxInlineUniformBlockBindings = 16;
descriptorPoolInfo.pNext = &inlineUniformBlockInfo;
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
SLANG_VK_CHECK(m_api->vkCreateDescriptorPool(
- m_api->m_device, &descriptorPoolInfo, nullptr, &descriptorPool));
+ m_api->m_device,
+ &descriptorPoolInfo,
+ nullptr,
+ &descriptorPool));
pools.add(descriptorPool);
return descriptorPool;
}
@@ -77,4 +82,4 @@ VulkanDescriptorSet DescriptorSetAllocator::allocate(VkDescriptorSetLayout layou
assert(!"descriptor set allocation failed.");
return rs;
}
-}
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-descriptor-allocator.h b/tools/gfx/vulkan/vk-descriptor-allocator.h
index 3d5c441ad..5be1cfae2 100644
--- a/tools/gfx/vulkan/vk-descriptor-allocator.h
+++ b/tools/gfx/vulkan/vk-descriptor-allocator.h
@@ -2,8 +2,8 @@
#pragma once
-#include "vk-api.h"
#include "core/slang-list.h"
+#include "vk-api.h"
namespace gfx
{
diff --git a/tools/gfx/vulkan/vk-device-queue.cpp b/tools/gfx/vulkan/vk-device-queue.cpp
index 1bcfe28c8..8a98d68ec 100644
--- a/tools/gfx/vulkan/vk-device-queue.cpp
+++ b/tools/gfx/vulkan/vk-device-queue.cpp
@@ -1,11 +1,12 @@
// vk-device-queue.cpp
#include "vk-device-queue.h"
-#include <stdlib.h>
-#include <stdio.h>
#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
-namespace gfx {
+namespace gfx
+{
using namespace Slang;
VulkanDeviceQueue::~VulkanDeviceQueue()
@@ -24,7 +25,8 @@ void VulkanDeviceQueue::destroy()
for (int i = 0; i < m_numCommandBuffers; i++)
{
- m_api->vkFreeCommandBuffers(m_api->m_device, m_commandPools[i], 1, &m_commandBuffers[i]);
+ m_api
+ ->vkFreeCommandBuffers(m_api->m_device, m_commandPools[i], 1, &m_commandBuffers[i]);
m_api->vkDestroyFence(m_api->m_device, m_fences[i].fence, nullptr);
m_api->vkDestroyCommandPool(m_api->m_device, m_commandPools[i], nullptr);
}
@@ -35,7 +37,7 @@ void VulkanDeviceQueue::destroy()
SlangResult VulkanDeviceQueue::init(const VulkanApi& api, VkQueue queue, int queueIndex)
{
assert(m_api == nullptr);
-
+
for (int i = 0; i < int(EventType::CountOf); ++i)
{
m_semaphores[i] = VK_NULL_HANDLE;
@@ -135,7 +137,7 @@ void VulkanDeviceQueue::flushStepA()
makeCompleted(EventType::EndFrame);
}
-void VulkanDeviceQueue::_updateFenceAtIndex( int fenceIndex, bool blocking)
+void VulkanDeviceQueue::_updateFenceAtIndex(int fenceIndex, bool blocking)
{
Fence& fence = m_fences[fenceIndex];
@@ -143,7 +145,8 @@ void VulkanDeviceQueue::_updateFenceAtIndex( int fenceIndex, bool blocking)
{
uint64_t timeout = blocking ? ~uint64_t(0) : 0;
- if (VK_SUCCESS == m_api->vkWaitForFences(m_api->m_device, 1, &fence.fence, VK_TRUE, timeout))
+ if (VK_SUCCESS ==
+ m_api->vkWaitForFences(m_api->m_device, 1, &fence.fence, VK_TRUE, timeout))
{
m_api->vkResetFences(m_api->m_device, 1, &fence.fence);
@@ -211,4 +214,4 @@ void VulkanDeviceQueue::makeCompleted(EventType eventType)
m_currentSemaphores[int(eventType)] = VK_NULL_HANDLE;
}
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-device-queue.h b/tools/gfx/vulkan/vk-device-queue.h
index 38d8f2bd6..174e20850 100644
--- a/tools/gfx/vulkan/vk-device-queue.h
+++ b/tools/gfx/vulkan/vk-device-queue.h
@@ -4,7 +4,8 @@
#include "vk-api.h"
#include "vk-descriptor-allocator.h"
-namespace gfx {
+namespace gfx
+{
struct VulkanDeviceQueue
{
@@ -20,53 +21,56 @@ struct VulkanDeviceQueue
CountOf,
};
- /// Initialize - must be called before anything else can be done
+ /// Initialize - must be called before anything else can be done
SlangResult init(const VulkanApi& api, VkQueue queue, int queueIndex);
- /// Flushes the current command list, and steps to next (internally this is equivalent to a stepA followed by stepB)
+ /// Flushes the current command list, and steps to next (internally this is equivalent to a
+ /// stepA followed by stepB)
void flush();
- /// Performs a full flush, and then waits for idle.
+ /// Performs a full flush, and then waits for idle.
void flushAndWait();
- /// Blocks until all work submitted to GPU has completed
+ /// Blocks until all work submitted to GPU has completed
void waitForIdle() { m_api->vkQueueWaitIdle(m_queue); }
- /// Get the graphics queue index (as set on init)
+ /// Get the graphics queue index (as set on init)
int getQueueIndex() const { return m_queueIndex; }
- /// Make the specified event 'current' - meaning it's semaphore must be waited on
+ /// Make the specified event 'current' - meaning it's semaphore must be waited on
VkSemaphore makeCurrent(EventType eventType);
VkSemaphore getSemaphore(EventType eventType);
- /// Makes the event no longer required to be waited on
+ /// Makes the event no longer required to be waited on
void makeCompleted(EventType eventType);
- /// Returns true if the event is already current
- SLANG_FORCE_INLINE bool isCurrent(EventType eventType) const { return m_currentSemaphores[int(eventType)] != VK_NULL_HANDLE; }
+ /// Returns true if the event is already current
+ SLANG_FORCE_INLINE bool isCurrent(EventType eventType) const
+ {
+ return m_currentSemaphores[int(eventType)] != VK_NULL_HANDLE;
+ }
- /// Get the command buffer
+ /// Get the command buffer
VkCommandBuffer getCommandBuffer() const { return m_commandBuffer; }
- /// Get the queue
+ /// Get the queue
VkQueue getQueue() const { return m_queue; }
- /// Get the API
+ /// Get the API
const VulkanApi* getApi() const { return m_api; }
- /// Flushes the current command list
+ /// Flushes the current command list
void flushStepA();
- /// Steps to next command buffer and opens. May block if command buffer is still in use
+ /// Steps to next command buffer and opens. May block if command buffer is still in use
void flushStepB();
- /// Destroy the device queue
+ /// Destroy the device queue
void destroy();
- /// True if the queue appears to be valid and has been initialized
+ /// True if the queue appears to be valid and has been initialized
bool isValid() const { return m_api != nullptr; }
- /// Dtor
+ /// Dtor
~VulkanDeviceQueue();
- protected:
-
+protected:
struct Fence
{
VkFence fence;
@@ -82,9 +86,9 @@ struct VulkanDeviceQueue
int m_commandBufferIndex = 0;
// There are the same amount of command buffers as fences
VkCommandPool m_commandPools[kMaxCommandBuffers] = {VK_NULL_HANDLE};
- VkCommandBuffer m_commandBuffers[kMaxCommandBuffers] = { VK_NULL_HANDLE };
+ VkCommandBuffer m_commandBuffers[kMaxCommandBuffers] = {VK_NULL_HANDLE};
- Fence m_fences[kMaxCommandBuffers] = { {VK_NULL_HANDLE, 0, 0u} };
+ Fence m_fences[kMaxCommandBuffers] = {{VK_NULL_HANDLE, 0, 0u}};
VkCommandBuffer m_commandBuffer = VK_NULL_HANDLE;
VkCommandPool m_commandPool = VK_NULL_HANDLE;
@@ -99,4 +103,4 @@ struct VulkanDeviceQueue
const VulkanApi* m_api = nullptr;
};
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-device.cpp b/tools/gfx/vulkan/vk-device.cpp
index bc1641aff..68b8ba1db 100644
--- a/tools/gfx/vulkan/vk-device.cpp
+++ b/tools/gfx/vulkan/vk-device.cpp
@@ -1,30 +1,28 @@
// vk-device.cpp
#include "vk-device.h"
+#include "source/core/slang-platform.h"
#include "vk-buffer.h"
#include "vk-command-queue.h"
#include "vk-fence.h"
+#include "vk-helper-functions.h"
+#include "vk-pipeline-dump-layer.h"
#include "vk-query.h"
#include "vk-render-pass.h"
#include "vk-resource-views.h"
#include "vk-sampler.h"
-#include "vk-shader-object.h"
#include "vk-shader-object-layout.h"
+#include "vk-shader-object.h"
#include "vk-shader-program.h"
#include "vk-shader-table.h"
#include "vk-swap-chain.h"
#include "vk-transient-heap.h"
#include "vk-vertex-layout.h"
-#include "vk-pipeline-dump-layer.h"
-
-#include "vk-helper-functions.h"
-
-#include "source/core/slang-platform.h"
#ifdef GFX_NV_AFTERMATH
-# include "GFSDK_Aftermath.h"
-# include "GFSDK_Aftermath_Defines.h"
-# include "GFSDK_Aftermath_GpuCrashDump.h"
+#include "GFSDK_Aftermath.h"
+#include "GFSDK_Aftermath_Defines.h"
+#include "GFSDK_Aftermath_GpuCrashDump.h"
#endif
namespace gfx
@@ -150,12 +148,14 @@ static bool _hasAnySetBits(const T& val, size_t offset)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&val);
for (size_t i = offset; i < sizeof(val); i++)
- if (ptr[i]) return true;
+ if (ptr[i])
+ return true;
return false;
}
Result DeviceImpl::initVulkanInstanceAndDevice(
- const InteropHandle* handles, bool useValidationLayer)
+ const InteropHandle* handles,
+ bool useValidationLayer)
{
m_features.clear();
@@ -171,7 +171,9 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
switch (stype)
{
case StructType::RayTracingValidationDesc:
- enableRayTracingValidation = static_cast<RayTracingValidationDesc*>(m_desc.extendedDescs[i])->enableRaytracingValidation;
+ enableRayTracingValidation =
+ static_cast<RayTracingValidationDesc*>(m_desc.extendedDescs[i])
+ ->enableRaytracingValidation;
break;
}
}
@@ -180,7 +182,7 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
VkInstance instance = VK_NULL_HANDLE;
if (handles[0].handleValue == 0)
{
- VkApplicationInfo applicationInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
+ VkApplicationInfo applicationInfo = {VK_STRUCTURE_TYPE_APPLICATION_INFO};
applicationInfo.pApplicationName = "slang-gfx";
applicationInfo.pEngineName = "slang-gfx";
applicationInfo.apiVersion = VK_API_VERSION_1_1;
@@ -215,7 +217,7 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
if (ENABLE_VALIDATION_LAYER || isGfxDebugLayerEnabled())
instanceExtensions.add(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
- VkInstanceCreateInfo instanceCreateInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
+ VkInstanceCreateInfo instanceCreateInfo = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
#if SLANG_APPLE_FAMILY
instanceCreateInfo.flags = VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
#endif
@@ -223,10 +225,11 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
instanceCreateInfo.enabledExtensionCount = (uint32_t)instanceExtensions.getCount();
instanceCreateInfo.ppEnabledExtensionNames = &instanceExtensions[0];
- const char* layerNames[] = { nullptr };
+ const char* layerNames[] = {nullptr};
VkValidationFeaturesEXT validationFeatures = {};
- VkValidationFeatureEnableEXT enabledValidationFeatures[1] = { VK_VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT };
+ VkValidationFeatureEnableEXT enabledValidationFeatures[1] = {
+ VK_VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT};
if (useValidationLayer)
{
// Depending on driver version, validation layer may or may not exist.
@@ -245,9 +248,9 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
for (auto& layer : availableLayers)
{
if (strncmp(
- layer.layerName,
- "VK_LAYER_KHRONOS_validation",
- sizeof("VK_LAYER_KHRONOS_validation")) == 0)
+ layer.layerName,
+ "VK_LAYER_KHRONOS_validation",
+ sizeof("VK_LAYER_KHRONOS_validation")) == 0)
{
layerNames[0] = "VK_LAYER_KHRONOS_validation";
break;
@@ -260,9 +263,9 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
for (auto& layer : availableLayers)
{
if (strncmp(
- layer.layerName,
- "VK_LAYER_LUNARG_standard_validation",
- sizeof("VK_LAYER_LUNARG_standard_validation")) == 0)
+ layer.layerName,
+ "VK_LAYER_LUNARG_standard_validation",
+ sizeof("VK_LAYER_LUNARG_standard_validation")) == 0)
{
layerNames[0] = "VK_LAYER_LUNARG_standard_validation";
break;
@@ -281,7 +284,7 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
instanceCreateInfo.pNext = &validationFeatures;
}
}
- uint32_t apiVersionsToTry[] = { VK_API_VERSION_1_2, VK_API_VERSION_1_1, VK_API_VERSION_1_0 };
+ uint32_t apiVersionsToTry[] = {VK_API_VERSION_1_2, VK_API_VERSION_1_1, VK_API_VERSION_1_0};
for (auto apiVersion : apiVersionsToTry)
{
applicationInfo.apiVersion = apiVersion;
@@ -290,7 +293,7 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
// the layer is known earlier). It might, for example, be absent
// from the system library search path, and not referenced with an
// absolute path in VkLayer_khronos_validation.json.
- const auto r = m_api.vkCreateInstance(&instanceCreateInfo, nullptr, &instance) ;
+ const auto r = m_api.vkCreateInstance(&instanceCreateInfo, nullptr, &instance);
if (r == VK_SUCCESS)
{
break;
@@ -311,13 +314,16 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
VkDebugReportCallbackCreateInfoEXT debugCreateInfo = {
- VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT };
+ VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT};
debugCreateInfo.pfnCallback = &debugMessageCallback;
debugCreateInfo.pUserData = this;
debugCreateInfo.flags = debugFlags;
SLANG_VK_RETURN_ON_FAIL(m_api.vkCreateDebugReportCallbackEXT(
- instance, &debugCreateInfo, nullptr, &m_debugReportCallback));
+ instance,
+ &debugCreateInfo,
+ nullptr,
+ &m_debugReportCallback));
}
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
@@ -330,7 +336,9 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
List<VkPhysicalDevice> physicalDevices;
physicalDevices.setCount(numPhysicalDevices);
SLANG_VK_RETURN_ON_FAIL(m_api.vkEnumeratePhysicalDevices(
- instance, &numPhysicalDevices, physicalDevices.getBuffer()));
+ instance,
+ &numPhysicalDevices,
+ physicalDevices.getBuffer()));
// Use first physical device by default.
Index selectedDeviceIndex = 0;
@@ -373,12 +381,14 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
// Query the available extensions
uint32_t extensionCount = 0;
- m_api.vkEnumerateDeviceExtensionProperties(
- m_api.m_physicalDevice, NULL, &extensionCount, NULL);
+ m_api.vkEnumerateDeviceExtensionProperties(m_api.m_physicalDevice, NULL, &extensionCount, NULL);
Slang::List<VkExtensionProperties> extensions;
extensions.setCount(extensionCount);
m_api.vkEnumerateDeviceExtensionProperties(
- m_api.m_physicalDevice, NULL, &extensionCount, extensions.getBuffer());
+ m_api.m_physicalDevice,
+ NULL,
+ &extensionCount,
+ extensions.getBuffer());
HashSet<String> extensionNames;
for (const auto& e : extensions)
extensionNames.add(e.extensionName);
@@ -390,7 +400,7 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
deviceExtensions.add("VK_KHR_portability_subset");
#endif
- VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
+ VkDeviceCreateInfo deviceCreateInfo = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pEnabledFeatures = &m_api.m_deviceFeatures;
@@ -480,7 +490,7 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
// Variable pointer features.
extendedFeatures.variablePointersFeatures.pNext = deviceFeatures2.pNext;
deviceFeatures2.pNext = &extendedFeatures.variablePointersFeatures;
-
+
// Compute shader derivative features.
extendedFeatures.computeShaderDerivativeFeatures.pNext = deviceFeatures2.pNext;
deviceFeatures2.pNext = &extendedFeatures.computeShaderDerivativeFeatures;
@@ -501,7 +511,7 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
extendedFeatures.clockFeatures.pNext = deviceFeatures2.pNext;
deviceFeatures2.pNext = &extendedFeatures.clockFeatures;
- // Atomic Float
+ // Atomic Float
// To detect atomic float we need
// https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkPhysicalDeviceShaderAtomicFloatFeaturesEXT.html
@@ -564,12 +574,14 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
m_features.add("half");
}
- const auto addFeatureExtension = [&](const bool feature, auto& featureStruct, const char* extension = nullptr){
- if(!feature)
+ const auto addFeatureExtension =
+ [&](const bool feature, auto& featureStruct, const char* extension = nullptr)
+ {
+ if (!feature)
return false;
- if(extension)
+ if (extension)
{
- if(!extensionNames.contains(extension))
+ if (!extensionNames.contains(extension))
return false;
deviceExtensions.add(extension);
}
@@ -585,51 +597,47 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
// linked into the deviceCreateInfo chain and the features added to the
// supported features list.
#define SIMPLE_EXTENSION_FEATURE(s, m, e, ...) \
- do{ \
- const static auto fs = {__VA_ARGS__}; \
- if(addFeatureExtension(s.m, s, e)) \
- for(const auto& p : fs) \
- m_features.add(p); \
- } while(0)
+ do \
+ { \
+ const static auto fs = {__VA_ARGS__}; \
+ if (addFeatureExtension(s.m, s, e)) \
+ for (const auto& p : fs) \
+ m_features.add(p); \
+ } while (0)
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.storage16BitFeatures,
storageBuffer16BitAccess,
VK_KHR_16BIT_STORAGE_EXTENSION_NAME,
- "16-bit-storage"
- );
+ "16-bit-storage");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.atomicFloatFeatures,
shaderBufferFloat32Atomics,
VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME,
- "atomic-float"
- );
+ "atomic-float");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.atomicFloat2Features,
shaderBufferFloat16Atomics,
VK_EXT_SHADER_ATOMIC_FLOAT_2_EXTENSION_NAME,
- "atomic-float-2"
- );
+ "atomic-float-2");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.imageInt64AtomicFeatures,
shaderImageInt64Atomics,
VK_EXT_SHADER_IMAGE_ATOMIC_INT64_EXTENSION_NAME,
- "image-atomic-int64"
- );
+ "image-atomic-int64");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.extendedDynamicStateFeatures,
extendedDynamicState,
VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME,
- "extended-dynamic-states"
- );
+ "extended-dynamic-states");
- if (extendedFeatures.accelerationStructureFeatures.accelerationStructure
- && extensionNames.contains(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME)
- && extensionNames.contains(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME))
+ if (extendedFeatures.accelerationStructureFeatures.accelerationStructure &&
+ extensionNames.contains(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME) &&
+ extensionNames.contains(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME))
{
extendedFeatures.accelerationStructureFeatures.pNext = (void*)deviceCreateInfo.pNext;
deviceCreateInfo.pNext = &extendedFeatures.accelerationStructureFeatures;
@@ -644,89 +652,78 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
rayQuery,
VK_KHR_RAY_QUERY_EXTENSION_NAME,
"ray-query",
- "ray-tracing"
- );
+ "ray-tracing");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.rayTracingPipelineFeatures,
rayTracingPipeline,
VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME,
- "ray-tracing-pipeline"
- );
+ "ray-tracing-pipeline");
}
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.inlineUniformBlockFeatures,
inlineUniformBlock,
VK_EXT_INLINE_UNIFORM_BLOCK_EXTENSION_NAME,
- "inline-uniform-block",
- );
+ "inline-uniform-block", );
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.robustness2Features,
nullDescriptor,
VK_EXT_ROBUSTNESS_2_EXTENSION_NAME,
- "robustness2",
- );
+ "robustness2", );
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.clockFeatures,
shaderDeviceClock,
VK_KHR_SHADER_CLOCK_EXTENSION_NAME,
- "realtime-clock"
- );
+ "realtime-clock");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.meshShaderFeatures,
meshShader,
VK_EXT_MESH_SHADER_EXTENSION_NAME,
- "mesh-shader"
- );
+ "mesh-shader");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.multiviewFeatures,
multiview,
VK_KHR_MULTIVIEW_EXTENSION_NAME,
- "multiview"
- );
+ "multiview");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.fragmentShadingRateFeatures,
primitiveFragmentShadingRate,
VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME,
- "fragment-shading-rate"
- );
+ "fragment-shading-rate");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.rayTracingInvocationReorderFeatures,
rayTracingInvocationReorder,
VK_NV_RAY_TRACING_INVOCATION_REORDER_EXTENSION_NAME,
- "shader-execution-reorder"
- );
+ "shader-execution-reorder");
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.variablePointersFeatures,
variablePointers,
VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME,
- "variable-pointer"
- );
-
+ "variable-pointer");
+
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.computeShaderDerivativeFeatures,
computeDerivativeGroupLinear,
VK_NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME,
- "computeDerivativeGroupLinear"
- );
+ "computeDerivativeGroupLinear");
// Only enable raytracing validation if both requested and supported
- if(enableRayTracingValidation && extendedFeatures.rayTracingValidationFeatures.rayTracingValidation)
+ if (enableRayTracingValidation &&
+ extendedFeatures.rayTracingValidationFeatures.rayTracingValidation)
{
SIMPLE_EXTENSION_FEATURE(
extendedFeatures.rayTracingValidationFeatures,
rayTracingValidation,
VK_NV_RAY_TRACING_VALIDATION_EXTENSION_NAME,
- "ray-tracing-validation"
- );
+ "ray-tracing-validation");
}
#undef SIMPLE_EXTENSION_FEATURE
@@ -752,11 +749,11 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
}
VkPhysicalDeviceProperties2 extendedProps = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
VkPhysicalDeviceRayTracingPipelinePropertiesKHR rtProps = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR};
VkPhysicalDeviceSubgroupProperties subgroupProps = {
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES };
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES};
rtProps.pNext = extendedProps.pNext;
extendedProps.pNext = &rtProps;
@@ -767,16 +764,12 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
m_api.m_rtProperties = rtProps;
// Approximate DX12's WaveOps boolean
- if(subgroupProps.supportedOperations &
- ( VK_SUBGROUP_FEATURE_BASIC_BIT
- | VK_SUBGROUP_FEATURE_VOTE_BIT
- | VK_SUBGROUP_FEATURE_ARITHMETIC_BIT
- | VK_SUBGROUP_FEATURE_BALLOT_BIT
- | VK_SUBGROUP_FEATURE_SHUFFLE_BIT
- | VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT
- | VK_SUBGROUP_FEATURE_CLUSTERED_BIT
- | VK_SUBGROUP_FEATURE_QUAD_BIT
- | VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV))
+ if (subgroupProps.supportedOperations &
+ (VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_VOTE_BIT |
+ VK_SUBGROUP_FEATURE_ARITHMETIC_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT |
+ VK_SUBGROUP_FEATURE_SHUFFLE_BIT | VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT |
+ VK_SUBGROUP_FEATURE_CLUSTERED_BIT | VK_SUBGROUP_FEATURE_QUAD_BIT |
+ VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV))
{
m_features.add("wave-ops");
}
@@ -860,13 +853,32 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
// Derive approximate DX12 shader model.
const char* featureTable[] = {
- "sm_6_0", "wave-ops", "atomic-int64", nullptr,
- "sm_6_1", "barycentrics", "multiview", nullptr,
- "sm_6_2", "half", nullptr,
- "sm_6_3", "ray-tracing-pipeline", nullptr,
- "sm_6_4", "fragment-shading-rate", nullptr,
- "sm_6_5", "ray-query", "mesh-shader", nullptr,
- "sm_6_6", "wave-ops", "atomic-float", "atomic-int64", nullptr,
+ "sm_6_0",
+ "wave-ops",
+ "atomic-int64",
+ nullptr,
+ "sm_6_1",
+ "barycentrics",
+ "multiview",
+ nullptr,
+ "sm_6_2",
+ "half",
+ nullptr,
+ "sm_6_3",
+ "ray-tracing-pipeline",
+ nullptr,
+ "sm_6_4",
+ "fragment-shading-rate",
+ nullptr,
+ "sm_6_5",
+ "ray-query",
+ "mesh-shader",
+ nullptr,
+ "sm_6_6",
+ "wave-ops",
+ "atomic-float",
+ "atomic-int64",
+ nullptr,
nullptr,
};
@@ -924,11 +936,17 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
// Set up device creation info for Aftermath feature flag configuration.
VkDeviceDiagnosticsConfigFlagsNV aftermathFlags =
- VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV | // Enable automatic call stack checkpoints.
- VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV | // Enable tracking of resources.
- VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV; // Generate debug information for shaders.
- // Not available on the version of Vulkan currently building with.
- //VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_ERROR_REPORTING_BIT_NV; // Enable additional runtime shader error reporting.
+ VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV | // Enable automatic
+ // call stack
+ // checkpoints.
+ VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV | // Enable tracking of
+ // resources.
+ VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV; // Generate debug
+ // information for
+ // shaders.
+ // Not available on the version of Vulkan currently building with.
+ // VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_ERROR_REPORTING_BIT_NV; // Enable additional
+ // runtime shader error reporting.
aftermathInfo.sType = VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV;
aftermathInfo.flags = aftermathFlags;
@@ -941,7 +959,7 @@ Result DeviceImpl::initVulkanInstanceAndDevice(
if (handles[2].handleValue == 0)
{
float queuePriority = 0.0f;
- VkDeviceQueueCreateInfo queueCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
+ VkDeviceQueueCreateInfo queueCreateInfo = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
queueCreateInfo.queueFamilyIndex = m_queueFamilyIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
@@ -978,7 +996,7 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
m_info.bindingStyle = BindingStyle::Vulkan;
m_info.projectionStyle = ProjectionStyle::Vulkan;
m_info.deviceType = DeviceType::Vulkan;
- static const float kIdentity[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
+ static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
::memcpy(m_info.identityProjectionMatrix, kIdentity, sizeof(kIdentity));
}
@@ -997,7 +1015,8 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
continue;
descriptorSetAllocator.m_api = &m_api;
initDeviceResult = initVulkanInstanceAndDevice(
- desc.existingDeviceHandles.handles, ENABLE_VALIDATION_LAYER != 0 || isGfxDebugLayerEnabled());
+ desc.existingDeviceHandles.handles,
+ ENABLE_VALIDATION_LAYER != 0 || isGfxDebugLayerEnabled());
if (initDeviceResult == SLANG_OK)
break;
}
@@ -1015,11 +1034,11 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
desc.extendedDescs,
SLANG_SPIRV,
"sm_5_1",
- makeArray(slang::PreprocessorMacroDesc{ "__VK__", "1" }).getView()));
+ makeArray(slang::PreprocessorMacroDesc{"__VK__", "1"}).getView()));
// Create default sampler.
{
- VkSamplerCreateInfo samplerInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
+ VkSamplerCreateInfo samplerInfo = {VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
samplerInfo.magFilter = VK_FILTER_NEAREST;
samplerInfo.minFilter = VK_FILTER_NEAREST;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
@@ -1056,12 +1075,19 @@ SlangResult DeviceImpl::initialize(const Desc& desc)
return SLANG_OK;
}
-void DeviceImpl::waitForGpu() { m_deviceQueue.flushAndWait(); }
+void DeviceImpl::waitForGpu()
+{
+ m_deviceQueue.flushAndWait();
+}
-SLANG_NO_THROW const DeviceInfo& SLANG_MCALL DeviceImpl::getDeviceInfo() const { return m_info; }
+SLANG_NO_THROW const DeviceInfo& SLANG_MCALL DeviceImpl::getDeviceInfo() const
+{
+ return m_info;
+}
Result DeviceImpl::createTransientResourceHeap(
- const ITransientResourceHeap::Desc& desc, ITransientResourceHeap** outHeap)
+ const ITransientResourceHeap::Desc& desc,
+ ITransientResourceHeap** outHeap)
{
RefPtr<TransientResourceHeapImpl> result = new TransientResourceHeapImpl();
SLANG_RETURN_ON_FAIL(result->init(desc, this));
@@ -1085,7 +1111,9 @@ Result DeviceImpl::createCommandQueue(const ICommandQueue::Desc& desc, ICommandQ
}
Result DeviceImpl::createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain)
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain)
{
#if !defined(SLANG_ENABLE_XLIB)
if (window.type == WindowHandle::Type::XLibHandle)
@@ -1101,7 +1129,8 @@ Result DeviceImpl::createSwapchain(
}
Result DeviceImpl::createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout)
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout)
{
RefPtr<FramebufferLayoutImpl> layout = new FramebufferLayoutImpl();
SLANG_RETURN_ON_FAIL(layout->init(this, desc));
@@ -1110,7 +1139,8 @@ Result DeviceImpl::createFramebufferLayout(
}
Result DeviceImpl::createRenderPassLayout(
- const IRenderPassLayout::Desc& desc, IRenderPassLayout** outRenderPassLayout)
+ const IRenderPassLayout::Desc& desc,
+ IRenderPassLayout** outRenderPassLayout)
{
RefPtr<RenderPassLayoutImpl> result = new RenderPassLayoutImpl();
SLANG_RETURN_ON_FAIL(result->init(this, desc));
@@ -1196,16 +1226,24 @@ SlangResult DeviceImpl::readTextureResource(
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
- region.imageSubresource.aspectMask = getAspectMaskFromFormat(VulkanUtil::getVkFormat(desc->format));
+ region.imageSubresource.aspectMask =
+ getAspectMaskFromFormat(VulkanUtil::getVkFormat(desc->format));
region.imageSubresource.mipLevel = uint32_t(j);
region.imageSubresource.baseArrayLayer = i;
region.imageSubresource.layerCount = 1;
- region.imageOffset = { 0, 0, 0 };
+ region.imageOffset = {0, 0, 0};
region.imageExtent = {
- uint32_t(mipSize.width), uint32_t(mipSize.height), uint32_t(mipSize.depth) };
+ uint32_t(mipSize.width),
+ uint32_t(mipSize.height),
+ uint32_t(mipSize.depth)};
m_api.vkCmdCopyImageToBuffer(
- commandBuffer, srcImage, srcImageLayout, staging.m_buffer, 1, &region);
+ commandBuffer,
+ srcImage,
+ srcImageLayout,
+ staging.m_buffer,
+ 1,
+ &region);
dstOffset += rowSizeInBytes * numRows * mipSize.depth;
}
@@ -1231,7 +1269,10 @@ SlangResult DeviceImpl::readTextureResource(
}
SlangResult DeviceImpl::readBufferResource(
- IBufferResource* inBuffer, Offset offset, Size size, ISlangBlob** outBlob)
+ IBufferResource* inBuffer,
+ Offset offset,
+ Size size,
+ ISlangBlob** outBlob)
{
BufferResourceImpl* buffer = static_cast<BufferResourceImpl*>(inBuffer);
@@ -1280,7 +1321,7 @@ Result DeviceImpl::getAccelerationStructurePrebuildInfo(
return SLANG_E_NOT_AVAILABLE;
}
VkAccelerationStructureBuildSizesInfoKHR sizeInfo = {
- VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR };
+ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR};
AccelerationStructureBuildGeometryInfoBuilder geomInfoBuilder;
SLANG_RETURN_ON_FAIL(geomInfoBuilder.build(buildInputs, getDebugCallback()));
m_api.vkGetAccelerationStructureBuildSizesKHR(
@@ -1296,7 +1337,8 @@ Result DeviceImpl::getAccelerationStructurePrebuildInfo(
}
Result DeviceImpl::createAccelerationStructure(
- const IAccelerationStructure::CreateDesc& desc, IAccelerationStructure** outAS)
+ const IAccelerationStructure::CreateDesc& desc,
+ IAccelerationStructure** outAS)
{
if (!m_api.vkCreateAccelerationStructureKHR)
{
@@ -1309,7 +1351,7 @@ Result DeviceImpl::createAccelerationStructure(
resultAS->m_device = this;
resultAS->m_desc.type = IResourceView::Type::AccelerationStructure;
VkAccelerationStructureCreateInfoKHR createInfo = {
- VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR };
+ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR};
createInfo.buffer = resultAS->m_buffer->m_buffer.m_buffer;
createInfo.offset = desc.offset;
createInfo.size = desc.size;
@@ -1330,7 +1372,10 @@ Result DeviceImpl::createAccelerationStructure(
}
SLANG_VK_RETURN_ON_FAIL(m_api.vkCreateAccelerationStructureKHR(
- m_api.m_device, &createInfo, nullptr, &resultAS->m_vkHandle));
+ m_api.m_device,
+ &createInfo,
+ nullptr,
+ &resultAS->m_vkHandle));
returnComPtr(outAS, resultAS);
return SLANG_OK;
}
@@ -1367,7 +1412,16 @@ void DeviceImpl::_transitionImageLayout(
VkPipelineStageFlags destinationStage = calcPipelineStageFlagsFromImageLayout(newLayout);
m_api.vkCmdPipelineBarrier(
- commandBuffer, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier);
+ commandBuffer,
+ sourceStage,
+ destinationStage,
+ 0,
+ 0,
+ nullptr,
+ 0,
+ nullptr,
+ 1,
+ &barrier);
}
uint32_t DeviceImpl::getQueueFamilyIndex(ICommandQueue::QueueType queueType)
@@ -1375,8 +1429,7 @@ uint32_t DeviceImpl::getQueueFamilyIndex(ICommandQueue::QueueType queueType)
switch (queueType)
{
case ICommandQueue::QueueType::Graphics:
- default:
- return m_queueFamilyIndex;
+ default: return m_queueFamilyIndex;
}
}
@@ -1392,7 +1445,9 @@ void DeviceImpl::_transitionImageLayout(
}
Result DeviceImpl::getTextureAllocationInfo(
- const ITextureResource::Desc& descIn, Size* outSize, Size* outAlignment)
+ const ITextureResource::Desc& descIn,
+ Size* outSize,
+ Size* outAlignment)
{
TextureResource::Desc desc = fixupTextureDesc(descIn);
@@ -1404,47 +1459,47 @@ Result DeviceImpl::getTextureAllocationInfo(
}
const int arraySize = calcEffectiveArraySize(desc);
- VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
+ VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
switch (desc.type)
{
case IResource::Type::Texture1D:
- {
- imageInfo.imageType = VK_IMAGE_TYPE_1D;
- imageInfo.extent = VkExtent3D{ uint32_t(descIn.size.width), 1, 1 };
- break;
- }
+ {
+ imageInfo.imageType = VK_IMAGE_TYPE_1D;
+ imageInfo.extent = VkExtent3D{uint32_t(descIn.size.width), 1, 1};
+ break;
+ }
case IResource::Type::Texture2D:
- {
- imageInfo.imageType = VK_IMAGE_TYPE_2D;
- imageInfo.extent =
- VkExtent3D{ uint32_t(descIn.size.width), uint32_t(descIn.size.height), 1 };
- break;
- }
+ {
+ imageInfo.imageType = VK_IMAGE_TYPE_2D;
+ imageInfo.extent =
+ VkExtent3D{uint32_t(descIn.size.width), uint32_t(descIn.size.height), 1};
+ break;
+ }
case IResource::Type::TextureCube:
- {
- imageInfo.imageType = VK_IMAGE_TYPE_2D;
- imageInfo.extent =
- VkExtent3D{ uint32_t(descIn.size.width), uint32_t(descIn.size.height), 1 };
- imageInfo.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
- break;
- }
+ {
+ imageInfo.imageType = VK_IMAGE_TYPE_2D;
+ imageInfo.extent =
+ VkExtent3D{uint32_t(descIn.size.width), uint32_t(descIn.size.height), 1};
+ imageInfo.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
+ break;
+ }
case IResource::Type::Texture3D:
- {
- // Can't have an array and 3d texture
- assert(desc.arraySize <= 1);
-
- imageInfo.imageType = VK_IMAGE_TYPE_3D;
- imageInfo.extent = VkExtent3D{
- uint32_t(descIn.size.width),
- uint32_t(descIn.size.height),
- uint32_t(descIn.size.depth) };
- break;
- }
+ {
+ // Can't have an array and 3d texture
+ assert(desc.arraySize <= 1);
+
+ imageInfo.imageType = VK_IMAGE_TYPE_3D;
+ imageInfo.extent = VkExtent3D{
+ uint32_t(descIn.size.width),
+ uint32_t(descIn.size.height),
+ uint32_t(descIn.size.depth)};
+ break;
+ }
default:
- {
- assert(!"Unhandled type");
- return SLANG_FAIL;
- }
+ {
+ assert(!"Unhandled type");
+ return SLANG_FAIL;
+ }
}
imageInfo.mipLevels = desc.numMipLevels;
@@ -1497,47 +1552,47 @@ Result DeviceImpl::createTextureResource(
texture->m_vkformat = format;
// Create the image
- VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
+ VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
switch (desc.type)
{
case IResource::Type::Texture1D:
- {
- imageInfo.imageType = VK_IMAGE_TYPE_1D;
- imageInfo.extent = VkExtent3D{ uint32_t(descIn.size.width), 1, 1 };
- break;
- }
+ {
+ imageInfo.imageType = VK_IMAGE_TYPE_1D;
+ imageInfo.extent = VkExtent3D{uint32_t(descIn.size.width), 1, 1};
+ break;
+ }
case IResource::Type::Texture2D:
- {
- imageInfo.imageType = VK_IMAGE_TYPE_2D;
- imageInfo.extent =
- VkExtent3D{ uint32_t(descIn.size.width), uint32_t(descIn.size.height), 1 };
- break;
- }
+ {
+ imageInfo.imageType = VK_IMAGE_TYPE_2D;
+ imageInfo.extent =
+ VkExtent3D{uint32_t(descIn.size.width), uint32_t(descIn.size.height), 1};
+ break;
+ }
case IResource::Type::TextureCube:
- {
- imageInfo.imageType = VK_IMAGE_TYPE_2D;
- imageInfo.extent =
- VkExtent3D{ uint32_t(descIn.size.width), uint32_t(descIn.size.height), 1 };
- imageInfo.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
- break;
- }
+ {
+ imageInfo.imageType = VK_IMAGE_TYPE_2D;
+ imageInfo.extent =
+ VkExtent3D{uint32_t(descIn.size.width), uint32_t(descIn.size.height), 1};
+ imageInfo.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
+ break;
+ }
case IResource::Type::Texture3D:
- {
- // Can't have an array and 3d texture
- assert(desc.arraySize <= 1);
-
- imageInfo.imageType = VK_IMAGE_TYPE_3D;
- imageInfo.extent = VkExtent3D{
- uint32_t(descIn.size.width),
- uint32_t(descIn.size.height),
- uint32_t(descIn.size.depth) };
- break;
- }
+ {
+ // Can't have an array and 3d texture
+ assert(desc.arraySize <= 1);
+
+ imageInfo.imageType = VK_IMAGE_TYPE_3D;
+ imageInfo.extent = VkExtent3D{
+ uint32_t(descIn.size.width),
+ uint32_t(descIn.size.height),
+ uint32_t(descIn.size.depth)};
+ break;
+ }
default:
- {
- assert(!"Unhandled type");
- return SLANG_FAIL;
- }
+ {
+ assert(!"Unhandled type");
+ return SLANG_FAIL;
+ }
}
imageInfo.mipLevels = desc.numMipLevels;
@@ -1552,7 +1607,7 @@ Result DeviceImpl::createTextureResource(
imageInfo.samples = (VkSampleCountFlagBits)desc.sampleDesc.numSamples;
VkExternalMemoryImageCreateInfo externalMemoryImageCreateInfo = {
- VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO };
+ VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO};
VkExternalMemoryHandleTypeFlags extMemoryHandleType =
#if SLANG_WINDOWS_FAMILY
VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT;
@@ -1578,15 +1633,15 @@ Result DeviceImpl::createTextureResource(
VkMemoryPropertyFlags actualMemoryProperites =
m_api.m_deviceMemoryProperties.memoryTypes[memoryTypeIndex].propertyFlags;
- VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
+ VkMemoryAllocateInfo allocInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = memoryTypeIndex;
#if SLANG_WINDOWS_FAMILY
VkExportMemoryWin32HandleInfoKHR exportMemoryWin32HandleInfo = {
- VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR };
+ VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR};
#endif
VkExportMemoryAllocateInfoKHR exportMemoryAllocateInfo = {
- VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR };
+ VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR};
if (descIn.isShared)
{
#if SLANG_WINDOWS_FAMILY
@@ -1598,8 +1653,8 @@ Result DeviceImpl::createTextureResource(
exportMemoryAllocateInfo.pNext =
extMemoryHandleType & VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR
- ? &exportMemoryWin32HandleInfo
- : nullptr;
+ ? &exportMemoryWin32HandleInfo
+ : nullptr;
#endif
exportMemoryAllocateInfo.handleTypes = extMemoryHandleType;
allocInfo.pNext = &exportMemoryAllocateInfo;
@@ -1705,7 +1760,7 @@ Result DeviceImpl::createTextureResource(
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
- if(desc.sampleDesc.numSamples != 1)
+ if (desc.sampleDesc.numSamples != 1)
{
// Handle senario where texture is sampled. We cannot use
// a simple buffer copy for sampled textures. ClearColorImage
@@ -1714,70 +1769,81 @@ Result DeviceImpl::createTextureResource(
gfxGetFormatInfo(desc.format, &formatInfo);
uint32_t data = 0;
VkClearColorValue clearColor;
- switch(formatInfo.channelType)
+ switch (formatInfo.channelType)
{
case SLANG_SCALAR_TYPE_INT32:
- for(int i = 0; i < 4; i++)
- clearColor.int32[i] = *reinterpret_cast<int32_t*>(const_cast<void*>(initData->data));
+ for (int i = 0; i < 4; i++)
+ clearColor.int32[i] =
+ *reinterpret_cast<int32_t*>(const_cast<void*>(initData->data));
break;
case SLANG_SCALAR_TYPE_UINT32:
- for(int i = 0; i < 4; i++)
- clearColor.uint32[i] = *reinterpret_cast<uint32_t*>(const_cast<void*>(initData->data));
+ for (int i = 0; i < 4; i++)
+ clearColor.uint32[i] =
+ *reinterpret_cast<uint32_t*>(const_cast<void*>(initData->data));
break;
case SLANG_SCALAR_TYPE_INT64:
- {
- for(int i = 0; i < 4; i++)
- clearColor.int32[i] = int32_t(*reinterpret_cast<int64_t*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.int32[i] =
+ int32_t(*reinterpret_cast<int64_t*>(const_cast<void*>(initData->data)));
+ break;
+ }
case SLANG_SCALAR_TYPE_UINT64:
- {
- for(int i = 0; i < 4; i++)
- clearColor.uint32[i] = uint32_t(*reinterpret_cast<uint64_t*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.uint32[i] = uint32_t(
+ *reinterpret_cast<uint64_t*>(const_cast<void*>(initData->data)));
+ break;
+ }
case SLANG_SCALAR_TYPE_FLOAT16:
- {
- for(int i = 0; i < 4; i++)
- clearColor.float32[i] = HalfToFloat(*reinterpret_cast<uint16_t*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.float32[i] = HalfToFloat(
+ *reinterpret_cast<uint16_t*>(const_cast<void*>(initData->data)));
+ break;
+ }
case SLANG_SCALAR_TYPE_FLOAT32:
- {
- for(int i = 0; i < 4; i++)
- clearColor.float32[i] = (*reinterpret_cast<float*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.float32[i] =
+ (*reinterpret_cast<float*>(const_cast<void*>(initData->data)));
+ break;
+ }
case SLANG_SCALAR_TYPE_FLOAT64:
- {
- for(int i = 0; i < 4; i++)
- clearColor.float32[i] = float(*reinterpret_cast<double*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.float32[i] =
+ float(*reinterpret_cast<double*>(const_cast<void*>(initData->data)));
+ break;
+ }
case SLANG_SCALAR_TYPE_INT8:
- {
- for(int i = 0; i < 4; i++)
- clearColor.int32[i] = int32_t(*reinterpret_cast<int8_t*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.int32[i] =
+ int32_t(*reinterpret_cast<int8_t*>(const_cast<void*>(initData->data)));
+ break;
+ }
case SLANG_SCALAR_TYPE_UINT8:
- {
- for(int i = 0; i < 4; i++)
- clearColor.uint32[i] = uint32_t(*reinterpret_cast<uint8_t*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.uint32[i] = uint32_t(
+ *reinterpret_cast<uint8_t*>(const_cast<void*>(initData->data)));
+ break;
+ }
case SLANG_SCALAR_TYPE_INT16:
- {
- for(int i = 0; i < 4; i++)
- clearColor.int32[i] = int32_t(*reinterpret_cast<int16_t*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.int32[i] =
+ int32_t(*reinterpret_cast<int16_t*>(const_cast<void*>(initData->data)));
+ break;
+ }
case SLANG_SCALAR_TYPE_UINT16:
- {
- for(int i = 0; i < 4; i++)
- clearColor.uint32[i] = uint32_t(*reinterpret_cast<uint16_t*>(const_cast<void*>(initData->data)));
- break;
- }
+ {
+ for (int i = 0; i < 4; i++)
+ clearColor.uint32[i] = uint32_t(
+ *reinterpret_cast<uint16_t*>(const_cast<void*>(initData->data)));
+ break;
+ }
};
VkImageSubresourceRange range{};
@@ -1824,9 +1890,11 @@ Result DeviceImpl::createTextureResource(
region.imageSubresource.mipLevel = uint32_t(j);
region.imageSubresource.baseArrayLayer = i;
region.imageSubresource.layerCount = 1;
- region.imageOffset = { 0, 0, 0 };
+ region.imageOffset = {0, 0, 0};
region.imageExtent = {
- uint32_t(mipSize.width), uint32_t(mipSize.height), uint32_t(mipSize.depth) };
+ uint32_t(mipSize.width),
+ uint32_t(mipSize.height),
+ uint32_t(mipSize.depth)};
// Do the copy (do all depths in a single go)
m_api.vkCmdCopyBufferToImage(
@@ -1869,7 +1937,9 @@ Result DeviceImpl::createTextureResource(
}
Result DeviceImpl::createBufferResource(
- const IBufferResource::Desc& descIn, const void* initData, IBufferResource** outResource)
+ const IBufferResource::Desc& descIn,
+ const void* initData,
+ IBufferResource** outResource)
{
return createBufferResourceImpl(descIn, 0, initData, outResource);
}
@@ -1947,7 +2017,12 @@ Result DeviceImpl::createBufferResourceImpl(
// Copy into staging buffer
void* mappedData = nullptr;
SLANG_VK_CHECK(m_api.vkMapMemory(
- m_device, buffer->m_uploadBuffer.m_memory, 0, bufferSize, 0, &mappedData));
+ m_device,
+ buffer->m_uploadBuffer.m_memory,
+ 0,
+ bufferSize,
+ 0,
+ &mappedData));
::memcpy(mappedData, initData, bufferSize);
m_api.vkUnmapMemory(m_device, buffer->m_uploadBuffer.m_memory);
@@ -1969,7 +2044,12 @@ Result DeviceImpl::createBufferResourceImpl(
// Copy into mapped buffer directly
void* mappedData = nullptr;
SLANG_VK_CHECK(m_api.vkMapMemory(
- m_device, buffer->m_buffer.m_memory, 0, bufferSize, 0, &mappedData));
+ m_device,
+ buffer->m_buffer.m_memory,
+ 0,
+ bufferSize,
+ 0,
+ &mappedData));
::memcpy(mappedData, initData, bufferSize);
m_api.vkUnmapMemory(m_device, buffer->m_buffer.m_memory);
}
@@ -1980,7 +2060,9 @@ Result DeviceImpl::createBufferResourceImpl(
}
Result DeviceImpl::createBufferFromNativeHandle(
- InteropHandle handle, const IBufferResource::Desc& srcDesc, IBufferResource** outResource)
+ InteropHandle handle,
+ const IBufferResource::Desc& srcDesc,
+ IBufferResource** outResource)
{
RefPtr<BufferResourceImpl> buffer(new BufferResourceImpl(srcDesc, this));
@@ -1999,7 +2081,7 @@ Result DeviceImpl::createBufferFromNativeHandle(
Result DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler)
{
- VkSamplerCreateInfo samplerInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
+ VkSamplerCreateInfo samplerInfo = {VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
samplerInfo.magFilter = VulkanUtil::translateFilterMode(desc.minFilter);
samplerInfo.minFilter = VulkanUtil::translateFilterMode(desc.magFilter);
@@ -2021,7 +2103,8 @@ Result DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerS
samplerInfo.minLod = Math::Max(0.0f, desc.minLOD);
samplerInfo.maxLod = Math::Clamp(desc.maxLOD, samplerInfo.minLod, VK_LOD_CLAMP_NONE);
- VkSamplerReductionModeCreateInfo reductionInfo = { VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO };
+ VkSamplerReductionModeCreateInfo reductionInfo = {
+ VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO};
reductionInfo.reductionMode = VulkanUtil::translateReductionOp(desc.reductionOp);
samplerInfo.pNext = &reductionInfo;
@@ -2035,7 +2118,9 @@ Result DeviceImpl::createSamplerState(ISamplerState::Desc const& desc, ISamplerS
}
Result DeviceImpl::createTextureView(
- ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView)
+ ITextureResource* texture,
+ IResourceView::Desc const& desc,
+ IResourceView** outView)
{
auto resourceImpl = static_cast<TextureResourceImpl*>(texture);
RefPtr<TextureResourceViewImpl> view = new TextureResourceViewImpl(this);
@@ -2053,14 +2138,14 @@ Result DeviceImpl::createTextureView(
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.flags = 0;
createInfo.format = gfxIsTypelessFormat(texture->getDesc()->format)
- ? VulkanUtil::getVkFormat(desc.format)
- : resourceImpl->m_vkformat;
+ ? VulkanUtil::getVkFormat(desc.format)
+ : resourceImpl->m_vkformat;
createInfo.image = resourceImpl->m_image;
createInfo.components = VkComponentMapping{
VK_COMPONENT_SWIZZLE_R,
VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B,
- VK_COMPONENT_SWIZZLE_A };
+ VK_COMPONENT_SWIZZLE_A};
switch (resourceImpl->getType())
{
case IResource::Type::Texture1D:
@@ -2069,15 +2154,11 @@ Result DeviceImpl::createTextureView(
case IResource::Type::Texture2D:
createInfo.viewType = isArray ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D;
break;
- case IResource::Type::Texture3D:
- createInfo.viewType = VK_IMAGE_VIEW_TYPE_3D;
- break;
+ case IResource::Type::Texture3D: createInfo.viewType = VK_IMAGE_VIEW_TYPE_3D; break;
case IResource::Type::TextureCube:
createInfo.viewType = isArray ? VK_IMAGE_VIEW_TYPE_CUBE_ARRAY : VK_IMAGE_VIEW_TYPE_CUBE;
break;
- default:
- SLANG_UNIMPLEMENTED_X("Unknown Texture type.");
- break;
+ default: SLANG_UNIMPLEMENTED_X("Unknown Texture type."); break;
}
createInfo.subresourceRange.aspectMask = getAspectMaskFromFormat(resourceImpl->m_vkformat);
@@ -2094,8 +2175,8 @@ Result DeviceImpl::createTextureView(
}
}
createInfo.subresourceRange.levelCount = desc.subresourceRange.mipLevelCount == 0
- ? VK_REMAINING_MIP_LEVELS
- : desc.subresourceRange.mipLevelCount;
+ ? VK_REMAINING_MIP_LEVELS
+ : desc.subresourceRange.mipLevelCount;
switch (desc.type)
{
case IResourceView::Type::DepthStencil:
@@ -2109,12 +2190,8 @@ Result DeviceImpl::createTextureView(
case IResourceView::Type::ShaderResource:
view->m_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
break;
- case IResourceView::Type::UnorderedAccess:
- view->m_layout = VK_IMAGE_LAYOUT_GENERAL;
- break;
- default:
- SLANG_UNIMPLEMENTED_X("Unknown TextureViewDesc type.");
- break;
+ case IResourceView::Type::UnorderedAccess: view->m_layout = VK_IMAGE_LAYOUT_GENERAL; break;
+ default: SLANG_UNIMPLEMENTED_X("Unknown TextureViewDesc type."); break;
}
m_api.vkCreateImageView(m_device, &createInfo, nullptr, &view->m_view);
returnComPtr(outView, view);
@@ -2129,7 +2206,9 @@ Result DeviceImpl::getFormatSupportedResourceStates(Format format, ResourceState
VkFormatProperties supportedProperties = {};
m_api.vkGetPhysicalDeviceFormatProperties(
- m_api.m_physicalDevice, vkFormat, &supportedProperties);
+ m_api.m_physicalDevice,
+ vkFormat,
+ &supportedProperties);
HashSet<VkFormat> presentableFormats;
// TODO: enable this once we have VK_GOOGLE_surfaceless_query.
@@ -2147,8 +2226,8 @@ Result DeviceImpl::getFormatSupportedResourceStates(Format format, ResourceState
presentableFormats.add(surfaceFormat.format);
}
#else
-// Until we have a solution to query presentable formats without needing a surface,
-// hard code presentable formats that is supported by most drivers.
+ // Until we have a solution to query presentable formats without needing a surface,
+ // hard code presentable formats that is supported by most drivers.
presentableFormats.add(VK_FORMAT_R8G8B8A8_UNORM);
presentableFormats.add(VK_FORMAT_B8G8R8A8_UNORM);
presentableFormats.add(VK_FORMAT_R8G8B8A8_SRGB);
@@ -2167,11 +2246,8 @@ Result DeviceImpl::getFormatSupportedResourceStates(Format format, ResourceState
switch (format)
{
case Format::R32_UINT:
- case Format::R16_UINT:
- allowedStates.add(ResourceState::IndexBuffer);
- break;
- default:
- break;
+ case Format::R16_UINT: allowedStates.add(ResourceState::IndexBuffer); break;
+ default: break;
}
// ConstantBuffer
allowedStates.add(ResourceState::ConstantBuffer);
@@ -2186,7 +2262,7 @@ Result DeviceImpl::getFormatSupportedResourceStates(Format format, ResourceState
(VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT))
allowedStates.add(ResourceState::UnorderedAccess);
if (bufferFeatures & (VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT |
- VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT))
+ VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT))
allowedStates.add(ResourceState::UnorderedAccess);
// RenderTarget
if (imageFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)
@@ -2235,8 +2311,8 @@ Result DeviceImpl::createBufferView(
VkDeviceSize offset = (VkDeviceSize)desc.bufferRange.offset;
VkDeviceSize size = desc.bufferRange.size == 0
- ? (buffer ? resourceImpl->getDesc()->sizeInBytes : 0)
- : (VkDeviceSize)desc.bufferRange.size;
+ ? (buffer ? resourceImpl->getDesc()->sizeInBytes : 0)
+ : (VkDeviceSize)desc.bufferRange.size;
// There are two different cases we need to think about for buffers.
//
@@ -2259,9 +2335,7 @@ Result DeviceImpl::createBufferView(
switch (desc.type)
{
- default:
- assert(!"unhandled");
- return SLANG_FAIL;
+ default: assert(!"unhandled"); return SLANG_FAIL;
case IResourceView::Type::UnorderedAccess:
case IResourceView::Type::ShaderResource:
@@ -2286,7 +2360,7 @@ Result DeviceImpl::createBufferView(
//
// FALLTHROUGH
{
- VkBufferViewCreateInfo info = { VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO };
+ VkBufferViewCreateInfo info = {VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO};
VkBufferView view = VK_NULL_HANDLE;
@@ -2352,8 +2426,8 @@ Result DeviceImpl::createInputLayout(IInputLayout::Desc const& desc, IInputLayou
dstStream.stride = (uint32_t)srcStream.stride;
dstStream.binding = (uint32_t)i;
dstStream.inputRate = (srcStream.slotClass == InputSlotClass::PerInstance)
- ? VK_VERTEX_INPUT_RATE_INSTANCE
- : VK_VERTEX_INPUT_RATE_VERTEX;
+ ? VK_VERTEX_INPUT_RATE_INSTANCE
+ : VK_VERTEX_INPUT_RATE_VERTEX;
}
for (Int i = 0; i < numElements; ++i)
@@ -2380,7 +2454,9 @@ Result DeviceImpl::createInputLayout(IInputLayout::Desc const& desc, IInputLayou
}
Result DeviceImpl::createProgram(
- const IShaderProgram::Desc& desc, IShaderProgram** outProgram, ISlangBlob** outDiagnosticBlob)
+ const IShaderProgram::Desc& desc,
+ IShaderProgram** outProgram,
+ ISlangBlob** outDiagnosticBlob)
{
RefPtr<ShaderProgramImpl> shaderProgram = new ShaderProgramImpl(this);
shaderProgram->init(desc);
@@ -2418,13 +2494,16 @@ Result DeviceImpl::createShaderObject(ShaderObjectLayoutBase* layout, IShaderObj
{
RefPtr<ShaderObjectImpl> shaderObject;
SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(
- this, static_cast<ShaderObjectLayoutImpl*>(layout), shaderObject.writeRef()));
+ this,
+ static_cast<ShaderObjectLayoutImpl*>(layout),
+ shaderObject.writeRef()));
returnComPtr(outObject, shaderObject);
return SLANG_OK;
}
Result DeviceImpl::createMutableShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject)
{
auto layoutImpl = static_cast<ShaderObjectLayoutImpl*>(layout);
@@ -2454,7 +2533,8 @@ Result DeviceImpl::createShaderTable(const IShaderTable::Desc& desc, IShaderTabl
}
Result DeviceImpl::createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& inDesc, IPipelineState** outState)
+ const GraphicsPipelineStateDesc& inDesc,
+ IPipelineState** outState)
{
GraphicsPipelineStateDesc desc = inDesc;
RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl(this);
@@ -2467,7 +2547,8 @@ Result DeviceImpl::createGraphicsPipelineState(
}
Result DeviceImpl::createComputePipelineState(
- const ComputePipelineStateDesc& inDesc, IPipelineState** outState)
+ const ComputePipelineStateDesc& inDesc,
+ IPipelineState** outState)
{
ComputePipelineStateDesc desc = inDesc;
RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl(this);
@@ -2479,7 +2560,8 @@ Result DeviceImpl::createComputePipelineState(
}
Result DeviceImpl::createRayTracingPipelineState(
- const RayTracingPipelineStateDesc& desc, IPipelineState** outState)
+ const RayTracingPipelineStateDesc& desc,
+ IPipelineState** outState)
{
RefPtr<RayTracingPipelineStateImpl> pipelineStateImpl = new RayTracingPipelineStateImpl(this);
pipelineStateImpl->init(desc);
@@ -2506,7 +2588,11 @@ Result DeviceImpl::createFence(const IFence::Desc& desc, IFence** outFence)
}
Result DeviceImpl::waitForFences(
- GfxCount fenceCount, IFence** fences, uint64_t* fenceValues, bool waitForAll, uint64_t timeout)
+ GfxCount fenceCount,
+ IFence** fences,
+ uint64_t* fenceValues,
+ bool waitForAll,
+ uint64_t timeout)
{
ShortList<VkSemaphore> semaphores;
for (GfxIndex i = 0; i < fenceCount; ++i)
diff --git a/tools/gfx/vulkan/vk-device.h b/tools/gfx/vulkan/vk-device.h
index 89c7aa103..3b6c83103 100644
--- a/tools/gfx/vulkan/vk-device.h
+++ b/tools/gfx/vulkan/vk-device.h
@@ -19,19 +19,24 @@ public:
Result initVulkanInstanceAndDevice(const InteropHandle* handles, bool useValidationLayer);
virtual SLANG_NO_THROW Result SLANG_MCALL initialize(const Desc& desc) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
+ getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTransientResourceHeap(
- const ITransientResourceHeap::Desc& desc, ITransientResourceHeap** outHeap) override;
+ const ITransientResourceHeap::Desc& desc,
+ ITransientResourceHeap** outHeap) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
+ createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createSwapchain(
- const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain) override;
+ const ISwapchain::Desc& desc,
+ WindowHandle window,
+ ISwapchain** outSwapchain) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createFramebufferLayout(
- const IFramebufferLayout::Desc& desc, IFramebufferLayout** outLayout) override;
+ const IFramebufferLayout::Desc& desc,
+ IFramebufferLayout** outLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
+ createFramebuffer(const IFramebuffer::Desc& desc, IFramebuffer** outFramebuffer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createRenderPassLayout(
- const IRenderPassLayout::Desc& desc, IRenderPassLayout** outRenderPassLayout) override;
+ const IRenderPassLayout::Desc& desc,
+ IRenderPassLayout** outRenderPassLayout) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureResource(
const ITextureResource::Desc& desc,
const ITextureResource::SubresourceData* initData,
@@ -50,7 +55,7 @@ public:
const IBufferResource::Desc& srcDesc,
IBufferResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
+ createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
ITextureResource* texture,
@@ -63,33 +68,37 @@ public:
IResourceView** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
+ createInputLayout(IInputLayout::Desc const& desc, IInputLayout** outLayout) override;
virtual Result createShaderObjectLayout(
slang::ISession* session,
slang::TypeLayoutReflection* typeLayout,
ShaderObjectLayoutBase** outLayout) override;
- virtual Result createShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
+ virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
+ override;
virtual Result createMutableShaderObject(
- ShaderObjectLayoutBase* layout, IShaderObject** outObject) override;
+ ShaderObjectLayoutBase* layout,
+ IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
+ createMutableRootShaderObject(IShaderProgram* program, IShaderObject** outObject) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outShaderTable) override;
+ createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outShaderTable) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createProgram(
const IShaderProgram::Desc& desc,
IShaderProgram** outProgram,
ISlangBlob** outDiagnosticBlob) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
- const GraphicsPipelineStateDesc& desc, IPipelineState** outState) override;
+ const GraphicsPipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
- const ComputePipelineStateDesc& desc, IPipelineState** outState) override;
+ const ComputePipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createRayTracingPipelineState(
- const RayTracingPipelineStateDesc& desc, IPipelineState** outState) override;
+ const RayTracingPipelineStateDesc& desc,
+ IPipelineState** outState) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool) override;
+ createQueryPool(const IQueryPool::Desc& desc, IQueryPool** outPool) override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL readTextureResource(
ITextureResource* texture,
@@ -99,22 +108,28 @@ public:
Size* outPixelSize) override;
virtual SLANG_NO_THROW SlangResult SLANG_MCALL readBufferResource(
- IBufferResource* buffer, Offset offset, Size size, ISlangBlob** outBlob) override;
+ IBufferResource* buffer,
+ Offset offset,
+ Size size,
+ ISlangBlob** outBlob) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getAccelerationStructurePrebuildInfo(
const IAccelerationStructure::BuildInputs& buildInputs,
IAccelerationStructure::PrebuildInfo* outPrebuildInfo) override;
virtual SLANG_NO_THROW Result SLANG_MCALL createAccelerationStructure(
- const IAccelerationStructure::CreateDesc& desc, IAccelerationStructure** outView) override;
+ const IAccelerationStructure::CreateDesc& desc,
+ IAccelerationStructure** outView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureAllocationInfo(
- const ITextureResource::Desc& desc, Size* outSize, Size* outAlignment) override;
+ const ITextureResource::Desc& desc,
+ Size* outSize,
+ Size* outAlignment) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getTextureRowAlignment(Size* outAlignment) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- createFence(const IFence::Desc& desc, IFence** outFence) override;
+ createFence(const IFence::Desc& desc, IFence** outFence) override;
virtual SLANG_NO_THROW Result SLANG_MCALL waitForFences(
GfxCount fenceCount,
@@ -128,7 +143,7 @@ public:
virtual SLANG_NO_THROW const DeviceInfo& SLANG_MCALL getDeviceInfo() const override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeDeviceHandles(InteropHandles* outHandles) override;
+ getNativeDeviceHandles(InteropHandles* outHandles) override;
~DeviceImpl();
@@ -146,7 +161,8 @@ public:
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objType,
uint64_t srcObject,
- Size location, // TODO: Is "location" still needed? Calls handleDebugMessage() which doesn't use it
+ Size location, // TODO: Is "location" still needed? Calls handleDebugMessage() which doesn't
+ // use it
int32_t msgCode,
const char* pLayerPrefix,
const char* pMsg,
diff --git a/tools/gfx/vulkan/vk-fence.cpp b/tools/gfx/vulkan/vk-fence.cpp
index d71847dcb..9ecbcb712 100644
--- a/tools/gfx/vulkan/vk-fence.cpp
+++ b/tools/gfx/vulkan/vk-fence.cpp
@@ -18,7 +18,8 @@ namespace vk
FenceImpl::FenceImpl(DeviceImpl* device)
: m_device(device)
-{}
+{
+}
FenceImpl::~FenceImpl()
{
@@ -51,11 +52,12 @@ Result FenceImpl::init(const IFence::Desc& desc)
if (desc.isShared)
{
#if SLANG_WINDOWS_FAMILY
- exportSemaphoreWin32HandleInfoKHR.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR;
+ exportSemaphoreWin32HandleInfoKHR.sType =
+ VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR;
exportSemaphoreWin32HandleInfoKHR.pNext = timelineCreateInfo.pNext;
exportSemaphoreWin32HandleInfoKHR.pAttributes = nullptr;
exportSemaphoreWin32HandleInfoKHR.dwAccess = GENERIC_ALL;
- exportSemaphoreWin32HandleInfoKHR.name = (LPCWSTR)nullptr;
+ exportSemaphoreWin32HandleInfoKHR.name = (LPCWSTR) nullptr;
#endif
exportSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR;
#if SLANG_WINDOWS_FAMILY
@@ -69,7 +71,10 @@ Result FenceImpl::init(const IFence::Desc& desc)
}
SLANG_VK_RETURN_ON_FAIL(m_device->m_api.vkCreateSemaphore(
- m_device->m_api.m_device, &createInfo, nullptr, &m_semaphore));
+ m_device->m_api.m_device,
+ &createInfo,
+ nullptr,
+ &m_semaphore));
return SLANG_OK;
}
@@ -77,7 +82,9 @@ Result FenceImpl::init(const IFence::Desc& desc)
Result FenceImpl::getCurrentValue(uint64_t* outValue)
{
SLANG_VK_RETURN_ON_FAIL(m_device->m_api.vkGetSemaphoreCounterValue(
- m_device->m_api.m_device, m_semaphore, outValue));
+ m_device->m_api.m_device,
+ m_semaphore,
+ outValue));
return SLANG_OK;
}
@@ -85,7 +92,9 @@ Result FenceImpl::setCurrentValue(uint64_t value)
{
uint64_t currentValue = 0;
SLANG_VK_RETURN_ON_FAIL(m_device->m_api.vkGetSemaphoreCounterValue(
- m_device->m_api.m_device, m_semaphore, &currentValue));
+ m_device->m_api.m_device,
+ m_semaphore,
+ &currentValue));
if (currentValue < value)
{
VkSemaphoreSignalInfo signalInfo;
@@ -117,16 +126,19 @@ Result FenceImpl::getSharedHandle(InteropHandle* outHandle)
handleInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT;
SLANG_VK_RETURN_ON_FAIL(m_device->m_api.vkGetSemaphoreWin32HandleKHR(
- m_device->m_api.m_device, &handleInfo, (HANDLE*)&sharedHandle.handleValue));
+ m_device->m_api.m_device,
+ &handleInfo,
+ (HANDLE*)&sharedHandle.handleValue));
#else
- VkSemaphoreGetFdInfoKHR fdInfo = {
- VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR};
+ VkSemaphoreGetFdInfoKHR fdInfo = {VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR};
fdInfo.pNext = nullptr;
fdInfo.semaphore = m_semaphore;
fdInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
SLANG_VK_RETURN_ON_FAIL(m_device->m_api.vkGetSemaphoreFdKHR(
- m_device->m_api.m_device, &fdInfo, (int*)&sharedHandle.handleValue));
+ m_device->m_api.m_device,
+ &fdInfo,
+ (int*)&sharedHandle.handleValue));
#endif
sharedHandle.api = InteropHandleAPI::Vulkan;
diff --git a/tools/gfx/vulkan/vk-fence.h b/tools/gfx/vulkan/vk-fence.h
index 46b0ebc2b..a70334ac2 100644
--- a/tools/gfx/vulkan/vk-fence.h
+++ b/tools/gfx/vulkan/vk-fence.h
@@ -30,7 +30,7 @@ public:
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeHandle(InteropHandle* outNativeHandle) override;
+ getNativeHandle(InteropHandle* outNativeHandle) override;
};
} // namespace vk
diff --git a/tools/gfx/vulkan/vk-framebuffer.cpp b/tools/gfx/vulkan/vk-framebuffer.cpp
index 7f91b0d19..3eef533fa 100644
--- a/tools/gfx/vulkan/vk-framebuffer.cpp
+++ b/tools/gfx/vulkan/vk-framebuffer.cpp
@@ -2,9 +2,8 @@
#include "vk-framebuffer.h"
#include "vk-device.h"
-#include "vk-resource-views.h"
-
#include "vk-helper-functions.h"
+#include "vk-resource-views.h"
namespace gfx
{
@@ -106,7 +105,10 @@ Result FramebufferLayoutImpl::init(DeviceImpl* renderer, const IFramebufferLayou
renderPassCreateInfo.subpassCount = 1;
renderPassCreateInfo.pSubpasses = &subpassDesc;
SLANG_VK_RETURN_ON_FAIL(m_renderer->m_api.vkCreateRenderPass(
- m_renderer->m_api.m_device, &renderPassCreateInfo, nullptr, &m_renderPass));
+ m_renderer->m_api.m_device,
+ &renderPassCreateInfo,
+ nullptr,
+ &m_renderPass));
return SLANG_OK;
}
@@ -142,7 +144,9 @@ Result FramebufferImpl::init(DeviceImpl* renderer, const IFramebuffer::Desc& des
auto size = resourceDesc->size;
m_width = getMipLevelSize(viewDesc->subresourceRange.mipLevel, size.width);
m_height = getMipLevelSize(viewDesc->subresourceRange.mipLevel, size.height);
- layerCount = (resourceDesc->type == IResource::Type::Texture3D) ? size.depth : viewDesc->subresourceRange.layerCount;
+ layerCount = (resourceDesc->type == IResource::Type::Texture3D)
+ ? size.depth
+ : viewDesc->subresourceRange.layerCount;
}
else
{
@@ -200,7 +204,10 @@ Result FramebufferImpl::init(DeviceImpl* renderer, const IFramebuffer::Desc& des
framebufferInfo.layers = layerCount;
SLANG_VK_RETURN_ON_FAIL(m_renderer->m_api.vkCreateFramebuffer(
- m_renderer->m_api.m_device, &framebufferInfo, nullptr, &m_handle));
+ m_renderer->m_api.m_device,
+ &framebufferInfo,
+ nullptr,
+ &m_handle));
return SLANG_OK;
}
diff --git a/tools/gfx/vulkan/vk-helper-functions.cpp b/tools/gfx/vulkan/vk-helper-functions.cpp
index 1f7c6b6ff..b7bbeec2b 100644
--- a/tools/gfx/vulkan/vk-helper-functions.cpp
+++ b/tools/gfx/vulkan/vk-helper-functions.cpp
@@ -31,12 +31,9 @@ VkAttachmentLoadOp translateLoadOp(IRenderPassLayout::TargetLoadOp loadOp)
{
switch (loadOp)
{
- case IRenderPassLayout::TargetLoadOp::Clear:
- return VK_ATTACHMENT_LOAD_OP_CLEAR;
- case IRenderPassLayout::TargetLoadOp::Load:
- return VK_ATTACHMENT_LOAD_OP_LOAD;
- default:
- return VK_ATTACHMENT_LOAD_OP_DONT_CARE;
+ case IRenderPassLayout::TargetLoadOp::Clear: return VK_ATTACHMENT_LOAD_OP_CLEAR;
+ case IRenderPassLayout::TargetLoadOp::Load: return VK_ATTACHMENT_LOAD_OP_LOAD;
+ default: return VK_ATTACHMENT_LOAD_OP_DONT_CARE;
}
}
@@ -44,10 +41,8 @@ VkAttachmentStoreOp translateStoreOp(IRenderPassLayout::TargetStoreOp storeOp)
{
switch (storeOp)
{
- case IRenderPassLayout::TargetStoreOp::Store:
- return VK_ATTACHMENT_STORE_OP_STORE;
- default:
- return VK_ATTACHMENT_STORE_OP_DONT_CARE;
+ case IRenderPassLayout::TargetStoreOp::Store: return VK_ATTACHMENT_STORE_OP_STORE;
+ default: return VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
}
@@ -71,33 +66,21 @@ VkImageLayout translateImageLayout(ResourceState state)
{
switch (state)
{
- case ResourceState::Undefined:
- return VK_IMAGE_LAYOUT_UNDEFINED;
- case ResourceState::PreInitialized:
- return VK_IMAGE_LAYOUT_PREINITIALIZED;
- case ResourceState::UnorderedAccess:
- return VK_IMAGE_LAYOUT_GENERAL;
- case ResourceState::RenderTarget:
- return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
- case ResourceState::DepthRead:
- return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
- case ResourceState::DepthWrite:
- return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
+ case ResourceState::Undefined: return VK_IMAGE_LAYOUT_UNDEFINED;
+ case ResourceState::PreInitialized: return VK_IMAGE_LAYOUT_PREINITIALIZED;
+ case ResourceState::UnorderedAccess: return VK_IMAGE_LAYOUT_GENERAL;
+ case ResourceState::RenderTarget: return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
+ case ResourceState::DepthRead: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
+ case ResourceState::DepthWrite: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
case ResourceState::ShaderResource:
case ResourceState::NonPixelShaderResource:
- case ResourceState::PixelShaderResource:
- return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
+ case ResourceState::PixelShaderResource: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
case ResourceState::ResolveDestination:
- case ResourceState::CopyDestination:
- return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+ case ResourceState::CopyDestination: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
case ResourceState::ResolveSource:
- case ResourceState::CopySource:
- return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
- case ResourceState::Present:
- return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
- default:
- assert(!"Unsupported");
- return VK_IMAGE_LAYOUT_UNDEFINED;
+ case ResourceState::CopySource: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
+ case ResourceState::Present: return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
+ default: assert(!"Unsupported"); return VK_IMAGE_LAYOUT_UNDEFINED;
}
}
@@ -107,37 +90,28 @@ VkAccessFlagBits calcAccessFlags(ResourceState state)
{
case ResourceState::Undefined:
case ResourceState::Present:
- case ResourceState::PreInitialized:
- return VkAccessFlagBits(0);
- case ResourceState::VertexBuffer:
- return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
- case ResourceState::ConstantBuffer:
- return VK_ACCESS_UNIFORM_READ_BIT;
- case ResourceState::IndexBuffer:
- return VK_ACCESS_INDEX_READ_BIT;
+ case ResourceState::PreInitialized: return VkAccessFlagBits(0);
+ case ResourceState::VertexBuffer: return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
+ case ResourceState::ConstantBuffer: return VK_ACCESS_UNIFORM_READ_BIT;
+ case ResourceState::IndexBuffer: return VK_ACCESS_INDEX_READ_BIT;
case ResourceState::RenderTarget:
return VkAccessFlagBits(
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT);
case ResourceState::ShaderResource:
case ResourceState::NonPixelShaderResource:
- case ResourceState::PixelShaderResource:
- return VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
+ case ResourceState::PixelShaderResource: return VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
case ResourceState::UnorderedAccess:
return VkAccessFlagBits(VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
- case ResourceState::DepthRead:
- return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
+ case ResourceState::DepthRead: return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
case ResourceState::DepthWrite:
return VkAccessFlagBits(
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
- case ResourceState::IndirectArgument:
- return VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
+ case ResourceState::IndirectArgument: return VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
case ResourceState::ResolveDestination:
- case ResourceState::CopyDestination:
- return VK_ACCESS_TRANSFER_WRITE_BIT;
+ case ResourceState::CopyDestination: return VK_ACCESS_TRANSFER_WRITE_BIT;
case ResourceState::ResolveSource:
- case ResourceState::CopySource:
- return VK_ACCESS_TRANSFER_READ_BIT;
+ case ResourceState::CopySource: return VK_ACCESS_TRANSFER_READ_BIT;
case ResourceState::AccelerationStructure:
return VkAccessFlagBits(
VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR |
@@ -146,9 +120,7 @@ VkAccessFlagBits calcAccessFlags(ResourceState state)
return VkAccessFlagBits(VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR);
case ResourceState::General:
return VkAccessFlagBits(VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
- default:
- assert(!"Unsupported");
- return VkAccessFlagBits(0);
+ default: assert(!"Unsupported"); return VkAccessFlagBits(0);
}
}
@@ -157,12 +129,9 @@ VkPipelineStageFlagBits calcPipelineStageFlags(ResourceState state, bool src)
switch (state)
{
case ResourceState::Undefined:
- case ResourceState::PreInitialized:
- assert(src);
- return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
+ case ResourceState::PreInitialized: assert(src); return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
case ResourceState::VertexBuffer:
- case ResourceState::IndexBuffer:
- return VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
+ case ResourceState::IndexBuffer: return VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
case ResourceState::ConstantBuffer:
case ResourceState::UnorderedAccess:
return VkPipelineStageFlagBits(
@@ -173,27 +142,22 @@ VkPipelineStageFlagBits calcPipelineStageFlags(ResourceState state, bool src)
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR);
case ResourceState::ShaderResource:
case ResourceState::NonPixelShaderResource:
- case ResourceState::PixelShaderResource:
- return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
- case ResourceState::RenderTarget:
- return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
+ case ResourceState::PixelShaderResource: return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
+ case ResourceState::RenderTarget: return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
case ResourceState::DepthRead:
case ResourceState::DepthWrite:
return VkPipelineStageFlagBits(
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT);
- case ResourceState::IndirectArgument:
- return VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
+ case ResourceState::IndirectArgument: return VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
case ResourceState::CopySource:
case ResourceState::CopyDestination:
case ResourceState::ResolveSource:
- case ResourceState::ResolveDestination:
- return VK_PIPELINE_STAGE_TRANSFER_BIT;
+ case ResourceState::ResolveDestination: return VK_PIPELINE_STAGE_TRANSFER_BIT;
case ResourceState::Present:
return src ? VkPipelineStageFlagBits(
- VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)
- : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
- case ResourceState::General:
- return VkPipelineStageFlagBits(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
+ VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)
+ : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
+ case ResourceState::General: return VkPipelineStageFlagBits(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
case ResourceState::AccelerationStructure:
return VkPipelineStageFlagBits(
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
@@ -204,9 +168,7 @@ VkPipelineStageFlagBits calcPipelineStageFlags(ResourceState state, bool src)
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
case ResourceState::AccelerationStructureBuildInput:
return VkPipelineStageFlagBits(VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
- default:
- assert(!"Unsupported");
- return VkPipelineStageFlagBits(0);
+ default: assert(!"Unsupported"); return VkPipelineStageFlagBits(0);
}
}
@@ -215,7 +177,7 @@ VkAccessFlags translateAccelerationStructureAccessFlag(AccessFlag access)
VkAccessFlags result = 0;
if ((uint32_t)access & (uint32_t)AccessFlag::Read)
result |= VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR | VK_ACCESS_SHADER_READ_BIT |
- VK_ACCESS_TRANSFER_READ_BIT;
+ VK_ACCESS_TRANSFER_READ_BIT;
if ((uint32_t)access & (uint32_t)AccessFlag::Write)
result |= VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR;
return result;
@@ -225,41 +187,33 @@ VkBufferUsageFlagBits _calcBufferUsageFlags(ResourceState state)
{
switch (state)
{
- case ResourceState::VertexBuffer:
- return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
- case ResourceState::IndexBuffer:
- return VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
- case ResourceState::ConstantBuffer:
- return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
- case ResourceState::StreamOutput:
- return VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT;
+ case ResourceState::VertexBuffer: return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
+ case ResourceState::IndexBuffer: return VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
+ case ResourceState::ConstantBuffer: return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
+ case ResourceState::StreamOutput: return VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT;
case ResourceState::RenderTarget:
case ResourceState::DepthRead:
case ResourceState::DepthWrite:
- {
- assert(!"Invalid resource state for buffer resource.");
- return VkBufferUsageFlagBits(0);
- }
+ {
+ assert(!"Invalid resource state for buffer resource.");
+ return VkBufferUsageFlagBits(0);
+ }
case ResourceState::UnorderedAccess:
- return (
- VkBufferUsageFlagBits)(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
+ return (VkBufferUsageFlagBits)(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT |
+ VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
case ResourceState::ShaderResource:
case ResourceState::NonPixelShaderResource:
case ResourceState::PixelShaderResource:
- return (
- VkBufferUsageFlagBits)(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
- case ResourceState::CopySource:
- return VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
- case ResourceState::CopyDestination:
- return VK_BUFFER_USAGE_TRANSFER_DST_BIT;
+ return (VkBufferUsageFlagBits)(VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT |
+ VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
+ case ResourceState::CopySource: return VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
+ case ResourceState::CopyDestination: return VK_BUFFER_USAGE_TRANSFER_DST_BIT;
case ResourceState::AccelerationStructure:
return VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR;
- case ResourceState::IndirectArgument:
- return VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
+ case ResourceState::IndirectArgument: return VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
case ResourceState::AccelerationStructureBuildInput:
return VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
- default:
- return VkBufferUsageFlagBits(0);
+ default: return VkBufferUsageFlagBits(0);
}
}
@@ -279,36 +233,25 @@ VkImageUsageFlagBits _calcImageUsageFlags(ResourceState state)
{
switch (state)
{
- case ResourceState::RenderTarget:
- return VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
- case ResourceState::DepthWrite:
- return VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
- case ResourceState::DepthRead:
- return VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
+ case ResourceState::RenderTarget: return VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
+ case ResourceState::DepthWrite: return VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
+ case ResourceState::DepthRead: return VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
case ResourceState::ShaderResource:
case ResourceState::NonPixelShaderResource:
- case ResourceState::PixelShaderResource:
- return VK_IMAGE_USAGE_SAMPLED_BIT;
- case ResourceState::UnorderedAccess:
- return VK_IMAGE_USAGE_STORAGE_BIT;
- case ResourceState::CopySource:
- return VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
- case ResourceState::CopyDestination:
- return VK_IMAGE_USAGE_TRANSFER_DST_BIT;
- case ResourceState::ResolveSource:
- return VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
- case ResourceState::ResolveDestination:
- return VK_IMAGE_USAGE_TRANSFER_DST_BIT;
- case ResourceState::Present:
- return VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
+ case ResourceState::PixelShaderResource: return VK_IMAGE_USAGE_SAMPLED_BIT;
+ case ResourceState::UnorderedAccess: return VK_IMAGE_USAGE_STORAGE_BIT;
+ case ResourceState::CopySource: return VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
+ case ResourceState::CopyDestination: return VK_IMAGE_USAGE_TRANSFER_DST_BIT;
+ case ResourceState::ResolveSource: return VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
+ case ResourceState::ResolveDestination: return VK_IMAGE_USAGE_TRANSFER_DST_BIT;
+ case ResourceState::Present: return VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
case ResourceState::Undefined:
- case ResourceState::General:
- return (VkImageUsageFlagBits)0;
+ case ResourceState::General: return (VkImageUsageFlagBits)0;
default:
- {
- assert(!"Unsupported");
- return VkImageUsageFlagBits(0);
- }
+ {
+ assert(!"Unsupported");
+ return VkImageUsageFlagBits(0);
+ }
}
}
@@ -323,17 +266,16 @@ VkImageViewType _calcImageViewType(ITextureResource::Type type, const ITextureRe
case IResource::Type::TextureCube:
return desc.arraySize > 1 ? VK_IMAGE_VIEW_TYPE_CUBE_ARRAY : VK_IMAGE_VIEW_TYPE_CUBE;
case IResource::Type::Texture3D:
- {
- // Can't have an array and 3d texture
- assert(desc.arraySize <= 1);
- if (desc.arraySize <= 1)
{
- return VK_IMAGE_VIEW_TYPE_3D;
+ // Can't have an array and 3d texture
+ assert(desc.arraySize <= 1);
+ if (desc.arraySize <= 1)
+ {
+ return VK_IMAGE_VIEW_TYPE_3D;
+ }
+ break;
}
- break;
- }
- default:
- break;
+ default: break;
}
return VK_IMAGE_VIEW_TYPE_MAX_ENUM;
@@ -352,7 +294,9 @@ VkImageUsageFlagBits _calcImageUsageFlags(ResourceStateSet states)
}
VkImageUsageFlags _calcImageUsageFlags(
- ResourceStateSet states, MemoryType memoryType, const void* initData)
+ ResourceStateSet states,
+ MemoryType memoryType,
+ const void* initData)
{
VkImageUsageFlags usage = _calcImageUsageFlags(states);
@@ -387,12 +331,9 @@ VkAccessFlags calcAccessFlagsFromImageLayout(VkImageLayout layout)
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL:
return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
- case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
- return VK_ACCESS_SHADER_READ_BIT;
- case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
- return VK_ACCESS_TRANSFER_READ_BIT;
- case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
- return VK_ACCESS_TRANSFER_WRITE_BIT;
+ case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: return VK_ACCESS_SHADER_READ_BIT;
+ case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: return VK_ACCESS_TRANSFER_READ_BIT;
+ case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: return VK_ACCESS_TRANSFER_WRITE_BIT;
default:
assert(!"Unsupported VkImageLayout");
return (VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
@@ -406,16 +347,13 @@ VkPipelineStageFlags calcPipelineStageFlagsFromImageLayout(VkImageLayout layout)
case VK_IMAGE_LAYOUT_UNDEFINED:
case VK_IMAGE_LAYOUT_PREINITIALIZED:
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
- case VK_IMAGE_LAYOUT_GENERAL:
- return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
+ case VK_IMAGE_LAYOUT_GENERAL: return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
return (VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
- case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
- return VK_PIPELINE_STAGE_TRANSFER_BIT;
- case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
- return VK_PIPELINE_STAGE_TRANSFER_BIT;
+ case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: return VK_PIPELINE_STAGE_TRANSFER_BIT;
+ case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: return VK_PIPELINE_STAGE_TRANSFER_BIT;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL:
@@ -426,9 +364,7 @@ VkPipelineStageFlags calcPipelineStageFlagsFromImageLayout(VkImageLayout layout)
case VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL:
return (
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT);
- default:
- assert(!"Unsupported VkImageLayout");
- return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
+ default: assert(!"Unsupported VkImageLayout"); return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
}
}
@@ -442,12 +378,9 @@ VkImageAspectFlags getAspectMaskFromFormat(VkFormat format)
return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_D32_SFLOAT:
- case VK_FORMAT_X8_D24_UNORM_PACK32:
- return VK_IMAGE_ASPECT_DEPTH_BIT;
- case VK_FORMAT_S8_UINT:
- return VK_IMAGE_ASPECT_STENCIL_BIT;
- default:
- return VK_IMAGE_ASPECT_COLOR_BIT;
+ case VK_FORMAT_X8_D24_UNORM_PACK32: return VK_IMAGE_ASPECT_DEPTH_BIT;
+ case VK_FORMAT_S8_UINT: return VK_IMAGE_ASPECT_STENCIL_BIT;
+ default: return VK_IMAGE_ASPECT_COLOR_BIT;
}
}
@@ -455,8 +388,8 @@ AdapterLUID getAdapterLUID(VulkanApi api, VkPhysicalDevice physicalDevice)
{
AdapterLUID luid = {};
- VkPhysicalDeviceIDPropertiesKHR idProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR };
- VkPhysicalDeviceProperties2 props = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 };
+ VkPhysicalDeviceIDPropertiesKHR idProps = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR};
+ VkPhysicalDeviceProperties2 props = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
props.pNext = &idProps;
SLANG_ASSERT(api.vkGetPhysicalDeviceFeatures2);
api.vkGetPhysicalDeviceProperties2(physicalDevice, &props);
@@ -487,7 +420,7 @@ Result SLANG_MCALL getVKAdapters(List<AdapterInfo>& outAdapters)
if (api.initGlobalProcs(module) != SLANG_OK)
continue;
- VkInstanceCreateInfo instanceCreateInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
+ VkInstanceCreateInfo instanceCreateInfo = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
const char* instanceExtensions[] = {
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
#if SLANG_APPLE_FAMILY
@@ -509,18 +442,25 @@ Result SLANG_MCALL getVKAdapters(List<AdapterInfo>& outAdapters)
if (api.vkEnumeratePhysicalDevices || api.vkGetPhysicalDeviceProperties)
{
uint32_t numPhysicalDevices = 0;
- SLANG_VK_RETURN_ON_FAIL(api.vkEnumeratePhysicalDevices(instance, &numPhysicalDevices, nullptr));
+ SLANG_VK_RETURN_ON_FAIL(
+ api.vkEnumeratePhysicalDevices(instance, &numPhysicalDevices, nullptr));
List<VkPhysicalDevice> physicalDevices;
physicalDevices.setCount(numPhysicalDevices);
- SLANG_VK_RETURN_ON_FAIL(api.vkEnumeratePhysicalDevices(instance, &numPhysicalDevices, physicalDevices.getBuffer()));
+ SLANG_VK_RETURN_ON_FAIL(api.vkEnumeratePhysicalDevices(
+ instance,
+ &numPhysicalDevices,
+ physicalDevices.getBuffer()));
for (const auto& physicalDevice : physicalDevices)
{
VkPhysicalDeviceProperties props;
api.vkGetPhysicalDeviceProperties(physicalDevice, &props);
AdapterInfo info = {};
- memcpy(info.name, props.deviceName, Math::Min(strlen(props.deviceName), sizeof(AdapterInfo::name) - 1));
+ memcpy(
+ info.name,
+ props.deviceName,
+ Math::Min(strlen(props.deviceName), sizeof(AdapterInfo::name) - 1));
info.vendorID = props.vendorID;
info.deviceID = props.deviceID;
info.luid = vk::getAdapterLUID(api, physicalDevice);
diff --git a/tools/gfx/vulkan/vk-helper-functions.h b/tools/gfx/vulkan/vk-helper-functions.h
index 8eab863f4..59dc61230 100644
--- a/tools/gfx/vulkan/vk-helper-functions.h
+++ b/tools/gfx/vulkan/vk-helper-functions.h
@@ -1,30 +1,30 @@
// vk-helper-functions.h
#pragma once
-#include "vk-base.h"
#include "core/slang-blob.h"
+#include "vk-base.h"
#include "vk-util.h"
// Vulkan has a different coordinate system to ogl
// http://anki3d.org/vulkan-coordinate-system/
#ifndef ENABLE_VALIDATION_LAYER
-# if _DEBUG
-# define ENABLE_VALIDATION_LAYER 1
-# else
-# define ENABLE_VALIDATION_LAYER 0
-# endif
+#if _DEBUG
+#define ENABLE_VALIDATION_LAYER 1
+#else
+#define ENABLE_VALIDATION_LAYER 0
+#endif
#endif
#ifdef _MSC_VER
-# include <stddef.h>
-# pragma warning(disable : 4996)
-# if (_MSC_VER < 1900)
-# define snprintf sprintf_s
-# endif
+#include <stddef.h>
+#pragma warning(disable : 4996)
+#if (_MSC_VER < 1900)
+#define snprintf sprintf_s
+#endif
#endif
#if SLANG_WINDOWS_FAMILY
-# include <dxgi1_2.h>
+#include <dxgi1_2.h>
#endif
namespace gfx
@@ -108,13 +108,14 @@ struct BindingOffset : SimpleBindingOffset
/// Create an offset from a simple offset
explicit BindingOffset(SimpleBindingOffset const& offset)
: SimpleBindingOffset(offset)
- {}
+ {
+ }
/// Create an offset based on offset information in the given Slang `varLayout`
BindingOffset(slang::VariableLayoutReflection* varLayout)
- : SimpleBindingOffset(varLayout)
- , pending(varLayout->getPendingDataLayout())
- {}
+ : SimpleBindingOffset(varLayout), pending(varLayout->getPendingDataLayout())
+ {
+ }
/// Add any values in the given `offset`
void operator+=(SimpleBindingOffset const& offset) { SimpleBindingOffset::operator+=(offset); }
@@ -166,7 +167,9 @@ VkImageUsageFlagBits _calcImageUsageFlags(ResourceState state);
VkImageViewType _calcImageViewType(ITextureResource::Type type, const ITextureResource::Desc& desc);
VkImageUsageFlagBits _calcImageUsageFlags(ResourceStateSet states);
VkImageUsageFlags _calcImageUsageFlags(
- ResourceStateSet states, MemoryType memoryType, const void* initData);
+ ResourceStateSet states,
+ MemoryType memoryType,
+ const void* initData);
VkAccessFlags calcAccessFlagsFromImageLayout(VkImageLayout layout);
VkPipelineStageFlags calcPipelineStageFlagsFromImageLayout(VkImageLayout layout);
diff --git a/tools/gfx/vulkan/vk-module.cpp b/tools/gfx/vulkan/vk-module.cpp
index 0e4df8e7f..6a3d4e095 100644
--- a/tools/gfx/vulkan/vk-module.cpp
+++ b/tools/gfx/vulkan/vk-module.cpp
@@ -1,19 +1,20 @@
// module.cpp
#include "vk-module.h"
-#include <stdlib.h>
-#include <stdio.h>
#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
#if SLANG_WINDOWS_FAMILY
-# include <windows.h>
+#include <windows.h>
#else
-# include <dlfcn.h>
+#include <dlfcn.h>
#endif
#include "../renderer-shared.h"
-namespace gfx {
+namespace gfx
+{
using namespace Slang;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! VulkanModule !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
@@ -81,4 +82,4 @@ void VulkanModule::destroy()
m_module = nullptr;
}
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-module.h b/tools/gfx/vulkan/vk-module.h
index 062c953f6..4ee04dbc8 100644
--- a/tools/gfx/vulkan/vk-module.h
+++ b/tools/gfx/vulkan/vk-module.h
@@ -1,18 +1,17 @@
// vk-module.h
#pragma once
-#include "slang.h"
-
#include "slang-com-helper.h"
+#include "slang.h"
#if SLANG_WINDOWS_FAMILY
-# define VK_USE_PLATFORM_WIN32_KHR 1
+#define VK_USE_PLATFORM_WIN32_KHR 1
#elif SLANG_APPLE_FAMILY
-# define VK_USE_PLATFORM_METAL_EXT 1
+#define VK_USE_PLATFORM_METAL_EXT 1
#else
-# if SLANG_ENABLE_XLIB
-# define VK_USE_PLATFORM_XLIB_KHR 1
-# endif
+#if SLANG_ENABLE_XLIB
+#define VK_USE_PLATFORM_XLIB_KHR 1
+#endif
#endif
#define VK_NO_PROTOTYPES
@@ -21,36 +20,37 @@
// Undef xlib macros
#ifdef Always
-# undef Always
+#undef Always
#endif
#ifdef None
-# undef None
+#undef None
#endif
-namespace gfx {
+namespace gfx
+{
struct VulkanModule
{
- /// true if has been initialized
+ /// true if has been initialized
SLANG_FORCE_INLINE bool isInitialized() const { return m_module != nullptr; }
- /// Get a function by name
+ /// Get a function by name
PFN_vkVoidFunction getFunction(const char* name) const;
- /// true if using a software Vulkan implementation.
+ /// true if using a software Vulkan implementation.
bool isSoftware() const { return m_isSoftware; }
- /// Initialize
+ /// Initialize
Slang::Result init(bool useSoftwareImpl);
- /// Destroy
+ /// Destroy
void destroy();
- /// Dtor
+ /// Dtor
~VulkanModule() { destroy(); }
- protected:
- void* m_module = nullptr;
- bool m_isSoftware = false;
+protected:
+ void* m_module = nullptr;
+ bool m_isSoftware = false;
};
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-pipeline-dump-layer.cpp b/tools/gfx/vulkan/vk-pipeline-dump-layer.cpp
index 959eee15d..e17dea1f9 100644
--- a/tools/gfx/vulkan/vk-pipeline-dump-layer.cpp
+++ b/tools/gfx/vulkan/vk-pipeline-dump-layer.cpp
@@ -1,152 +1,182 @@
#include "vk-pipeline-dump-layer.h"
+
#include "core/slang-basic.h"
#include "core/slang-stream.h"
-namespace gfx {
- using namespace Slang;
-
- struct PipelineDumpContext
- {
- Dictionary<VkPipelineLayout, Index> pipelineLayouts;
- Dictionary<VkShaderModule, Index> shaderModules;
- Dictionary<VkDescriptorSetLayout, Index> descriptorSets;
- Dictionary<VkPipeline, Index> computePipelines;
-
- List<uint8_t> serializedBytes;
-
- VulkanApi api;
-
- template<typename T>
- void writeRaw(T v)
- {
- auto startIndex = serializedBytes.getCount();
- serializedBytes.growToCount(startIndex + sizeof(T));
- memcpy(serializedBytes.getBuffer() + startIndex, &v, sizeof(T));
- }
-
- template<typename T>
- void writeArray(uint32_t elementCount, const T* data)
- {
- writeRaw(elementCount);
-
- auto startIndex = serializedBytes.getCount();
- serializedBytes.growToCount(startIndex + sizeof(T) * elementCount);
- memcpy(serializedBytes.getBuffer() + startIndex, data, sizeof(T) * elementCount);
- }
-
- void writeStr(const char* str)
- {
- auto len = (uint32_t)strlen(str) + 1;
- writeRaw(len);
-
- auto startIndex = serializedBytes.getCount();
- serializedBytes.growToCount(startIndex + len);
- memcpy(serializedBytes.getBuffer() + startIndex, str, len - 1);
- serializedBytes[startIndex + len - 1] = 0;
- }
+namespace gfx
+{
+using namespace Slang;
- void writePipelineLayout(VkPipelineLayout layout, const VkPipelineLayoutCreateInfo* createInfo)
- {
- auto startIndex = serializedBytes.getCount();
- writeRaw(createInfo->sType);
- writeRaw(createInfo->flags);
- writeRaw(createInfo->setLayoutCount);
- for (uint32_t i = 0; i < createInfo->setLayoutCount; i++)
- writeRaw(descriptorSets.getValue(createInfo->pSetLayouts[i]));
- writeArray(createInfo->pushConstantRangeCount, createInfo->pPushConstantRanges);
- pipelineLayouts[layout] = startIndex;
- }
+struct PipelineDumpContext
+{
+ Dictionary<VkPipelineLayout, Index> pipelineLayouts;
+ Dictionary<VkShaderModule, Index> shaderModules;
+ Dictionary<VkDescriptorSetLayout, Index> descriptorSets;
+ Dictionary<VkPipeline, Index> computePipelines;
- void writeShaderModule(VkShaderModule module, const VkShaderModuleCreateInfo* createInfo)
- {
- auto startIndex = serializedBytes.getCount();
- writeRaw(createInfo->sType);
- writeRaw(createInfo->flags);
- writeArray((uint32_t)(createInfo->codeSize/sizeof(uint32_t)), createInfo->pCode);
- shaderModules[module] = startIndex;
- }
+ List<uint8_t> serializedBytes;
- void writeDescriptorSetLayout(VkDescriptorSetLayout layout, const VkDescriptorSetLayoutCreateInfo* createInfo)
- {
- auto startIndex = serializedBytes.getCount();
- writeRaw(createInfo->sType);
- writeRaw(createInfo->flags);
- writeArray(createInfo->bindingCount, createInfo->pBindings);
- descriptorSets[layout] = startIndex;
- }
+ VulkanApi api;
- void writePipeline(VkPipeline pipeline, const VkComputePipelineCreateInfo* createInfo)
- {
- auto startIndex = serializedBytes.getCount();
- writeRaw(createInfo->sType);
- writeRaw(createInfo->flags);
- writeRaw(createInfo->stage.sType);
- writeRaw(createInfo->stage.flags);
- writeRaw(createInfo->stage.stage);
- writeRaw(shaderModules.getValue(createInfo->stage.module));
- writeStr(createInfo->stage.pName);
- writeRaw(pipelineLayouts.getValue(createInfo->layout));
- computePipelines[pipeline] = startIndex;
- }
+ template<typename T>
+ void writeRaw(T v)
+ {
+ auto startIndex = serializedBytes.getCount();
+ serializedBytes.growToCount(startIndex + sizeof(T));
+ memcpy(serializedBytes.getBuffer() + startIndex, &v, sizeof(T));
+ }
- void writeToFile(UnownedStringSlice path)
- {
- RefPtr<FileStream> fs = new FileStream();
- fs->init(path, FileMode::Create);
- uint32_t pipelineCount = (uint32_t)computePipelines.getCount();
- fs->write(&pipelineCount, sizeof(uint32_t));
- for (auto& pair : computePipelines)
- {
- fs->write(KeyValueDetail::getValue(&pair), sizeof(Index));
- }
- Index blobSize = serializedBytes.getCount();
- fs->write(&blobSize, sizeof(blobSize));
- fs->write(serializedBytes.getBuffer(), serializedBytes.getCount());
- fs->close();
- }
- };
+ template<typename T>
+ void writeArray(uint32_t elementCount, const T* data)
+ {
+ writeRaw(elementCount);
- PipelineDumpContext dumpContext;
+ auto startIndex = serializedBytes.getCount();
+ serializedBytes.growToCount(startIndex + sizeof(T) * elementCount);
+ memcpy(serializedBytes.getBuffer() + startIndex, data, sizeof(T) * elementCount);
+ }
- VkResult SLANG_MCALL createPipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* createInfo, const VkAllocationCallbacks* callbacks, VkPipelineLayout* outLayout)
+ void writeStr(const char* str)
{
- auto result = dumpContext.api.vkCreatePipelineLayout(device, createInfo, callbacks, outLayout);
- dumpContext.writePipelineLayout(*outLayout, createInfo);
- return result;
+ auto len = (uint32_t)strlen(str) + 1;
+ writeRaw(len);
+
+ auto startIndex = serializedBytes.getCount();
+ serializedBytes.growToCount(startIndex + len);
+ memcpy(serializedBytes.getBuffer() + startIndex, str, len - 1);
+ serializedBytes[startIndex + len - 1] = 0;
}
- VkResult SLANG_MCALL createComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t createInfoCount, const VkComputePipelineCreateInfo* createInfos, const VkAllocationCallbacks* callbacks, VkPipeline* outPipelines)
+ void writePipelineLayout(VkPipelineLayout layout, const VkPipelineLayoutCreateInfo* createInfo)
{
- auto result = dumpContext.api.vkCreateComputePipelines(device, cache, createInfoCount, createInfos, callbacks, outPipelines);
- for (uint32_t i = 0; i < createInfoCount; i++)
- dumpContext.writePipeline(outPipelines[i], createInfos + i);
- return result;
+ auto startIndex = serializedBytes.getCount();
+ writeRaw(createInfo->sType);
+ writeRaw(createInfo->flags);
+ writeRaw(createInfo->setLayoutCount);
+ for (uint32_t i = 0; i < createInfo->setLayoutCount; i++)
+ writeRaw(descriptorSets.getValue(createInfo->pSetLayouts[i]));
+ writeArray(createInfo->pushConstantRangeCount, createInfo->pPushConstantRanges);
+ pipelineLayouts[layout] = startIndex;
}
- VkResult SLANG_MCALL createShaderModule(VkDevice device, const VkShaderModuleCreateInfo* createInfo, const VkAllocationCallbacks* callbacks, VkShaderModule* outShaderModule)
+ void writeShaderModule(VkShaderModule module, const VkShaderModuleCreateInfo* createInfo)
{
- auto result = dumpContext.api.vkCreateShaderModule(device, createInfo, callbacks, outShaderModule);
- dumpContext.writeShaderModule(*outShaderModule, createInfo);
- return result;
+ auto startIndex = serializedBytes.getCount();
+ writeRaw(createInfo->sType);
+ writeRaw(createInfo->flags);
+ writeArray((uint32_t)(createInfo->codeSize / sizeof(uint32_t)), createInfo->pCode);
+ shaderModules[module] = startIndex;
}
- VkResult SLANG_MCALL createDescriptorSetLayout(VkDevice device, const VkDescriptorSetLayoutCreateInfo* createInfo, const VkAllocationCallbacks* callbacks, VkDescriptorSetLayout* outDescSetLayout)
+ void writeDescriptorSetLayout(
+ VkDescriptorSetLayout layout,
+ const VkDescriptorSetLayoutCreateInfo* createInfo)
{
- auto result = dumpContext.api.vkCreateDescriptorSetLayout(device, createInfo, callbacks, outDescSetLayout);
- dumpContext.writeDescriptorSetLayout(*outDescSetLayout, createInfo);
- return result;
+ auto startIndex = serializedBytes.getCount();
+ writeRaw(createInfo->sType);
+ writeRaw(createInfo->flags);
+ writeArray(createInfo->bindingCount, createInfo->pBindings);
+ descriptorSets[layout] = startIndex;
}
- void installPipelineDumpLayer(VulkanApi& api)
+ void writePipeline(VkPipeline pipeline, const VkComputePipelineCreateInfo* createInfo)
{
- dumpContext.api = api;
- api.vkCreatePipelineLayout = createPipelineLayout;
- api.vkCreateComputePipelines = createComputePipelines;
- api.vkCreateShaderModule = createShaderModule;
- api.vkCreateDescriptorSetLayout = createDescriptorSetLayout;
+ auto startIndex = serializedBytes.getCount();
+ writeRaw(createInfo->sType);
+ writeRaw(createInfo->flags);
+ writeRaw(createInfo->stage.sType);
+ writeRaw(createInfo->stage.flags);
+ writeRaw(createInfo->stage.stage);
+ writeRaw(shaderModules.getValue(createInfo->stage.module));
+ writeStr(createInfo->stage.pName);
+ writeRaw(pipelineLayouts.getValue(createInfo->layout));
+ computePipelines[pipeline] = startIndex;
}
- void writePipelineDump(UnownedStringSlice path)
+ void writeToFile(UnownedStringSlice path)
{
- dumpContext.writeToFile(path);
+ RefPtr<FileStream> fs = new FileStream();
+ fs->init(path, FileMode::Create);
+ uint32_t pipelineCount = (uint32_t)computePipelines.getCount();
+ fs->write(&pipelineCount, sizeof(uint32_t));
+ for (auto& pair : computePipelines)
+ {
+ fs->write(KeyValueDetail::getValue(&pair), sizeof(Index));
+ }
+ Index blobSize = serializedBytes.getCount();
+ fs->write(&blobSize, sizeof(blobSize));
+ fs->write(serializedBytes.getBuffer(), serializedBytes.getCount());
+ fs->close();
}
-} // renderer_test
+};
+
+PipelineDumpContext dumpContext;
+
+VkResult SLANG_MCALL createPipelineLayout(
+ VkDevice device,
+ const VkPipelineLayoutCreateInfo* createInfo,
+ const VkAllocationCallbacks* callbacks,
+ VkPipelineLayout* outLayout)
+{
+ auto result = dumpContext.api.vkCreatePipelineLayout(device, createInfo, callbacks, outLayout);
+ dumpContext.writePipelineLayout(*outLayout, createInfo);
+ return result;
+}
+
+VkResult SLANG_MCALL createComputePipelines(
+ VkDevice device,
+ VkPipelineCache cache,
+ uint32_t createInfoCount,
+ const VkComputePipelineCreateInfo* createInfos,
+ const VkAllocationCallbacks* callbacks,
+ VkPipeline* outPipelines)
+{
+ auto result = dumpContext.api.vkCreateComputePipelines(
+ device,
+ cache,
+ createInfoCount,
+ createInfos,
+ callbacks,
+ outPipelines);
+ for (uint32_t i = 0; i < createInfoCount; i++)
+ dumpContext.writePipeline(outPipelines[i], createInfos + i);
+ return result;
+}
+
+VkResult SLANG_MCALL createShaderModule(
+ VkDevice device,
+ const VkShaderModuleCreateInfo* createInfo,
+ const VkAllocationCallbacks* callbacks,
+ VkShaderModule* outShaderModule)
+{
+ auto result =
+ dumpContext.api.vkCreateShaderModule(device, createInfo, callbacks, outShaderModule);
+ dumpContext.writeShaderModule(*outShaderModule, createInfo);
+ return result;
+}
+
+VkResult SLANG_MCALL createDescriptorSetLayout(
+ VkDevice device,
+ const VkDescriptorSetLayoutCreateInfo* createInfo,
+ const VkAllocationCallbacks* callbacks,
+ VkDescriptorSetLayout* outDescSetLayout)
+{
+ auto result = dumpContext.api
+ .vkCreateDescriptorSetLayout(device, createInfo, callbacks, outDescSetLayout);
+ dumpContext.writeDescriptorSetLayout(*outDescSetLayout, createInfo);
+ return result;
+}
+
+void installPipelineDumpLayer(VulkanApi& api)
+{
+ dumpContext.api = api;
+ api.vkCreatePipelineLayout = createPipelineLayout;
+ api.vkCreateComputePipelines = createComputePipelines;
+ api.vkCreateShaderModule = createShaderModule;
+ api.vkCreateDescriptorSetLayout = createDescriptorSetLayout;
+}
+
+void writePipelineDump(UnownedStringSlice path)
+{
+ dumpContext.writeToFile(path);
+}
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-pipeline-dump-layer.h b/tools/gfx/vulkan/vk-pipeline-dump-layer.h
index c514f7f3e..75f4b32cc 100644
--- a/tools/gfx/vulkan/vk-pipeline-dump-layer.h
+++ b/tools/gfx/vulkan/vk-pipeline-dump-layer.h
@@ -1,11 +1,11 @@
// vk-api.cpp
-#include "vk-api.h"
-
#include "core/slang-string.h"
+#include "vk-api.h"
-namespace gfx {
+namespace gfx
+{
void installPipelineDumpLayer(VulkanApi& api);
void writePipelineDump(Slang::UnownedStringSlice path);
-} // renderer_test
+} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-pipeline-state.cpp b/tools/gfx/vulkan/vk-pipeline-state.cpp
index 2e7bb1c0a..8fd0c5680 100644
--- a/tools/gfx/vulkan/vk-pipeline-state.cpp
+++ b/tools/gfx/vulkan/vk-pipeline-state.cpp
@@ -2,12 +2,11 @@
#include "vk-pipeline-state.h"
#include "vk-device.h"
-#include "vk-shader-program.h"
+#include "vk-helper-functions.h"
#include "vk-shader-object-layout.h"
+#include "vk-shader-program.h"
#include "vk-vertex-layout.h"
-#include "vk-helper-functions.h"
-
namespace gfx
{
@@ -35,9 +34,15 @@ PipelineStateImpl::~PipelineStateImpl()
}
}
-void PipelineStateImpl::establishStrongDeviceReference() { m_device.establishStrongReference(); }
+void PipelineStateImpl::establishStrongDeviceReference()
+{
+ m_device.establishStrongReference();
+}
-void PipelineStateImpl::comFree() { m_device.breakStrongReference(); }
+void PipelineStateImpl::comFree()
+{
+ m_device.breakStrongReference();
+}
void PipelineStateImpl::init(const GraphicsPipelineStateDesc& inDesc)
{
@@ -159,8 +164,8 @@ Result PipelineStateImpl::createVKGraphicsPipelineState()
multisampling.alphaToCoverageEnable = blendDesc.alphaToCoverageEnable;
multisampling.alphaToOneEnable = VK_FALSE;
- auto targetCount =
- GfxCount(Math::Min(framebufferLayoutImpl->m_renderTargetCount, (uint32_t)blendDesc.targetCount));
+ auto targetCount = GfxCount(
+ Math::Min(framebufferLayoutImpl->m_renderTargetCount, (uint32_t)blendDesc.targetCount));
List<VkPipelineColorBlendAttachmentState> colorBlendTargets;
// Regardless of whether blending is enabled, Vulkan always applies the color write mask
@@ -222,7 +227,8 @@ Result PipelineStateImpl::createVKGraphicsPipelineState()
dynamicStates.add(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
// It's not valid to specify VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT when
// the pipeline contains a mesh shader.
- if (!m_program->isMeshShaderProgram() && m_device->m_api.m_extendedFeatures.extendedDynamicStateFeatures.extendedDynamicState)
+ if (!m_program->isMeshShaderProgram() &&
+ m_device->m_api.m_extendedFeatures.extendedDynamicStateFeatures.extendedDynamicState)
{
dynamicStates.add(VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT);
@@ -275,17 +281,21 @@ Result PipelineStateImpl::createVKGraphicsPipelineState()
if (m_device->m_pipelineCreationAPIDispatcher)
{
- SLANG_RETURN_ON_FAIL(
- m_device->m_pipelineCreationAPIDispatcher->createGraphicsPipelineState(
- m_device,
- programImpl->linkedProgram.get(),
- &pipelineInfo,
- (void**)&m_pipeline));
+ SLANG_RETURN_ON_FAIL(m_device->m_pipelineCreationAPIDispatcher->createGraphicsPipelineState(
+ m_device,
+ programImpl->linkedProgram.get(),
+ &pipelineInfo,
+ (void**)&m_pipeline));
}
else
{
SLANG_VK_RETURN_ON_FAIL(m_device->m_api.vkCreateGraphicsPipelines(
- m_device->m_device, pipelineCache, 1, &pipelineInfo, nullptr, &m_pipeline));
+ m_device->m_device,
+ pipelineCache,
+ 1,
+ &pipelineInfo,
+ nullptr,
+ &m_pipeline));
}
return SLANG_OK;
@@ -300,24 +310,28 @@ Result PipelineStateImpl::createVKComputePipelineState()
}
VkComputePipelineCreateInfo computePipelineInfo = {
- VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
+ VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
computePipelineInfo.stage = programImpl->m_stageCreateInfos[0];
computePipelineInfo.layout = programImpl->m_rootObjectLayout->m_pipelineLayout;
if (m_device->m_pipelineCreationAPIDispatcher)
{
- SLANG_RETURN_ON_FAIL(
- m_device->m_pipelineCreationAPIDispatcher->createComputePipelineState(
- m_device,
- programImpl->linkedProgram.get(),
- &computePipelineInfo,
- (void**)&m_pipeline));
+ SLANG_RETURN_ON_FAIL(m_device->m_pipelineCreationAPIDispatcher->createComputePipelineState(
+ m_device,
+ programImpl->linkedProgram.get(),
+ &computePipelineInfo,
+ (void**)&m_pipeline));
}
else
{
VkPipelineCache pipelineCache = VK_NULL_HANDLE;
SLANG_VK_RETURN_ON_FAIL(m_device->m_api.vkCreateComputePipelines(
- m_device->m_device, pipelineCache, 1, &computePipelineInfo, nullptr, &m_pipeline));
+ m_device->m_device,
+ pipelineCache,
+ 1,
+ &computePipelineInfo,
+ nullptr,
+ &m_pipeline));
}
return SLANG_OK;
}
@@ -329,13 +343,9 @@ Result PipelineStateImpl::ensureAPIPipelineStateCreated()
switch (desc.type)
{
- case PipelineType::Compute:
- return createVKComputePipelineState();
- case PipelineType::Graphics:
- return createVKGraphicsPipelineState();
- default:
- SLANG_UNREACHABLE("Unknown pipeline type.");
- return SLANG_FAIL;
+ case PipelineType::Compute: return createVKComputePipelineState();
+ case PipelineType::Graphics: return createVKGraphicsPipelineState();
+ default: SLANG_UNREACHABLE("Unknown pipeline type."); return SLANG_FAIL;
}
}
SLANG_NO_THROW Result SLANG_MCALL PipelineStateImpl::getNativeHandle(InteropHandle* outHandle)
@@ -349,9 +359,11 @@ SLANG_NO_THROW Result SLANG_MCALL PipelineStateImpl::getNativeHandle(InteropHand
RayTracingPipelineStateImpl::RayTracingPipelineStateImpl(DeviceImpl* device)
: PipelineStateImpl(device)
-{}
+{
+}
uint32_t RayTracingPipelineStateImpl::findEntryPointIndexByName(
- const Dictionary<String, Index>& entryPointNameToIndex, const char* name)
+ const Dictionary<String, Index>& entryPointNameToIndex,
+ const char* name)
{
if (!name)
return VK_SHADER_UNUSED_KHR;
@@ -451,7 +463,8 @@ Result RayTracingPipelineStateImpl::createVKRayTracingPipelineState()
if (m_device->m_pipelineCreationAPIDispatcher)
{
m_device->m_pipelineCreationAPIDispatcher->beforeCreateRayTracingState(
- m_device, programImpl->linkedProgram.get());
+ m_device,
+ programImpl->linkedProgram.get());
}
VkPipelineCache pipelineCache = VK_NULL_HANDLE;
@@ -468,7 +481,8 @@ Result RayTracingPipelineStateImpl::createVKRayTracingPipelineState()
if (m_device->m_pipelineCreationAPIDispatcher)
{
m_device->m_pipelineCreationAPIDispatcher->afterCreateRayTracingState(
- m_device, programImpl->linkedProgram.get());
+ m_device,
+ programImpl->linkedProgram.get());
}
return SLANG_OK;
}
@@ -479,11 +493,8 @@ Result RayTracingPipelineStateImpl::ensureAPIPipelineStateCreated()
switch (desc.type)
{
- case PipelineType::RayTracing:
- return createVKRayTracingPipelineState();
- default:
- SLANG_UNREACHABLE("Unknown pipeline type.");
- return SLANG_FAIL;
+ case PipelineType::RayTracing: return createVKRayTracingPipelineState();
+ default: SLANG_UNREACHABLE("Unknown pipeline type."); return SLANG_FAIL;
}
}
Result RayTracingPipelineStateImpl::getNativeHandle(InteropHandle* outHandle)
diff --git a/tools/gfx/vulkan/vk-pipeline-state.h b/tools/gfx/vulkan/vk-pipeline-state.h
index 3e84ca158..4bf585d7e 100644
--- a/tools/gfx/vulkan/vk-pipeline-state.h
+++ b/tools/gfx/vulkan/vk-pipeline-state.h
@@ -50,7 +50,8 @@ public:
RayTracingPipelineStateImpl(DeviceImpl* device);
uint32_t findEntryPointIndexByName(
- const Dictionary<String, Index>& entryPointNameToIndex, const char* name);
+ const Dictionary<String, Index>& entryPointNameToIndex,
+ const char* name);
Result createVKRayTracingPipelineState();
diff --git a/tools/gfx/vulkan/vk-query.cpp b/tools/gfx/vulkan/vk-query.cpp
index ccdb84647..694896966 100644
--- a/tools/gfx/vulkan/vk-query.cpp
+++ b/tools/gfx/vulkan/vk-query.cpp
@@ -19,9 +19,7 @@ Result QueryPoolImpl::init(const IQueryPool::Desc& desc, DeviceImpl* device)
createInfo.queryCount = (uint32_t)desc.count;
switch (desc.type)
{
- case QueryType::Timestamp:
- createInfo.queryType = VK_QUERY_TYPE_TIMESTAMP;
- break;
+ case QueryType::Timestamp: createInfo.queryType = VK_QUERY_TYPE_TIMESTAMP; break;
case QueryType::AccelerationStructureCompactedSize:
createInfo.queryType = VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR;
break;
@@ -31,8 +29,7 @@ Result QueryPoolImpl::init(const IQueryPool::Desc& desc, DeviceImpl* device)
case QueryType::AccelerationStructureCurrentSize:
// Vulkan does not support CurrentSize query, will not create actual pools here.
return SLANG_OK;
- default:
- return SLANG_E_INVALID_ARG;
+ default: return SLANG_E_INVALID_ARG;
}
SLANG_VK_RETURN_ON_FAIL(
m_device->m_api.vkCreateQueryPool(m_device->m_api.m_device, &createInfo, nullptr, &m_pool));
@@ -67,12 +64,18 @@ Result QueryPoolImpl::getResult(GfxIndex index, GfxCount count, uint64_t* data)
}
void _writeTimestamp(
- VulkanApi* api, VkCommandBuffer vkCmdBuffer, IQueryPool* queryPool, SlangInt index)
+ VulkanApi* api,
+ VkCommandBuffer vkCmdBuffer,
+ IQueryPool* queryPool,
+ SlangInt index)
{
auto queryPoolImpl = static_cast<QueryPoolImpl*>(queryPool);
api->vkCmdResetQueryPool(vkCmdBuffer, queryPoolImpl->m_pool, (uint32_t)index, 1);
api->vkCmdWriteTimestamp(
- vkCmdBuffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, queryPoolImpl->m_pool, (uint32_t)index);
+ vkCmdBuffer,
+ VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
+ queryPoolImpl->m_pool,
+ (uint32_t)index);
}
} // namespace vk
diff --git a/tools/gfx/vulkan/vk-query.h b/tools/gfx/vulkan/vk-query.h
index b9cda2557..2ff20d5ab 100644
--- a/tools/gfx/vulkan/vk-query.h
+++ b/tools/gfx/vulkan/vk-query.h
@@ -20,7 +20,7 @@ public:
public:
virtual SLANG_NO_THROW Result SLANG_MCALL
- getResult(GfxIndex index, GfxCount count, uint64_t* data) override;
+ getResult(GfxIndex index, GfxCount count, uint64_t* data) override;
public:
VkQueryPool m_pool;
@@ -28,7 +28,10 @@ public:
};
void _writeTimestamp(
- VulkanApi* api, VkCommandBuffer vkCmdBuffer, IQueryPool* queryPool, SlangInt index);
+ VulkanApi* api,
+ VkCommandBuffer vkCmdBuffer,
+ IQueryPool* queryPool,
+ SlangInt index);
} // namespace vk
} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-render-pass.cpp b/tools/gfx/vulkan/vk-render-pass.cpp
index 25a39c58a..10453fadb 100644
--- a/tools/gfx/vulkan/vk-render-pass.cpp
+++ b/tools/gfx/vulkan/vk-render-pass.cpp
@@ -67,9 +67,8 @@ Result RenderPassLayoutImpl::init(DeviceImpl* renderer, const IRenderPassLayout:
subpassDesc.colorAttachmentCount = desc.renderTargetCount;
subpassDesc.pColorAttachments = framebufferLayout->m_colorReferences.getBuffer();
subpassDesc.pResolveAttachments = nullptr;
- subpassDesc.pDepthStencilAttachment = framebufferLayout->m_hasDepthStencilTarget
- ? &framebufferLayout->m_depthReference
- : nullptr;
+ subpassDesc.pDepthStencilAttachment =
+ framebufferLayout->m_hasDepthStencilTarget ? &framebufferLayout->m_depthReference : nullptr;
subpassDesc.preserveAttachmentCount = 0u;
subpassDesc.pPreserveAttachments = nullptr;
@@ -80,7 +79,10 @@ Result RenderPassLayoutImpl::init(DeviceImpl* renderer, const IRenderPassLayout:
renderPassCreateInfo.subpassCount = 1;
renderPassCreateInfo.pSubpasses = &subpassDesc;
SLANG_VK_RETURN_ON_FAIL(m_renderer->m_api.vkCreateRenderPass(
- m_renderer->m_api.m_device, &renderPassCreateInfo, nullptr, &m_renderPass));
+ m_renderer->m_api.m_device,
+ &renderPassCreateInfo,
+ nullptr,
+ &m_renderPass));
return SLANG_OK;
}
diff --git a/tools/gfx/vulkan/vk-render-pass.h b/tools/gfx/vulkan/vk-render-pass.h
index 7cc1a581f..9fa3808c3 100644
--- a/tools/gfx/vulkan/vk-render-pass.h
+++ b/tools/gfx/vulkan/vk-render-pass.h
@@ -12,9 +12,7 @@ using namespace Slang;
namespace vk
{
-class RenderPassLayoutImpl
- : public IRenderPassLayout
- , public ComObject
+class RenderPassLayoutImpl : public IRenderPassLayout, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
diff --git a/tools/gfx/vulkan/vk-resource-views.cpp b/tools/gfx/vulkan/vk-resource-views.cpp
index 10d96ed54..b6b97b9f5 100644
--- a/tools/gfx/vulkan/vk-resource-views.cpp
+++ b/tools/gfx/vulkan/vk-resource-views.cpp
@@ -23,7 +23,8 @@ Result TextureResourceViewImpl::getNativeHandle(InteropHandle* outHandle)
TexelBufferResourceViewImpl::TexelBufferResourceViewImpl(DeviceImpl* device)
: ResourceViewImpl(ViewType::TexelBuffer, device)
-{}
+{
+}
TexelBufferResourceViewImpl::~TexelBufferResourceViewImpl()
{
@@ -39,7 +40,8 @@ Result TexelBufferResourceViewImpl::getNativeHandle(InteropHandle* outHandle)
PlainBufferResourceViewImpl::PlainBufferResourceViewImpl(DeviceImpl* device)
: ResourceViewImpl(ViewType::PlainBuffer, device)
-{}
+{
+}
Result PlainBufferResourceViewImpl::getNativeHandle(InteropHandle* outHandle)
{
@@ -63,7 +65,9 @@ AccelerationStructureImpl::~AccelerationStructureImpl()
if (m_device)
{
m_device->m_api.vkDestroyAccelerationStructureKHR(
- m_device->m_api.m_device, m_vkHandle, nullptr);
+ m_device->m_api.m_device,
+ m_vkHandle,
+ nullptr);
}
}
diff --git a/tools/gfx/vulkan/vk-resource-views.h b/tools/gfx/vulkan/vk-resource-views.h
index bba99f704..e8b4fbb0a 100644
--- a/tools/gfx/vulkan/vk-resource-views.h
+++ b/tools/gfx/vulkan/vk-resource-views.h
@@ -26,9 +26,9 @@ public:
public:
ResourceViewImpl(ViewType viewType, DeviceImpl* device)
- : m_type(viewType)
- , m_device(device)
- {}
+ : m_type(viewType), m_device(device)
+ {
+ }
ViewType m_type;
RefPtr<DeviceImpl> m_device;
};
@@ -38,7 +38,8 @@ class TextureResourceViewImpl : public ResourceViewImpl
public:
TextureResourceViewImpl(DeviceImpl* device)
: ResourceViewImpl(ViewType::Texture, device)
- {}
+ {
+ }
~TextureResourceViewImpl();
RefPtr<TextureResourceImpl> m_texture;
VkImageView m_view;
diff --git a/tools/gfx/vulkan/vk-sampler.cpp b/tools/gfx/vulkan/vk-sampler.cpp
index e07cff753..ee9357609 100644
--- a/tools/gfx/vulkan/vk-sampler.cpp
+++ b/tools/gfx/vulkan/vk-sampler.cpp
@@ -11,7 +11,8 @@ namespace vk
SamplerStateImpl::SamplerStateImpl(DeviceImpl* device)
: m_device(device)
-{}
+{
+}
SamplerStateImpl::~SamplerStateImpl()
{
diff --git a/tools/gfx/vulkan/vk-shader-object-layout.cpp b/tools/gfx/vulkan/vk-shader-object-layout.cpp
index d84627e86..6129246cb 100644
--- a/tools/gfx/vulkan/vk-shader-object-layout.cpp
+++ b/tools/gfx/vulkan/vk-shader-object-layout.cpp
@@ -31,33 +31,22 @@ VkDescriptorType ShaderObjectLayoutImpl::Builder::_mapDescriptorType(
switch (slangBindingType)
{
case slang::BindingType::PushConstant:
- default:
- SLANG_ASSERT("unsupported binding type");
- return VK_DESCRIPTOR_TYPE_MAX_ENUM;
+ default: SLANG_ASSERT("unsupported binding type"); return VK_DESCRIPTOR_TYPE_MAX_ENUM;
- case slang::BindingType::Sampler:
- return VK_DESCRIPTOR_TYPE_SAMPLER;
+ case slang::BindingType::Sampler: return VK_DESCRIPTOR_TYPE_SAMPLER;
case slang::BindingType::CombinedTextureSampler:
return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
- case slang::BindingType::Texture:
- return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
- case slang::BindingType::MutableTexture:
- return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
- case slang::BindingType::TypedBuffer:
- return VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
- case slang::BindingType::MutableTypedBuffer:
- return VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
+ case slang::BindingType::Texture: return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
+ case slang::BindingType::MutableTexture: return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
+ case slang::BindingType::TypedBuffer: return VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
+ case slang::BindingType::MutableTypedBuffer: return VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
case slang::BindingType::RawBuffer:
- case slang::BindingType::MutableRawBuffer:
- return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
- case slang::BindingType::InputRenderTarget:
- return VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
- case slang::BindingType::InlineUniformData:
- return VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT;
+ case slang::BindingType::MutableRawBuffer: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
+ case slang::BindingType::InputRenderTarget: return VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
+ case slang::BindingType::InlineUniformData: return VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT;
case slang::BindingType::RayTracingAccelerationStructure:
return VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
- case slang::BindingType::ConstantBuffer:
- return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
+ case slang::BindingType::ConstantBuffer: return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
}
}
@@ -65,7 +54,8 @@ VkDescriptorType ShaderObjectLayoutImpl::Builder::_mapDescriptorType(
/// sub-object described by `typeLayout`, at the given `offset`.
void ShaderObjectLayoutImpl::Builder::_addDescriptorRangesAsValue(
- slang::TypeLayoutReflection* typeLayout, BindingOffset const& offset)
+ slang::TypeLayoutReflection* typeLayout,
+ BindingOffset const& offset)
{
// First we will scan through all the descriptor sets that the Slang reflection
// information believes go into making up the given type.
@@ -94,8 +84,7 @@ void ShaderObjectLayoutImpl::Builder::_addDescriptorRangesAsValue(
auto bindingRangeType = typeLayout->getBindingRangeType(bindingRangeIndex);
switch (bindingRangeType)
{
- default:
- break;
+ default: break;
// We will skip over ranges that represent sub-objects for now, and handle
// them in a separate pass.
@@ -103,8 +92,7 @@ void ShaderObjectLayoutImpl::Builder::_addDescriptorRangesAsValue(
case slang::BindingType::ParameterBlock:
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ExistentialValue:
- case slang::BindingType::PushConstant:
- continue;
+ case slang::BindingType::PushConstant: continue;
}
// Given a binding range we are interested in, we will then enumerate
@@ -126,7 +114,8 @@ void ShaderObjectLayoutImpl::Builder::_addDescriptorRangesAsValue(
{
Index descriptorRangeIndex = firstDescriptorRangeIndex + j;
auto slangDescriptorType = typeLayout->getDescriptorSetDescriptorRangeType(
- slangDescriptorSetIndex, descriptorRangeIndex);
+ slangDescriptorSetIndex,
+ descriptorRangeIndex);
// Certain kinds of descriptor ranges reflected by Slang do not
// manifest as descriptors at the Vulkan level, so we will skip those.
@@ -135,20 +124,20 @@ void ShaderObjectLayoutImpl::Builder::_addDescriptorRangesAsValue(
{
case slang::BindingType::ExistentialValue:
case slang::BindingType::InlineUniformData:
- case slang::BindingType::PushConstant:
- continue;
- default:
- break;
+ case slang::BindingType::PushConstant: continue;
+ default: break;
}
auto vkDescriptorType = _mapDescriptorType(slangDescriptorType);
VkDescriptorSetLayoutBinding vkBindingRangeDesc = {};
vkBindingRangeDesc.binding =
offset.binding + (uint32_t)typeLayout->getDescriptorSetDescriptorRangeIndexOffset(
- slangDescriptorSetIndex, descriptorRangeIndex);
+ slangDescriptorSetIndex,
+ descriptorRangeIndex);
vkBindingRangeDesc.descriptorCount =
(uint32_t)typeLayout->getDescriptorSetDescriptorRangeDescriptorCount(
- slangDescriptorSetIndex, descriptorRangeIndex);
+ slangDescriptorSetIndex,
+ descriptorRangeIndex);
vkBindingRangeDesc.descriptorType = vkDescriptorType;
vkBindingRangeDesc.stageFlags = VK_SHADER_STAGE_ALL;
@@ -181,8 +170,7 @@ void ShaderObjectLayoutImpl::Builder::_addDescriptorRangesAsValue(
// decriptor sets of a parent object.
//
case slang::BindingType::ParameterBlock:
- default:
- break;
+ default: break;
case slang::BindingType::ExistentialValue:
// An interest/existential-typed sub-object range will only contribute
@@ -221,7 +209,9 @@ void ShaderObjectLayoutImpl::Builder::_addDescriptorRangesAsValue(
elementOffset += BindingOffset(elementVarLayout);
_addDescriptorRangesAsConstantBuffer(
- elementTypeLayout, containerOffset, elementOffset);
+ elementTypeLayout,
+ containerOffset,
+ elementOffset);
}
break;
@@ -252,7 +242,9 @@ void ShaderObjectLayoutImpl::Builder::_addDescriptorRangesAsValue(
elementOffset += BindingOffset(elementVarLayout);
_addDescriptorRangesAsPushConstantBuffer(
- elementTypeLayout, containerOffset, elementOffset);
+ elementTypeLayout,
+ containerOffset,
+ elementOffset);
}
break;
}
@@ -416,7 +408,8 @@ void ShaderObjectLayoutImpl::Builder::addBindingRanges(slang::TypeLayoutReflecti
auto set = typeLayout->getDescriptorSetSpaceOffset(descriptorSetIndex);
auto bindingOffset = typeLayout->getDescriptorSetDescriptorRangeIndexOffset(
- descriptorSetIndex, descriptorRangeIndex);
+ descriptorSetIndex,
+ descriptorRangeIndex);
bindingRangeInfo.setOffset = uint32_t(set);
bindingRangeInfo.bindingOffset = uint32_t(bindingOffset);
@@ -449,7 +442,10 @@ void ShaderObjectLayoutImpl::Builder::addBindingRanges(slang::TypeLayoutReflecti
auto varLayout = slangLeafTypeLayout->getElementVarLayout();
auto subTypeLayout = varLayout->getTypeLayout();
ShaderObjectLayoutImpl::createForElementType(
- m_renderer, m_session, subTypeLayout, subObjectLayout.writeRef());
+ m_renderer,
+ m_session,
+ subTypeLayout,
+ subObjectLayout.writeRef());
}
break;
@@ -457,7 +453,10 @@ void ShaderObjectLayoutImpl::Builder::addBindingRanges(slang::TypeLayoutReflecti
if (auto pendingTypeLayout = slangLeafTypeLayout->getPendingDataTypeLayout())
{
ShaderObjectLayoutImpl::createForElementType(
- m_renderer, m_session, pendingTypeLayout, subObjectLayout.writeRef());
+ m_renderer,
+ m_session,
+ pendingTypeLayout,
+ subObjectLayout.writeRef());
}
break;
}
@@ -509,8 +508,7 @@ void ShaderObjectLayoutImpl::Builder::addBindingRanges(slang::TypeLayoutReflecti
}
break;
- default:
- break;
+ default: break;
}
m_subObjectRanges.add(subObjectRange);
@@ -602,7 +600,9 @@ Result ShaderObjectLayoutImpl::createForElementType(
// since that is how things will be laid out inside the parameter block.
//
builder._addDescriptorRangesAsConstantBuffer(
- builder.m_elementTypeLayout, containerOffset, elementOffset);
+ builder.m_elementTypeLayout,
+ containerOffset,
+ elementOffset);
return builder.build(outLayout);
}
@@ -611,7 +611,9 @@ ShaderObjectLayoutImpl::~ShaderObjectLayoutImpl()
for (auto& descSetInfo : m_descriptorSetInfos)
{
getDevice()->m_api.vkDestroyDescriptorSetLayout(
- getDevice()->m_api.m_device, descSetInfo.descriptorSetLayout, nullptr);
+ getDevice()->m_api.m_device,
+ descSetInfo.descriptorSetLayout,
+ nullptr);
}
}
@@ -645,7 +647,10 @@ Result ShaderObjectLayoutImpl::_init(Builder const* builder)
createInfo.bindingCount = (uint32_t)descriptorSetInfo.vkBindings.getCount();
VkDescriptorSetLayout vkDescSetLayout;
SLANG_RETURN_ON_FAIL(renderer->m_api.vkCreateDescriptorSetLayout(
- renderer->m_api.m_device, &createInfo, nullptr, &vkDescSetLayout));
+ renderer->m_api.m_device,
+ &createInfo,
+ nullptr,
+ &vkDescSetLayout));
descriptorSetInfo.descriptorSetLayout = vkDescSetLayout;
}
return SLANG_OK;
@@ -693,7 +698,9 @@ RootShaderObjectLayout::~RootShaderObjectLayout()
if (m_pipelineLayout)
{
m_renderer->m_api.vkDestroyPipelineLayout(
- m_renderer->m_api.m_device, m_pipelineLayout, nullptr);
+ m_renderer->m_api.m_device,
+ m_pipelineLayout,
+ nullptr);
}
}
@@ -790,7 +797,10 @@ Result RootShaderObjectLayout::_init(Builder const* builder)
pipelineLayoutCreateInfo.pPushConstantRanges = m_allPushConstantRanges.getBuffer();
}
SLANG_RETURN_ON_FAIL(m_renderer->m_api.vkCreatePipelineLayout(
- m_renderer->m_api.m_device, &pipelineLayoutCreateInfo, nullptr, &m_pipelineLayout));
+ m_renderer->m_api.m_device,
+ &pipelineLayoutCreateInfo,
+ nullptr,
+ &m_pipelineLayout));
return SLANG_OK;
}
diff --git a/tools/gfx/vulkan/vk-shader-object-layout.h b/tools/gfx/vulkan/vk-shader-object-layout.h
index 3f60e6b89..bc95097f8 100644
--- a/tools/gfx/vulkan/vk-shader-object-layout.h
+++ b/tools/gfx/vulkan/vk-shader-object-layout.h
@@ -136,7 +136,8 @@ public:
public:
Builder(DeviceImpl* renderer, slang::ISession* session)
: m_renderer(renderer), m_session(session)
- {}
+ {
+ }
DeviceImpl* m_renderer;
slang::ISession* m_session;
@@ -180,7 +181,8 @@ public:
/// Add any descriptor ranges implied by this object containing a leaf
/// sub-object described by `typeLayout`, at the given `offset`.
void _addDescriptorRangesAsValue(
- slang::TypeLayoutReflection* typeLayout, BindingOffset const& offset);
+ slang::TypeLayoutReflection* typeLayout,
+ BindingOffset const& offset);
/// Add the descriptor ranges implied by a `ConstantBuffer<X>` where `X` is
/// described by `elementTypeLayout`.
@@ -325,7 +327,8 @@ public:
{
Builder(DeviceImpl* device, slang::ISession* session)
: Super::Builder(device, session)
- {}
+ {
+ }
Result build(EntryPointLayout** outLayout);
@@ -372,7 +375,8 @@ public:
: Super::Builder(renderer, program->getSession())
, m_program(program)
, m_programLayout(programLayout)
- {}
+ {
+ }
Result build(RootShaderObjectLayout** outLayout);
diff --git a/tools/gfx/vulkan/vk-shader-object.cpp b/tools/gfx/vulkan/vk-shader-object.cpp
index 37edd8efa..862f6137a 100644
--- a/tools/gfx/vulkan/vk-shader-object.cpp
+++ b/tools/gfx/vulkan/vk-shader-object.cpp
@@ -14,7 +14,9 @@ namespace vk
{
Result ShaderObjectImpl::create(
- IDevice* device, ShaderObjectLayoutImpl* layout, ShaderObjectImpl** outShaderObject)
+ IDevice* device,
+ ShaderObjectLayoutImpl* layout,
+ ShaderObjectImpl** outShaderObject)
{
auto object = RefPtr<ShaderObjectImpl>(new ShaderObjectImpl());
SLANG_RETURN_ON_FAIL(object->init(device, layout));
@@ -23,9 +25,15 @@ Result ShaderObjectImpl::create(
return SLANG_OK;
}
-RendererBase* ShaderObjectImpl::getDevice() { return m_layout->getDevice(); }
+RendererBase* ShaderObjectImpl::getDevice()
+{
+ return m_layout->getDevice();
+}
-GfxCount ShaderObjectImpl::getEntryPointCount() { return 0; }
+GfxCount ShaderObjectImpl::getEntryPointCount()
+{
+ return 0;
+}
Result ShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
{
@@ -33,9 +41,15 @@ Result ShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryP
return SLANG_OK;
}
-const void* ShaderObjectImpl::getRawData() { return m_data.getBuffer(); }
+const void* ShaderObjectImpl::getRawData()
+{
+ return m_data.getBuffer();
+}
-Size ShaderObjectImpl::getSize() { return (Size)m_data.getCount(); }
+Size ShaderObjectImpl::getSize()
+{
+ return (Size)m_data.getCount();
+}
// TODO: Change size_t and Index to Size?
Result ShaderObjectImpl::setData(ShaderOffset const& inOffset, void const* data, size_t inSize)
@@ -110,7 +124,9 @@ Result ShaderObjectImpl::setSampler(ShaderOffset const& offset, ISamplerState* s
}
Result ShaderObjectImpl::setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler)
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler)
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
@@ -307,7 +323,8 @@ Result ShaderObjectImpl::_writeOrdinaryData(
}
void ShaderObjectImpl::writeDescriptor(
- RootBindingContext& context, VkWriteDescriptorSet const& write)
+ RootBindingContext& context,
+ VkWriteDescriptorSet const& write)
{
auto device = context.device;
device->m_api.vkUpdateDescriptorSets(device->m_device, 1, &write, 0, nullptr);
@@ -350,7 +367,12 @@ void ShaderObjectImpl::writeBufferDescriptor(
BufferResourceImpl* buffer)
{
writeBufferDescriptor(
- context, offset, descriptorType, buffer, 0, buffer->getDesc()->sizeInBytes);
+ context,
+ offset,
+ descriptorType,
+ buffer,
+ 0,
+ buffer->getDesc()->sizeInBytes);
}
void ShaderObjectImpl::writePlainBufferDescriptor(
@@ -586,7 +608,8 @@ bool ShaderObjectImpl::shouldAllocateConstantBuffer(TransientResourceHeapImpl* t
}
Result ShaderObjectImpl::_ensureOrdinaryDataBufferCreatedIfNeeded(
- PipelineCommandEncoder* encoder, ShaderObjectLayoutImpl* specializedLayout)
+ PipelineCommandEncoder* encoder,
+ ShaderObjectLayoutImpl* specializedLayout)
{
// If data has been changed since last allocation/filling of constant buffer,
// we will need to allocate a new one.
@@ -609,7 +632,9 @@ Result ShaderObjectImpl::_ensureOrdinaryDataBufferCreatedIfNeeded(
// it from the transient resource heap.
//
SLANG_RETURN_ON_FAIL(encoder->m_commandBuffer->m_transientHeap->allocateConstantBuffer(
- m_constantBufferSize, m_constantBuffer, m_constantBufferOffset));
+ m_constantBufferSize,
+ m_constantBuffer,
+ m_constantBufferOffset));
// Once the buffer is allocated, we can use `_writeOrdinaryData` to fill it in.
//
@@ -647,8 +672,7 @@ Result ShaderObjectImpl::bindAsValue(
{
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ParameterBlock:
- case slang::BindingType::ExistentialValue:
- break;
+ case slang::BindingType::ExistentialValue: break;
case slang::BindingType::Texture:
rangeOffset.bindingSet += bindingRangeInfo.setOffset;
@@ -727,8 +751,7 @@ Result ShaderObjectImpl::bindAsValue(
m_resourceViews.getArrayView(baseIndex, count));
break;
case slang::BindingType::VaryingInput:
- case slang::BindingType::VaryingOutput:
- break;
+ case slang::BindingType::VaryingOutput: break;
default:
SLANG_ASSERT(!"unsupported binding type");
@@ -824,8 +847,8 @@ Result ShaderObjectImpl::bindAsValue(
// already.
//
ShaderObjectImpl* subObject = m_objects[subObjectIndex + i];
- subObject->bindAsValue(
- encoder, context, BindingOffset(objOffset), subObjectLayout);
+ subObject
+ ->bindAsValue(encoder, context, BindingOffset(objOffset), subObjectLayout);
objOffset += objStride;
}
}
@@ -987,7 +1010,9 @@ Result ShaderObjectImpl::_createSpecializedLayout(ShaderObjectLayoutImpl** outLa
}
Result EntryPointShaderObject::create(
- IDevice* device, EntryPointLayout* layout, EntryPointShaderObject** outShaderObject)
+ IDevice* device,
+ EntryPointLayout* layout,
+ EntryPointShaderObject** outShaderObject)
{
RefPtr<EntryPointShaderObject> object = new EntryPointShaderObject();
SLANG_RETURN_ON_FAIL(object->init(device, layout));
@@ -1080,7 +1105,10 @@ List<RefPtr<EntryPointShaderObject>> const& RootShaderObjectImpl::getEntryPoints
return m_entryPoints;
}
-GfxCount RootShaderObjectImpl::getEntryPointCount() { return (GfxCount)m_entryPoints.getCount(); }
+GfxCount RootShaderObjectImpl::getEntryPointCount()
+{
+ return (GfxCount)m_entryPoints.getCount();
+}
Result RootShaderObjectImpl::getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint)
{
@@ -1103,7 +1131,9 @@ Result RootShaderObjectImpl::copyFrom(IShaderObject* object, ITransientResourceH
}
Result RootShaderObjectImpl::bindAsRoot(
- PipelineCommandEncoder* encoder, RootBindingContext& context, RootShaderObjectLayout* layout)
+ PipelineCommandEncoder* encoder,
+ RootBindingContext& context,
+ RootShaderObjectLayout* layout)
{
BindingOffset offset = {};
offset.pending = layout->getPendingDataOffset();
@@ -1141,8 +1171,8 @@ Result RootShaderObjectImpl::bindAsRoot(
// `RootShaderObjectLayout` has already baked any offsets
// from the global layout into the `entryPointInfo`.
- entryPoint->bindAsEntryPoint(
- encoder, context, entryPointInfo.offset, entryPointInfo.layout);
+ entryPoint
+ ->bindAsEntryPoint(encoder, context, entryPointInfo.offset, entryPointInfo.layout);
}
return SLANG_OK;
diff --git a/tools/gfx/vulkan/vk-shader-object.h b/tools/gfx/vulkan/vk-shader-object.h
index efd8842cb..fafeb67f1 100644
--- a/tools/gfx/vulkan/vk-shader-object.h
+++ b/tools/gfx/vulkan/vk-shader-object.h
@@ -2,10 +2,10 @@
#pragma once
#include "vk-base.h"
+#include "vk-helper-functions.h"
#include "vk-resource-views.h"
#include "vk-sampler.h"
#include "vk-shader-object-layout.h"
-#include "vk-helper-functions.h"
namespace gfx
{
@@ -27,14 +27,16 @@ class ShaderObjectImpl
{
public:
static Result create(
- IDevice* device, ShaderObjectLayoutImpl* layout, ShaderObjectImpl** outShaderObject);
+ IDevice* device,
+ ShaderObjectLayoutImpl* layout,
+ ShaderObjectImpl** outShaderObject);
RendererBase* getDevice();
virtual SLANG_NO_THROW GfxCount SLANG_MCALL getEntryPointCount() override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
virtual SLANG_NO_THROW const void* SLANG_MCALL getRawData() override;
@@ -42,16 +44,18 @@ public:
// TODO: Changed size_t to Size? inSize assigned to an Index variable inside implementation
virtual SLANG_NO_THROW Result SLANG_MCALL
- setData(ShaderOffset const& inOffset, void const* data, size_t inSize) override;
+ setData(ShaderOffset const& inOffset, void const* data, size_t inSize) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setResource(ShaderOffset const& offset, IResourceView* resourceView) override;
+ setResource(ShaderOffset const& offset, IResourceView* resourceView) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
+ setSampler(ShaderOffset const& offset, ISamplerState* sampler) override;
virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
- ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) override;
+ ShaderOffset const& offset,
+ IResourceView* textureView,
+ ISamplerState* sampler) override;
protected:
friend class RootShaderObjectLayout;
@@ -125,7 +129,8 @@ public:
/// Ensure that the `m_ordinaryDataBuffer` has been created, if it is needed
Result _ensureOrdinaryDataBufferCreatedIfNeeded(
- PipelineCommandEncoder* encoder, ShaderObjectLayoutImpl* specializedLayout);
+ PipelineCommandEncoder* encoder,
+ ShaderObjectLayoutImpl* specializedLayout);
public:
/// Bind this shader object as a "value"
@@ -211,7 +216,9 @@ class EntryPointShaderObject : public ShaderObjectImpl
public:
static Result create(
- IDevice* device, EntryPointLayout* layout, EntryPointShaderObject** outShaderObject);
+ IDevice* device,
+ EntryPointLayout* layout,
+ EntryPointShaderObject** outShaderObject);
EntryPointLayout* getLayout();
@@ -244,10 +251,11 @@ public:
List<RefPtr<EntryPointShaderObject>> const& getEntryPoints() const;
virtual GfxCount SLANG_MCALL getEntryPointCount() override;
- virtual Result SLANG_MCALL getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
+ virtual Result SLANG_MCALL
+ getEntryPoint(GfxIndex index, IShaderObject** outEntryPoint) override;
virtual SLANG_NO_THROW Result SLANG_MCALL
- copyFrom(IShaderObject* object, ITransientResourceHeap* transientHeap) override;
+ copyFrom(IShaderObject* object, ITransientResourceHeap* transientHeap) override;
/// Bind this object as a root shader object
Result bindAsRoot(
diff --git a/tools/gfx/vulkan/vk-shader-program.cpp b/tools/gfx/vulkan/vk-shader-program.cpp
index 4159561d1..43a295786 100644
--- a/tools/gfx/vulkan/vk-shader-program.cpp
+++ b/tools/gfx/vulkan/vk-shader-program.cpp
@@ -30,7 +30,10 @@ ShaderProgramImpl::~ShaderProgramImpl()
}
}
-void ShaderProgramImpl::comFree() { m_device.breakStrongReference(); }
+void ShaderProgramImpl::comFree()
+{
+ m_device.breakStrongReference();
+}
VkPipelineShaderStageCreateInfo ShaderProgramImpl::compileEntryPoint(
const char* entryPointName,
@@ -50,7 +53,10 @@ VkPipelineShaderStageCreateInfo ShaderProgramImpl::compileEntryPoint(
VkShaderModule module;
SLANG_VK_CHECK(m_device->m_api.vkCreateShaderModule(
- m_device->m_device, &moduleCreateInfo, nullptr, &module));
+ m_device->m_device,
+ &moduleCreateInfo,
+ nullptr,
+ &module));
outShaderModule = module;
VkPipelineShaderStageCreateInfo shaderStageCreateInfo = {
@@ -64,7 +70,8 @@ VkPipelineShaderStageCreateInfo ShaderProgramImpl::compileEntryPoint(
}
Result ShaderProgramImpl::createShaderModule(
- slang::EntryPointReflection* entryPointInfo, ComPtr<ISlangBlob> kernelCode)
+ slang::EntryPointReflection* entryPointInfo,
+ ComPtr<ISlangBlob> kernelCode)
{
m_codeBlobs.add(kernelCode);
VkShaderModule shaderModule;
diff --git a/tools/gfx/vulkan/vk-shader-program.h b/tools/gfx/vulkan/vk-shader-program.h
index 49fd6d256..3fd56669a 100644
--- a/tools/gfx/vulkan/vk-shader-program.h
+++ b/tools/gfx/vulkan/vk-shader-program.h
@@ -36,7 +36,8 @@ public:
VkShaderModule& outShaderModule);
virtual Result createShaderModule(
- slang::EntryPointReflection* entryPointInfo, ComPtr<ISlangBlob> kernelCode) override;
+ slang::EntryPointReflection* entryPointInfo,
+ ComPtr<ISlangBlob> kernelCode) override;
};
diff --git a/tools/gfx/vulkan/vk-shader-table.cpp b/tools/gfx/vulkan/vk-shader-table.cpp
index beb826111..4d47a2b96 100644
--- a/tools/gfx/vulkan/vk-shader-table.cpp
+++ b/tools/gfx/vulkan/vk-shader-table.cpp
@@ -2,9 +2,8 @@
#include "vk-shader-table.h"
#include "vk-device.h"
-#include "vk-transient-heap.h"
-
#include "vk-helper-functions.h"
+#include "vk-transient-heap.h"
namespace gfx
{
@@ -24,11 +23,14 @@ RefPtr<BufferResource> ShaderTableImpl::createDeviceBuffer(
uint32_t handleSize = rtProps.shaderGroupHandleSize;
m_raygenTableSize = m_rayGenShaderCount * rtProps.shaderGroupBaseAlignment;
m_missTableSize = (uint32_t)VulkanUtil::calcAligned(
- m_missShaderCount * handleSize, rtProps.shaderGroupBaseAlignment);
+ m_missShaderCount * handleSize,
+ rtProps.shaderGroupBaseAlignment);
m_hitTableSize = (uint32_t)VulkanUtil::calcAligned(
- m_hitGroupCount * handleSize, rtProps.shaderGroupBaseAlignment);
+ m_hitGroupCount * handleSize,
+ rtProps.shaderGroupBaseAlignment);
m_callableTableSize = (uint32_t)VulkanUtil::calcAligned(
- m_callableShaderCount * handleSize, rtProps.shaderGroupBaseAlignment);
+ m_callableShaderCount * handleSize,
+ rtProps.shaderGroupBaseAlignment);
uint32_t tableSize = m_raygenTableSize + m_missTableSize + m_hitTableSize + m_callableTableSize;
auto pipelineImpl = static_cast<RayTracingPipelineStateImpl*>(pipeline);
@@ -51,8 +53,8 @@ RefPtr<BufferResource> ShaderTableImpl::createDeviceBuffer(
IBufferResource* stagingBuffer = nullptr;
Offset stagingBufferOffset = 0;
- transientHeapImpl->allocateStagingBuffer(
- tableSize, stagingBuffer, stagingBufferOffset, MemoryType::Upload);
+ transientHeapImpl
+ ->allocateStagingBuffer(tableSize, stagingBuffer, stagingBufferOffset, MemoryType::Upload);
assert(stagingBuffer);
void* stagingPtr = nullptr;
diff --git a/tools/gfx/vulkan/vk-swap-chain.cpp b/tools/gfx/vulkan/vk-swap-chain.cpp
index 7580e01b3..4f9bd3ca2 100644
--- a/tools/gfx/vulkan/vk-swap-chain.cpp
+++ b/tools/gfx/vulkan/vk-swap-chain.cpp
@@ -1,8 +1,8 @@
// vk-swap-chain.cpp
#include "vk-swap-chain.h"
-#include "vk-util.h"
#include "../apple/cocoa-util.h"
+#include "vk-util.h"
namespace gfx
{
@@ -44,7 +44,9 @@ void SwapchainImpl::getWindowSize(int* widthOut, int* heightOut) const
#elif defined(SLANG_ENABLE_XLIB)
XWindowAttributes winAttr = {};
XGetWindowAttributes(
- (Display*)m_windowHandle.handleValues[0], (Window)m_windowHandle.handleValues[1], &winAttr);
+ (Display*)m_windowHandle.handleValues[0],
+ (Window)m_windowHandle.handleValues[1],
+ &winAttr);
*widthOut = winAttr.width;
*heightOut = winAttr.height;
@@ -78,22 +80,32 @@ Result SwapchainImpl::createSwapchainAndImages()
VkSurfaceCapabilitiesKHR surfaceCaps;
SLANG_VK_RETURN_ON_FAIL(m_api->vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
- m_api->m_physicalDevice, m_surface, &surfaceCaps));
+ m_api->m_physicalDevice,
+ m_surface,
+ &surfaceCaps));
}
VkPresentModeKHR presentMode;
List<VkPresentModeKHR> presentModes;
uint32_t numPresentModes = 0;
m_api->vkGetPhysicalDeviceSurfacePresentModesKHR(
- m_api->m_physicalDevice, m_surface, &numPresentModes, nullptr);
+ m_api->m_physicalDevice,
+ m_surface,
+ &numPresentModes,
+ nullptr);
presentModes.setCount(numPresentModes);
m_api->vkGetPhysicalDeviceSurfacePresentModesKHR(
- m_api->m_physicalDevice, m_surface, &numPresentModes, presentModes.getBuffer());
+ m_api->m_physicalDevice,
+ m_surface,
+ &numPresentModes,
+ presentModes.getBuffer());
{
int numCheckPresentOptions = 3;
VkPresentModeKHR presentOptions[] = {
- VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR};
+ VK_PRESENT_MODE_IMMEDIATE_KHR,
+ VK_PRESENT_MODE_MAILBOX_KHR,
+ VK_PRESENT_MODE_FIFO_KHR};
if (m_desc.enableVSync)
{
presentOptions[0] = VK_PRESENT_MODE_FIFO_KHR;
@@ -147,14 +159,19 @@ Result SwapchainImpl::createSwapchainAndImages()
{
vkImages.setCount(numSwapChainImages);
m_api->vkGetSwapchainImagesKHR(
- m_api->m_device, m_swapChain, &numSwapChainImages, vkImages.getBuffer());
+ m_api->m_device,
+ m_swapChain,
+ &numSwapChainImages,
+ vkImages.getBuffer());
}
for (GfxIndex i = 0; i < m_desc.imageCount; i++)
{
ITextureResource::Desc imageDesc = {};
imageDesc.allowedStates = ResourceStateSet(
- ResourceState::Present, ResourceState::RenderTarget, ResourceState::CopyDestination);
+ ResourceState::Present,
+ ResourceState::RenderTarget,
+ ResourceState::CopyDestination);
imageDesc.type = IResource::Type::Texture2D;
imageDesc.arraySize = 0;
imageDesc.format = m_desc.format;
@@ -213,7 +230,10 @@ Result SwapchainImpl::init(DeviceImpl* renderer, const ISwapchain::Desc& desc, W
VkSemaphoreCreateInfo semaphoreCreateInfo = {};
semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
SLANG_VK_RETURN_ON_FAIL(renderer->m_api.vkCreateSemaphore(
- renderer->m_api.m_device, &semaphoreCreateInfo, nullptr, &m_nextImageSemaphore));
+ renderer->m_api.m_device,
+ &semaphoreCreateInfo,
+ nullptr,
+ &m_nextImageSemaphore));
m_queue = static_cast<CommandQueueImpl*>(desc.queue);
@@ -247,15 +267,24 @@ Result SwapchainImpl::init(DeviceImpl* renderer, const ISwapchain::Desc& desc, W
VkBool32 supported = false;
m_api->vkGetPhysicalDeviceSurfaceSupportKHR(
- m_api->m_physicalDevice, renderer->m_queueFamilyIndex, m_surface, &supported);
+ m_api->m_physicalDevice,
+ renderer->m_queueFamilyIndex,
+ m_surface,
+ &supported);
uint32_t numSurfaceFormats = 0;
List<VkSurfaceFormatKHR> surfaceFormats;
m_api->vkGetPhysicalDeviceSurfaceFormatsKHR(
- m_api->m_physicalDevice, m_surface, &numSurfaceFormats, nullptr);
+ m_api->m_physicalDevice,
+ m_surface,
+ &numSurfaceFormats,
+ nullptr);
surfaceFormats.setCount(int(numSurfaceFormats));
m_api->vkGetPhysicalDeviceSurfaceFormatsKHR(
- m_api->m_physicalDevice, m_surface, &numSurfaceFormats, surfaceFormats.getBuffer());
+ m_api->m_physicalDevice,
+ m_surface,
+ &numSurfaceFormats,
+ surfaceFormats.getBuffer());
// Look for a suitable format
List<VkFormat> formats;
@@ -360,8 +389,7 @@ int SwapchainImpl::acquireNextImage()
VK_NULL_HANDLE,
(uint32_t*)&m_currentImageIndex);
- if (
- result != VK_SUCCESS
+ if (result != VK_SUCCESS
#if SLANG_APPLE_FAMILY
&& result != VK_SUBOPTIMAL_KHR
#endif
@@ -376,7 +404,10 @@ int SwapchainImpl::acquireNextImage()
return m_currentImageIndex;
}
-Result SwapchainImpl::setFullScreenMode(bool mode) { return SLANG_FAIL; }
+Result SwapchainImpl::setFullScreenMode(bool mode)
+{
+ return SLANG_FAIL;
+}
} // namespace vk
} // namespace gfx
diff --git a/tools/gfx/vulkan/vk-swap-chain.h b/tools/gfx/vulkan/vk-swap-chain.h
index 50878cd7b..166140cce 100644
--- a/tools/gfx/vulkan/vk-swap-chain.h
+++ b/tools/gfx/vulkan/vk-swap-chain.h
@@ -14,9 +14,7 @@ using namespace Slang;
namespace vk
{
-class SwapchainImpl
- : public ISwapchain
- , public ComObject
+class SwapchainImpl : public ISwapchain, public ComObject
{
public:
SLANG_COM_OBJECT_IUNKNOWN_ALL
@@ -53,7 +51,7 @@ public:
virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override { return m_desc; }
virtual SLANG_NO_THROW Result SLANG_MCALL
- getImage(GfxIndex index, ITextureResource** outResource) override;
+ getImage(GfxIndex index, ITextureResource** outResource) override;
virtual SLANG_NO_THROW Result SLANG_MCALL resize(GfxCount width, GfxCount height) override;
virtual SLANG_NO_THROW Result SLANG_MCALL present() override;
virtual SLANG_NO_THROW int SLANG_MCALL acquireNextImage() override;
diff --git a/tools/gfx/vulkan/vk-texture.cpp b/tools/gfx/vulkan/vk-texture.cpp
index 13775cef0..ea305c1a1 100644
--- a/tools/gfx/vulkan/vk-texture.cpp
+++ b/tools/gfx/vulkan/vk-texture.cpp
@@ -10,9 +10,9 @@ namespace vk
{
TextureResourceImpl::TextureResourceImpl(const Desc& desc, DeviceImpl* device)
- : Parent(desc)
- , m_device(device)
-{}
+ : Parent(desc), m_device(device)
+{
+}
TextureResourceImpl::~TextureResourceImpl()
{
diff --git a/tools/gfx/vulkan/vk-texture.h b/tools/gfx/vulkan/vk-texture.h
index 95e3b779e..58ef420fe 100644
--- a/tools/gfx/vulkan/vk-texture.h
+++ b/tools/gfx/vulkan/vk-texture.h
@@ -26,7 +26,7 @@ public:
RefPtr<DeviceImpl> m_device;
virtual SLANG_NO_THROW Result SLANG_MCALL
- getNativeResourceHandle(InteropHandle* outHandle) override;
+ getNativeResourceHandle(InteropHandle* outHandle) override;
virtual SLANG_NO_THROW Result SLANG_MCALL getSharedHandle(InteropHandle* outHandle) override;
diff --git a/tools/gfx/vulkan/vk-transient-heap.cpp b/tools/gfx/vulkan/vk-transient-heap.cpp
index fa4eb718b..afc062d0f 100644
--- a/tools/gfx/vulkan/vk-transient-heap.cpp
+++ b/tools/gfx/vulkan/vk-transient-heap.cpp
@@ -22,7 +22,10 @@ void TransientResourceHeapImpl::advanceFence()
fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
m_device->m_api.vkCreateFence(
- m_device->m_api.m_device, &fenceCreateInfo, nullptr, &m_fences[m_fenceIndex]);
+ m_device->m_api.m_device,
+ &fenceCreateInfo,
+ nullptr,
+ &m_fences[m_fenceIndex]);
}
}
@@ -40,8 +43,8 @@ Result TransientResourceHeapImpl::init(const ITransientResourceHeap::Desc& desc,
poolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
poolCreateInfo.queueFamilyIndex =
device->getQueueFamilyIndex(ICommandQueue::QueueType::Graphics);
- device->m_api.vkCreateCommandPool(
- device->m_api.m_device, &poolCreateInfo, nullptr, &m_commandPool);
+ device->m_api
+ .vkCreateCommandPool(device->m_api.m_device, &poolCreateInfo, nullptr, &m_commandPool);
advanceFence();
return SLANG_OK;
@@ -83,8 +86,11 @@ Result TransientResourceHeapImpl::synchronizeAndReset()
m_commandBufferAllocId = 0;
auto& api = m_device->m_api;
if (api.vkWaitForFences(
- api.m_device, (uint32_t)m_fences.getCount(), m_fences.getBuffer(), 1, UINT64_MAX) !=
- VK_SUCCESS)
+ api.m_device,
+ (uint32_t)m_fences.getCount(),
+ m_fences.getBuffer(),
+ 1,
+ UINT64_MAX) != VK_SUCCESS)
{
return SLANG_FAIL;
}
diff --git a/tools/gfx/vulkan/vk-transient-heap.h b/tools/gfx/vulkan/vk-transient-heap.h
index e41d760f2..8a0f7a74d 100644
--- a/tools/gfx/vulkan/vk-transient-heap.h
+++ b/tools/gfx/vulkan/vk-transient-heap.h
@@ -34,7 +34,7 @@ public:
public:
virtual SLANG_NO_THROW Result SLANG_MCALL
- createCommandBuffer(ICommandBuffer** outCommandBuffer) override;
+ createCommandBuffer(ICommandBuffer** outCommandBuffer) override;
virtual SLANG_NO_THROW Result SLANG_MCALL synchronizeAndReset() override;
};
diff --git a/tools/gfx/vulkan/vk-util.cpp b/tools/gfx/vulkan/vk-util.cpp
index 1a571c812..696e80fc7 100644
--- a/tools/gfx/vulkan/vk-util.cpp
+++ b/tools/gfx/vulkan/vk-util.cpp
@@ -1,121 +1,123 @@
// vk-util.cpp
#include "vk-util.h"
+
#include "core/slang-math.h"
-#include <stdlib.h>
#include <stdio.h>
+#include <stdlib.h>
-namespace gfx {
+namespace gfx
+{
-/* static */VkFormat VulkanUtil::getVkFormat(Format format)
+/* static */ VkFormat VulkanUtil::getVkFormat(Format format)
{
switch (format)
{
- case Format::R32G32B32A32_TYPELESS: return VK_FORMAT_R32G32B32A32_SFLOAT;
- case Format::R32G32B32_TYPELESS: return VK_FORMAT_R32G32B32_SFLOAT;
- case Format::R32G32_TYPELESS: return VK_FORMAT_R32G32_SFLOAT;
- case Format::R32_TYPELESS: return VK_FORMAT_R32_SFLOAT;
-
- case Format::R16G16B16A16_TYPELESS: return VK_FORMAT_R16G16B16A16_SFLOAT;
- case Format::R16G16_TYPELESS: return VK_FORMAT_R16G16_SFLOAT;
- case Format::R16_TYPELESS: return VK_FORMAT_R16_SFLOAT;
-
- case Format::R8G8B8A8_TYPELESS: return VK_FORMAT_R8G8B8A8_UNORM;
- case Format::R8G8_TYPELESS: return VK_FORMAT_R8G8_UNORM;
- case Format::R8_TYPELESS: return VK_FORMAT_R8_UNORM;
- case Format::B8G8R8A8_TYPELESS: return VK_FORMAT_B8G8R8A8_UNORM;
-
- case Format::R64_UINT: return VK_FORMAT_R64_UINT;
-
- case Format::R32G32B32A32_FLOAT: return VK_FORMAT_R32G32B32A32_SFLOAT;
- case Format::R32G32B32_FLOAT: return VK_FORMAT_R32G32B32_SFLOAT;
- case Format::R32G32_FLOAT: return VK_FORMAT_R32G32_SFLOAT;
- case Format::R32_FLOAT: return VK_FORMAT_R32_SFLOAT;
-
- case Format::R16G16B16A16_FLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT;
- case Format::R16G16_FLOAT: return VK_FORMAT_R16G16_SFLOAT;
- case Format::R16_FLOAT: return VK_FORMAT_R16_SFLOAT;
-
- case Format::R32G32B32A32_UINT: return VK_FORMAT_R32G32B32A32_UINT;
- case Format::R32G32B32_UINT: return VK_FORMAT_R32G32B32_UINT;
- case Format::R32G32_UINT: return VK_FORMAT_R32G32_UINT;
- case Format::R32_UINT: return VK_FORMAT_R32_UINT;
-
- case Format::R16G16B16A16_UINT: return VK_FORMAT_R16G16B16A16_UINT;
- case Format::R16G16_UINT: return VK_FORMAT_R16G16_UINT;
- case Format::R16_UINT: return VK_FORMAT_R16_UINT;
-
- case Format::R8G8B8A8_UINT: return VK_FORMAT_R8G8B8A8_UINT;
- case Format::R8G8_UINT: return VK_FORMAT_R8G8_UINT;
- case Format::R8_UINT: return VK_FORMAT_R8_UINT;
-
- case Format::R64_SINT: return VK_FORMAT_R64_SINT;
-
- case Format::R32G32B32A32_SINT: return VK_FORMAT_R32G32B32A32_SINT;
- case Format::R32G32B32_SINT: return VK_FORMAT_R32G32B32_SINT;
- case Format::R32G32_SINT: return VK_FORMAT_R32G32_SINT;
- case Format::R32_SINT: return VK_FORMAT_R32_SINT;
-
- case Format::R16G16B16A16_SINT: return VK_FORMAT_R16G16B16A16_SINT;
- case Format::R16G16_SINT: return VK_FORMAT_R16G16_SINT;
- case Format::R16_SINT: return VK_FORMAT_R16_SINT;
-
- case Format::R8G8B8A8_SINT: return VK_FORMAT_R8G8B8A8_SINT;
- case Format::R8G8_SINT: return VK_FORMAT_R8G8_SINT;
- case Format::R8_SINT: return VK_FORMAT_R8_SINT;
-
- case Format::R16G16B16A16_UNORM: return VK_FORMAT_R16G16B16A16_UNORM;
- case Format::R16G16_UNORM: return VK_FORMAT_R16G16_UNORM;
- case Format::R16_UNORM: return VK_FORMAT_R16_UNORM;
-
- case Format::R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM;
- case Format::R8G8B8A8_UNORM_SRGB: return VK_FORMAT_R8G8B8A8_SRGB;
- case Format::R8G8_UNORM: return VK_FORMAT_R8G8_UNORM;
- case Format::R8_UNORM: return VK_FORMAT_R8_UNORM;
- case Format::B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM;
- case Format::B8G8R8A8_UNORM_SRGB: return VK_FORMAT_B8G8R8A8_SRGB;
- case Format::B8G8R8X8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM;
- case Format::B8G8R8X8_UNORM_SRGB: return VK_FORMAT_B8G8R8A8_SRGB;
-
- case Format::R16G16B16A16_SNORM: return VK_FORMAT_R16G16B16A16_SNORM;
- case Format::R16G16_SNORM: return VK_FORMAT_R16G16_SNORM;
- case Format::R16_SNORM: return VK_FORMAT_R16_SNORM;
-
- case Format::R8G8B8A8_SNORM: return VK_FORMAT_R8G8B8A8_SNORM;
- case Format::R8G8_SNORM: return VK_FORMAT_R8G8_SNORM;
- case Format::R8_SNORM: return VK_FORMAT_R8_SNORM;
-
- case Format::D32_FLOAT: return VK_FORMAT_D32_SFLOAT;
- case Format::D16_UNORM: return VK_FORMAT_D16_UNORM;
- case Format::D32_FLOAT_S8_UINT: return VK_FORMAT_D32_SFLOAT_S8_UINT;
- case Format::R32_FLOAT_X32_TYPELESS: return VK_FORMAT_R32_SFLOAT;
-
- case Format::B4G4R4A4_UNORM: return VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT;
- case Format::B5G6R5_UNORM: return VK_FORMAT_R5G6B5_UNORM_PACK16;
- case Format::B5G5R5A1_UNORM: return VK_FORMAT_A1R5G5B5_UNORM_PACK16;
-
- case Format::R9G9B9E5_SHAREDEXP: return VK_FORMAT_E5B9G9R9_UFLOAT_PACK32;
- case Format::R10G10B10A2_TYPELESS: return VK_FORMAT_A2B10G10R10_UINT_PACK32;
- case Format::R10G10B10A2_UINT: return VK_FORMAT_A2B10G10R10_UINT_PACK32;
- case Format::R10G10B10A2_UNORM: return VK_FORMAT_A2B10G10R10_UNORM_PACK32;
- case Format::R11G11B10_FLOAT: return VK_FORMAT_B10G11R11_UFLOAT_PACK32;
-
- case Format::BC1_UNORM: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
- case Format::BC1_UNORM_SRGB: return VK_FORMAT_BC1_RGBA_SRGB_BLOCK;
- case Format::BC2_UNORM: return VK_FORMAT_BC2_UNORM_BLOCK;
- case Format::BC2_UNORM_SRGB: return VK_FORMAT_BC2_SRGB_BLOCK;
- case Format::BC3_UNORM: return VK_FORMAT_BC3_UNORM_BLOCK;
- case Format::BC3_UNORM_SRGB: return VK_FORMAT_BC3_SRGB_BLOCK;
- case Format::BC4_UNORM: return VK_FORMAT_BC4_UNORM_BLOCK;
- case Format::BC4_SNORM: return VK_FORMAT_BC4_SNORM_BLOCK;
- case Format::BC5_UNORM: return VK_FORMAT_BC5_UNORM_BLOCK;
- case Format::BC5_SNORM: return VK_FORMAT_BC5_SNORM_BLOCK;
- case Format::BC6H_UF16: return VK_FORMAT_BC6H_UFLOAT_BLOCK;
- case Format::BC6H_SF16: return VK_FORMAT_BC6H_SFLOAT_BLOCK;
- case Format::BC7_UNORM: return VK_FORMAT_BC7_UNORM_BLOCK;
- case Format::BC7_UNORM_SRGB: return VK_FORMAT_BC7_SRGB_BLOCK;
-
- default: return VK_FORMAT_UNDEFINED;
+ case Format::R32G32B32A32_TYPELESS: return VK_FORMAT_R32G32B32A32_SFLOAT;
+ case Format::R32G32B32_TYPELESS: return VK_FORMAT_R32G32B32_SFLOAT;
+ case Format::R32G32_TYPELESS: return VK_FORMAT_R32G32_SFLOAT;
+ case Format::R32_TYPELESS: return VK_FORMAT_R32_SFLOAT;
+
+ case Format::R16G16B16A16_TYPELESS: return VK_FORMAT_R16G16B16A16_SFLOAT;
+ case Format::R16G16_TYPELESS: return VK_FORMAT_R16G16_SFLOAT;
+ case Format::R16_TYPELESS: return VK_FORMAT_R16_SFLOAT;
+
+ case Format::R8G8B8A8_TYPELESS: return VK_FORMAT_R8G8B8A8_UNORM;
+ case Format::R8G8_TYPELESS: return VK_FORMAT_R8G8_UNORM;
+ case Format::R8_TYPELESS: return VK_FORMAT_R8_UNORM;
+ case Format::B8G8R8A8_TYPELESS: return VK_FORMAT_B8G8R8A8_UNORM;
+
+ case Format::R64_UINT: return VK_FORMAT_R64_UINT;
+
+ case Format::R32G32B32A32_FLOAT: return VK_FORMAT_R32G32B32A32_SFLOAT;
+ case Format::R32G32B32_FLOAT: return VK_FORMAT_R32G32B32_SFLOAT;
+ case Format::R32G32_FLOAT: return VK_FORMAT_R32G32_SFLOAT;
+ case Format::R32_FLOAT: return VK_FORMAT_R32_SFLOAT;
+
+ case Format::R16G16B16A16_FLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT;
+ case Format::R16G16_FLOAT: return VK_FORMAT_R16G16_SFLOAT;
+ case Format::R16_FLOAT: return VK_FORMAT_R16_SFLOAT;
+
+ case Format::R32G32B32A32_UINT: return VK_FORMAT_R32G32B32A32_UINT;
+ case Format::R32G32B32_UINT: return VK_FORMAT_R32G32B32_UINT;
+ case Format::R32G32_UINT: return VK_FORMAT_R32G32_UINT;
+ case Format::R32_UINT: return VK_FORMAT_R32_UINT;
+
+ case Format::R16G16B16A16_UINT: return VK_FORMAT_R16G16B16A16_UINT;
+ case Format::R16G16_UINT: return VK_FORMAT_R16G16_UINT;
+ case Format::R16_UINT: return VK_FORMAT_R16_UINT;
+
+ case Format::R8G8B8A8_UINT: return VK_FORMAT_R8G8B8A8_UINT;
+ case Format::R8G8_UINT: return VK_FORMAT_R8G8_UINT;
+ case Format::R8_UINT: return VK_FORMAT_R8_UINT;
+
+ case Format::R64_SINT: return VK_FORMAT_R64_SINT;
+
+ case Format::R32G32B32A32_SINT: return VK_FORMAT_R32G32B32A32_SINT;
+ case Format::R32G32B32_SINT: return VK_FORMAT_R32G32B32_SINT;
+ case Format::R32G32_SINT: return VK_FORMAT_R32G32_SINT;
+ case Format::R32_SINT: return VK_FORMAT_R32_SINT;
+
+ case Format::R16G16B16A16_SINT: return VK_FORMAT_R16G16B16A16_SINT;
+ case Format::R16G16_SINT: return VK_FORMAT_R16G16_SINT;
+ case Format::R16_SINT: return VK_FORMAT_R16_SINT;
+
+ case Format::R8G8B8A8_SINT: return VK_FORMAT_R8G8B8A8_SINT;
+ case Format::R8G8_SINT: return VK_FORMAT_R8G8_SINT;
+ case Format::R8_SINT: return VK_FORMAT_R8_SINT;
+
+ case Format::R16G16B16A16_UNORM: return VK_FORMAT_R16G16B16A16_UNORM;
+ case Format::R16G16_UNORM: return VK_FORMAT_R16G16_UNORM;
+ case Format::R16_UNORM: return VK_FORMAT_R16_UNORM;
+
+ case Format::R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM;
+ case Format::R8G8B8A8_UNORM_SRGB: return VK_FORMAT_R8G8B8A8_SRGB;
+ case Format::R8G8_UNORM: return VK_FORMAT_R8G8_UNORM;
+ case Format::R8_UNORM: return VK_FORMAT_R8_UNORM;
+ case Format::B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM;
+ case Format::B8G8R8A8_UNORM_SRGB: return VK_FORMAT_B8G8R8A8_SRGB;
+ case Format::B8G8R8X8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM;
+ case Format::B8G8R8X8_UNORM_SRGB: return VK_FORMAT_B8G8R8A8_SRGB;
+
+ case Format::R16G16B16A16_SNORM: return VK_FORMAT_R16G16B16A16_SNORM;
+ case Format::R16G16_SNORM: return VK_FORMAT_R16G16_SNORM;
+ case Format::R16_SNORM: return VK_FORMAT_R16_SNORM;
+
+ case Format::R8G8B8A8_SNORM: return VK_FORMAT_R8G8B8A8_SNORM;
+ case Format::R8G8_SNORM: return VK_FORMAT_R8G8_SNORM;
+ case Format::R8_SNORM: return VK_FORMAT_R8_SNORM;
+
+ case Format::D32_FLOAT: return VK_FORMAT_D32_SFLOAT;
+ case Format::D16_UNORM: return VK_FORMAT_D16_UNORM;
+ case Format::D32_FLOAT_S8_UINT: return VK_FORMAT_D32_SFLOAT_S8_UINT;
+ case Format::R32_FLOAT_X32_TYPELESS: return VK_FORMAT_R32_SFLOAT;
+
+ case Format::B4G4R4A4_UNORM: return VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT;
+ case Format::B5G6R5_UNORM: return VK_FORMAT_R5G6B5_UNORM_PACK16;
+ case Format::B5G5R5A1_UNORM: return VK_FORMAT_A1R5G5B5_UNORM_PACK16;
+
+ case Format::R9G9B9E5_SHAREDEXP: return VK_FORMAT_E5B9G9R9_UFLOAT_PACK32;
+ case Format::R10G10B10A2_TYPELESS: return VK_FORMAT_A2B10G10R10_UINT_PACK32;
+ case Format::R10G10B10A2_UINT: return VK_FORMAT_A2B10G10R10_UINT_PACK32;
+ case Format::R10G10B10A2_UNORM: return VK_FORMAT_A2B10G10R10_UNORM_PACK32;
+ case Format::R11G11B10_FLOAT: return VK_FORMAT_B10G11R11_UFLOAT_PACK32;
+
+ case Format::BC1_UNORM: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
+ case Format::BC1_UNORM_SRGB: return VK_FORMAT_BC1_RGBA_SRGB_BLOCK;
+ case Format::BC2_UNORM: return VK_FORMAT_BC2_UNORM_BLOCK;
+ case Format::BC2_UNORM_SRGB: return VK_FORMAT_BC2_SRGB_BLOCK;
+ case Format::BC3_UNORM: return VK_FORMAT_BC3_UNORM_BLOCK;
+ case Format::BC3_UNORM_SRGB: return VK_FORMAT_BC3_SRGB_BLOCK;
+ case Format::BC4_UNORM: return VK_FORMAT_BC4_UNORM_BLOCK;
+ case Format::BC4_SNORM: return VK_FORMAT_BC4_SNORM_BLOCK;
+ case Format::BC5_UNORM: return VK_FORMAT_BC5_UNORM_BLOCK;
+ case Format::BC5_SNORM: return VK_FORMAT_BC5_SNORM_BLOCK;
+ case Format::BC6H_UF16: return VK_FORMAT_BC6H_UFLOAT_BLOCK;
+ case Format::BC6H_SF16: return VK_FORMAT_BC6H_SFLOAT_BLOCK;
+ case Format::BC7_UNORM: return VK_FORMAT_BC7_UNORM_BLOCK;
+ case Format::BC7_UNORM_SRGB: return VK_FORMAT_BC7_SRGB_BLOCK;
+
+ default: return VK_FORMAT_UNDEFINED;
}
}
@@ -132,38 +134,26 @@ VkImageAspectFlags VulkanUtil::getAspectMask(TextureAspect aspect, VkFormat form
return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_D32_SFLOAT:
- case VK_FORMAT_X8_D24_UNORM_PACK32:
- return VK_IMAGE_ASPECT_DEPTH_BIT;
- case VK_FORMAT_S8_UINT:
- return VK_IMAGE_ASPECT_STENCIL_BIT;
- default:
- return VK_IMAGE_ASPECT_COLOR_BIT;
+ case VK_FORMAT_X8_D24_UNORM_PACK32: return VK_IMAGE_ASPECT_DEPTH_BIT;
+ case VK_FORMAT_S8_UINT: return VK_IMAGE_ASPECT_STENCIL_BIT;
+ default: return VK_IMAGE_ASPECT_COLOR_BIT;
}
- case TextureAspect::Color:
- return VK_IMAGE_ASPECT_COLOR_BIT;
- case TextureAspect::Depth:
- return VK_IMAGE_ASPECT_DEPTH_BIT;
+ case TextureAspect::Color: return VK_IMAGE_ASPECT_COLOR_BIT;
+ case TextureAspect::Depth: return VK_IMAGE_ASPECT_DEPTH_BIT;
case TextureAspect::DepthStencil:
return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
- case TextureAspect::Stencil:
- return VK_IMAGE_ASPECT_STENCIL_BIT;
- case TextureAspect::Plane0:
- return VK_IMAGE_ASPECT_PLANE_0_BIT;
- case TextureAspect::Plane1:
- return VK_IMAGE_ASPECT_PLANE_1_BIT;
-
- case TextureAspect::Plane2:
- return VK_IMAGE_ASPECT_PLANE_2_BIT;
-
- case TextureAspect::MetaData:
- return VK_IMAGE_ASPECT_METADATA_BIT;
- default:
- SLANG_UNREACHABLE("getAspectMask");
- return 0;
+ case TextureAspect::Stencil: return VK_IMAGE_ASPECT_STENCIL_BIT;
+ case TextureAspect::Plane0: return VK_IMAGE_ASPECT_PLANE_0_BIT;
+ case TextureAspect::Plane1: return VK_IMAGE_ASPECT_PLANE_1_BIT;
+
+ case TextureAspect::Plane2: return VK_IMAGE_ASPECT_PLANE_2_BIT;
+
+ case TextureAspect::MetaData: return VK_IMAGE_ASPECT_METADATA_BIT;
+ default: SLANG_UNREACHABLE("getAspectMask"); return 0;
}
}
-/* static */SlangResult VulkanUtil::toSlangResult(VkResult res)
+/* static */ SlangResult VulkanUtil::toSlangResult(VkResult res)
{
return (res == VK_SUCCESS) ? SLANG_OK : SLANG_FAIL;
}
@@ -172,37 +162,21 @@ VkShaderStageFlags VulkanUtil::getShaderStage(SlangStage stage)
{
switch (stage)
{
- case SLANG_STAGE_ANY_HIT:
- return VK_SHADER_STAGE_ANY_HIT_BIT_KHR;
- case SLANG_STAGE_CALLABLE:
- return VK_SHADER_STAGE_CALLABLE_BIT_KHR;
- case SLANG_STAGE_CLOSEST_HIT:
- return VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR;
- case SLANG_STAGE_COMPUTE:
- return VK_SHADER_STAGE_COMPUTE_BIT;
- case SLANG_STAGE_DOMAIN:
- return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
- case SLANG_STAGE_FRAGMENT:
- return VK_SHADER_STAGE_FRAGMENT_BIT;
- case SLANG_STAGE_GEOMETRY:
- return VK_SHADER_STAGE_GEOMETRY_BIT;
- case SLANG_STAGE_HULL:
- return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
- case SLANG_STAGE_INTERSECTION:
- return VK_SHADER_STAGE_INTERSECTION_BIT_KHR;
- case SLANG_STAGE_MISS:
- return VK_SHADER_STAGE_MISS_BIT_KHR;
- case SLANG_STAGE_RAY_GENERATION:
- return VK_SHADER_STAGE_RAYGEN_BIT_KHR;
- case SLANG_STAGE_VERTEX:
- return VK_SHADER_STAGE_VERTEX_BIT;
- case SLANG_STAGE_MESH:
- return VK_SHADER_STAGE_MESH_BIT_EXT;
- case SLANG_STAGE_AMPLIFICATION:
- return VK_SHADER_STAGE_TASK_BIT_EXT;
- default:
- assert(!"unsupported stage.");
- return VkShaderStageFlags(-1);
+ case SLANG_STAGE_ANY_HIT: return VK_SHADER_STAGE_ANY_HIT_BIT_KHR;
+ case SLANG_STAGE_CALLABLE: return VK_SHADER_STAGE_CALLABLE_BIT_KHR;
+ case SLANG_STAGE_CLOSEST_HIT: return VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR;
+ case SLANG_STAGE_COMPUTE: return VK_SHADER_STAGE_COMPUTE_BIT;
+ case SLANG_STAGE_DOMAIN: return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
+ case SLANG_STAGE_FRAGMENT: return VK_SHADER_STAGE_FRAGMENT_BIT;
+ case SLANG_STAGE_GEOMETRY: return VK_SHADER_STAGE_GEOMETRY_BIT;
+ case SLANG_STAGE_HULL: return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
+ case SLANG_STAGE_INTERSECTION: return VK_SHADER_STAGE_INTERSECTION_BIT_KHR;
+ case SLANG_STAGE_MISS: return VK_SHADER_STAGE_MISS_BIT_KHR;
+ case SLANG_STAGE_RAY_GENERATION: return VK_SHADER_STAGE_RAYGEN_BIT_KHR;
+ case SLANG_STAGE_VERTEX: return VK_SHADER_STAGE_VERTEX_BIT;
+ case SLANG_STAGE_MESH: return VK_SHADER_STAGE_MESH_BIT_EXT;
+ case SLANG_STAGE_AMPLIFICATION: return VK_SHADER_STAGE_TASK_BIT_EXT;
+ default: assert(!"unsupported stage."); return VkShaderStageFlags(-1);
}
}
@@ -212,29 +186,18 @@ VkImageLayout VulkanUtil::getImageLayoutFromState(ResourceState state)
{
case ResourceState::ShaderResource:
case ResourceState::PixelShaderResource:
- case ResourceState::NonPixelShaderResource:
- return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
+ case ResourceState::NonPixelShaderResource: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
case ResourceState::UnorderedAccess:
- case ResourceState::General:
- return VK_IMAGE_LAYOUT_GENERAL;
- case ResourceState::Present:
- return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
- case ResourceState::CopySource:
- return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
- case ResourceState::CopyDestination:
- return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
- case ResourceState::RenderTarget:
- return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
- case ResourceState::DepthWrite:
- return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
- case ResourceState::DepthRead:
- return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
- case ResourceState::ResolveSource:
- return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
- case ResourceState::ResolveDestination:
- return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
- default:
- return VK_IMAGE_LAYOUT_UNDEFINED;
+ case ResourceState::General: return VK_IMAGE_LAYOUT_GENERAL;
+ case ResourceState::Present: return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
+ case ResourceState::CopySource: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
+ case ResourceState::CopyDestination: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+ case ResourceState::RenderTarget: return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
+ case ResourceState::DepthWrite: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
+ case ResourceState::DepthRead: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
+ case ResourceState::ResolveSource: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
+ case ResourceState::ResolveDestination: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+ default: return VK_IMAGE_LAYOUT_UNDEFINED;
}
return VkImageLayout();
}
@@ -243,23 +206,14 @@ VkSampleCountFlagBits VulkanUtil::translateSampleCount(uint32_t sampleCount)
{
switch (sampleCount)
{
- case 1:
- return VK_SAMPLE_COUNT_1_BIT;
- case 2:
- return VK_SAMPLE_COUNT_2_BIT;
- case 4:
- return VK_SAMPLE_COUNT_4_BIT;
- case 8:
- return VK_SAMPLE_COUNT_8_BIT;
- case 16:
- return VK_SAMPLE_COUNT_16_BIT;
- case 32:
- return VK_SAMPLE_COUNT_32_BIT;
- case 64:
- return VK_SAMPLE_COUNT_64_BIT;
- default:
- assert(!"Unsupported sample count");
- return VK_SAMPLE_COUNT_1_BIT;
+ case 1: return VK_SAMPLE_COUNT_1_BIT;
+ case 2: return VK_SAMPLE_COUNT_2_BIT;
+ case 4: return VK_SAMPLE_COUNT_4_BIT;
+ case 8: return VK_SAMPLE_COUNT_8_BIT;
+ case 16: return VK_SAMPLE_COUNT_16_BIT;
+ case 32: return VK_SAMPLE_COUNT_32_BIT;
+ case 64: return VK_SAMPLE_COUNT_64_BIT;
+ default: assert(!"Unsupported sample count"); return VK_SAMPLE_COUNT_1_BIT;
}
}
@@ -267,15 +221,10 @@ VkCullModeFlags VulkanUtil::translateCullMode(CullMode cullMode)
{
switch (cullMode)
{
- case CullMode::None:
- return VK_CULL_MODE_NONE;
- case CullMode::Front:
- return VK_CULL_MODE_FRONT_BIT;
- case CullMode::Back:
- return VK_CULL_MODE_BACK_BIT;
- default:
- assert(!"Unsupported cull mode");
- return VK_CULL_MODE_NONE;
+ case CullMode::None: return VK_CULL_MODE_NONE;
+ case CullMode::Front: return VK_CULL_MODE_FRONT_BIT;
+ case CullMode::Back: return VK_CULL_MODE_BACK_BIT;
+ default: assert(!"Unsupported cull mode"); return VK_CULL_MODE_NONE;
}
}
@@ -283,13 +232,9 @@ VkFrontFace VulkanUtil::translateFrontFaceMode(FrontFaceMode frontFaceMode)
{
switch (frontFaceMode)
{
- case FrontFaceMode::CounterClockwise:
- return VK_FRONT_FACE_COUNTER_CLOCKWISE;
- case FrontFaceMode::Clockwise:
- return VK_FRONT_FACE_CLOCKWISE;
- default:
- assert(!"Unsupported front face mode");
- return VK_FRONT_FACE_CLOCKWISE;
+ case FrontFaceMode::CounterClockwise: return VK_FRONT_FACE_COUNTER_CLOCKWISE;
+ case FrontFaceMode::Clockwise: return VK_FRONT_FACE_CLOCKWISE;
+ default: assert(!"Unsupported front face mode"); return VK_FRONT_FACE_CLOCKWISE;
}
}
@@ -297,13 +242,9 @@ VkPolygonMode VulkanUtil::translateFillMode(FillMode fillMode)
{
switch (fillMode)
{
- case FillMode::Solid:
- return VK_POLYGON_MODE_FILL;
- case FillMode::Wireframe:
- return VK_POLYGON_MODE_LINE;
- default:
- assert(!"Unsupported fill mode");
- return VK_POLYGON_MODE_FILL;
+ case FillMode::Solid: return VK_POLYGON_MODE_FILL;
+ case FillMode::Wireframe: return VK_POLYGON_MODE_LINE;
+ default: assert(!"Unsupported fill mode"); return VK_POLYGON_MODE_FILL;
}
}
@@ -311,44 +252,25 @@ VkBlendFactor VulkanUtil::translateBlendFactor(BlendFactor blendFactor)
{
switch (blendFactor)
{
- case BlendFactor::Zero:
- return VK_BLEND_FACTOR_ZERO;
- case BlendFactor::One:
- return VK_BLEND_FACTOR_ONE;
- case BlendFactor::SrcColor:
- return VK_BLEND_FACTOR_SRC_COLOR;
- case BlendFactor::InvSrcColor:
- return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
- case BlendFactor::SrcAlpha:
- return VK_BLEND_FACTOR_SRC_ALPHA;
- case BlendFactor::InvSrcAlpha:
- return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
- case BlendFactor::DestAlpha:
- return VK_BLEND_FACTOR_DST_ALPHA;
- case BlendFactor::InvDestAlpha:
- return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
- case BlendFactor::DestColor:
- return VK_BLEND_FACTOR_DST_COLOR;
- case BlendFactor::InvDestColor:
- return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
- case BlendFactor::SrcAlphaSaturate:
- return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE;
- case BlendFactor::BlendColor:
- return VK_BLEND_FACTOR_CONSTANT_COLOR;
- case BlendFactor::InvBlendColor:
- return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR;
- case BlendFactor::SecondarySrcColor:
- return VK_BLEND_FACTOR_SRC1_COLOR;
- case BlendFactor::InvSecondarySrcColor:
- return VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR;
- case BlendFactor::SecondarySrcAlpha:
- return VK_BLEND_FACTOR_SRC1_ALPHA;
- case BlendFactor::InvSecondarySrcAlpha:
- return VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
-
- default:
- assert(!"Unsupported blend factor");
- return VK_BLEND_FACTOR_ONE;
+ case BlendFactor::Zero: return VK_BLEND_FACTOR_ZERO;
+ case BlendFactor::One: return VK_BLEND_FACTOR_ONE;
+ case BlendFactor::SrcColor: return VK_BLEND_FACTOR_SRC_COLOR;
+ case BlendFactor::InvSrcColor: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
+ case BlendFactor::SrcAlpha: return VK_BLEND_FACTOR_SRC_ALPHA;
+ case BlendFactor::InvSrcAlpha: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
+ case BlendFactor::DestAlpha: return VK_BLEND_FACTOR_DST_ALPHA;
+ case BlendFactor::InvDestAlpha: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
+ case BlendFactor::DestColor: return VK_BLEND_FACTOR_DST_COLOR;
+ case BlendFactor::InvDestColor: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
+ case BlendFactor::SrcAlphaSaturate: return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE;
+ case BlendFactor::BlendColor: return VK_BLEND_FACTOR_CONSTANT_COLOR;
+ case BlendFactor::InvBlendColor: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR;
+ case BlendFactor::SecondarySrcColor: return VK_BLEND_FACTOR_SRC1_COLOR;
+ case BlendFactor::InvSecondarySrcColor: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR;
+ case BlendFactor::SecondarySrcAlpha: return VK_BLEND_FACTOR_SRC1_ALPHA;
+ case BlendFactor::InvSecondarySrcAlpha: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
+
+ default: assert(!"Unsupported blend factor"); return VK_BLEND_FACTOR_ONE;
}
}
@@ -356,38 +278,24 @@ VkBlendOp VulkanUtil::translateBlendOp(BlendOp op)
{
switch (op)
{
- case BlendOp::Add:
- return VK_BLEND_OP_ADD;
- case BlendOp::Subtract:
- return VK_BLEND_OP_SUBTRACT;
- case BlendOp::ReverseSubtract:
- return VK_BLEND_OP_REVERSE_SUBTRACT;
- case BlendOp::Min:
- return VK_BLEND_OP_MIN;
- case BlendOp::Max:
- return VK_BLEND_OP_MAX;
- default:
- assert(!"Unsupported blend op");
- return VK_BLEND_OP_ADD;
+ case BlendOp::Add: return VK_BLEND_OP_ADD;
+ case BlendOp::Subtract: return VK_BLEND_OP_SUBTRACT;
+ case BlendOp::ReverseSubtract: return VK_BLEND_OP_REVERSE_SUBTRACT;
+ case BlendOp::Min: return VK_BLEND_OP_MIN;
+ case BlendOp::Max: return VK_BLEND_OP_MAX;
+ default: assert(!"Unsupported blend op"); return VK_BLEND_OP_ADD;
}
}
-VkPrimitiveTopology VulkanUtil::translatePrimitiveTypeToListTopology(
- PrimitiveType primitiveType)
+VkPrimitiveTopology VulkanUtil::translatePrimitiveTypeToListTopology(PrimitiveType primitiveType)
{
switch (primitiveType)
{
- case PrimitiveType::Point:
- return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
- case PrimitiveType::Line:
- return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
- case PrimitiveType::Triangle:
- return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
- case PrimitiveType::Patch:
- return VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
- default:
- assert(!"unknown topology type.");
- return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
+ case PrimitiveType::Point: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
+ case PrimitiveType::Line: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
+ case PrimitiveType::Triangle: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
+ case PrimitiveType::Patch: return VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
+ default: assert(!"unknown topology type."); return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
}
}
@@ -395,24 +303,15 @@ VkStencilOp VulkanUtil::translateStencilOp(StencilOp op)
{
switch (op)
{
- case StencilOp::DecrementSaturate:
- return VK_STENCIL_OP_DECREMENT_AND_CLAMP;
- case StencilOp::DecrementWrap:
- return VK_STENCIL_OP_DECREMENT_AND_WRAP;
- case StencilOp::IncrementSaturate:
- return VK_STENCIL_OP_INCREMENT_AND_CLAMP;
- case StencilOp::IncrementWrap:
- return VK_STENCIL_OP_INCREMENT_AND_WRAP;
- case StencilOp::Invert:
- return VK_STENCIL_OP_INVERT;
- case StencilOp::Keep:
- return VK_STENCIL_OP_KEEP;
- case StencilOp::Replace:
- return VK_STENCIL_OP_REPLACE;
- case StencilOp::Zero:
- return VK_STENCIL_OP_ZERO;
- default:
- return VK_STENCIL_OP_KEEP;
+ case StencilOp::DecrementSaturate: return VK_STENCIL_OP_DECREMENT_AND_CLAMP;
+ case StencilOp::DecrementWrap: return VK_STENCIL_OP_DECREMENT_AND_WRAP;
+ case StencilOp::IncrementSaturate: return VK_STENCIL_OP_INCREMENT_AND_CLAMP;
+ case StencilOp::IncrementWrap: return VK_STENCIL_OP_INCREMENT_AND_WRAP;
+ case StencilOp::Invert: return VK_STENCIL_OP_INVERT;
+ case StencilOp::Keep: return VK_STENCIL_OP_KEEP;
+ case StencilOp::Replace: return VK_STENCIL_OP_REPLACE;
+ case StencilOp::Zero: return VK_STENCIL_OP_ZERO;
+ default: return VK_STENCIL_OP_KEEP;
}
}
@@ -420,12 +319,10 @@ VkFilter VulkanUtil::translateFilterMode(TextureFilteringMode mode)
{
switch (mode)
{
- default:
- return VkFilter(0);
+ default: return VkFilter(0);
-#define CASE(SRC, DST) \
- case TextureFilteringMode::SRC: \
- return VK_FILTER_##DST
+#define CASE(SRC, DST) \
+ case TextureFilteringMode::SRC: return VK_FILTER_##DST
CASE(Point, NEAREST);
CASE(Linear, LINEAR);
@@ -438,12 +335,10 @@ VkSamplerMipmapMode VulkanUtil::translateMipFilterMode(TextureFilteringMode mode
{
switch (mode)
{
- default:
- return VkSamplerMipmapMode(0);
+ default: return VkSamplerMipmapMode(0);
-#define CASE(SRC, DST) \
- case TextureFilteringMode::SRC: \
- return VK_SAMPLER_MIPMAP_MODE_##DST
+#define CASE(SRC, DST) \
+ case TextureFilteringMode::SRC: return VK_SAMPLER_MIPMAP_MODE_##DST
CASE(Point, NEAREST);
CASE(Linear, LINEAR);
@@ -456,12 +351,10 @@ VkSamplerAddressMode VulkanUtil::translateAddressingMode(TextureAddressingMode m
{
switch (mode)
{
- default:
- return VkSamplerAddressMode(0);
+ default: return VkSamplerAddressMode(0);
-#define CASE(SRC, DST) \
- case TextureAddressingMode::SRC: \
- return VK_SAMPLER_ADDRESS_MODE_##DST
+#define CASE(SRC, DST) \
+ case TextureAddressingMode::SRC: return VK_SAMPLER_ADDRESS_MODE_##DST
CASE(Wrap, REPEAT);
CASE(ClampToEdge, CLAMP_TO_EDGE);
@@ -481,9 +374,8 @@ VkCompareOp VulkanUtil::translateComparisonFunc(ComparisonFunc func)
// TODO: need to report failures
return VK_COMPARE_OP_ALWAYS;
-#define CASE(FROM, TO) \
- case ComparisonFunc::FROM: \
- return VK_COMPARE_OP_##TO
+#define CASE(FROM, TO) \
+ case ComparisonFunc::FROM: return VK_COMPARE_OP_##TO
CASE(Never, NEVER);
CASE(Less, LESS);
@@ -514,16 +406,13 @@ VkSamplerReductionMode VulkanUtil::translateReductionOp(TextureReductionOp op)
{
switch (op)
{
- case gfx::TextureReductionOp::Minimum:
- return VK_SAMPLER_REDUCTION_MODE_MIN;
- case gfx::TextureReductionOp::Maximum:
- return VK_SAMPLER_REDUCTION_MODE_MAX;
- default:
- return VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE;
+ case gfx::TextureReductionOp::Minimum: return VK_SAMPLER_REDUCTION_MODE_MIN;
+ case gfx::TextureReductionOp::Maximum: return VK_SAMPLER_REDUCTION_MODE_MAX;
+ default: return VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE;
}
}
-/* static */Slang::Result VulkanUtil::handleFail(VkResult res)
+/* static */ Slang::Result VulkanUtil::handleFail(VkResult res)
{
if (res != VK_SUCCESS)
{
@@ -532,29 +421,22 @@ VkSamplerReductionMode VulkanUtil::translateReductionOp(TextureReductionOp op)
return toSlangResult(res);
}
-/* static */void VulkanUtil::checkFail(VkResult res)
+/* static */ void VulkanUtil::checkFail(VkResult res)
{
assert(res != VK_SUCCESS);
assert(!"Vulkan check failed");
-
}
-/* static */VkPrimitiveTopology VulkanUtil::getVkPrimitiveTopology(PrimitiveTopology topology)
+/* static */ VkPrimitiveTopology VulkanUtil::getVkPrimitiveTopology(PrimitiveTopology topology)
{
switch (topology)
{
- case PrimitiveTopology::LineList:
- return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
- case PrimitiveTopology::LineStrip:
- return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
- case PrimitiveTopology::TriangleList:
- return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
- case PrimitiveTopology::TriangleStrip:
- return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
- case PrimitiveTopology::PointList:
- return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
- default:
- break;
+ case PrimitiveTopology::LineList: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
+ case PrimitiveTopology::LineStrip: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
+ case PrimitiveTopology::TriangleList: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
+ case PrimitiveTopology::TriangleStrip: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
+ case PrimitiveTopology::PointList: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
+ default: break;
}
assert(!"Unknown topology");
return VK_PRIMITIVE_TOPOLOGY_MAX_ENUM;
@@ -564,32 +446,20 @@ VkImageLayout VulkanUtil::mapResourceStateToLayout(ResourceState state)
{
switch (state)
{
- case ResourceState::Undefined:
- return VK_IMAGE_LAYOUT_UNDEFINED;
+ case ResourceState::Undefined: return VK_IMAGE_LAYOUT_UNDEFINED;
case ResourceState::ShaderResource:
case ResourceState::PixelShaderResource:
- case ResourceState::NonPixelShaderResource:
- return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
- case ResourceState::UnorderedAccess:
- return VK_IMAGE_LAYOUT_GENERAL;
- case ResourceState::RenderTarget:
- return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
- case ResourceState::DepthRead:
- return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
- case ResourceState::DepthWrite:
- return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
- case ResourceState::Present:
- return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
- case ResourceState::CopySource:
- return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
- case ResourceState::CopyDestination:
- return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
- case ResourceState::ResolveSource:
- return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
- case ResourceState::ResolveDestination:
- return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
- default:
- return VK_IMAGE_LAYOUT_UNDEFINED;
+ case ResourceState::NonPixelShaderResource: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
+ case ResourceState::UnorderedAccess: return VK_IMAGE_LAYOUT_GENERAL;
+ case ResourceState::RenderTarget: return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
+ case ResourceState::DepthRead: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
+ case ResourceState::DepthWrite: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
+ case ResourceState::Present: return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
+ case ResourceState::CopySource: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
+ case ResourceState::CopyDestination: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+ case ResourceState::ResolveSource: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
+ case ResourceState::ResolveDestination: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+ default: return VK_IMAGE_LAYOUT_UNDEFINED;
}
}
@@ -676,12 +546,8 @@ Result AccelerationStructureBuildGeometryInfoBuilder::build(
vkGeomData.triangles.maxVertex = geomDesc.content.triangles.vertexCount - 1;
switch (geomDesc.content.triangles.indexFormat)
{
- case Format::R32_UINT:
- vkGeomData.triangles.indexType = VK_INDEX_TYPE_UINT32;
- break;
- case Format::R16_UINT:
- vkGeomData.triangles.indexType = VK_INDEX_TYPE_UINT16;
- break;
+ case Format::R32_UINT: vkGeomData.triangles.indexType = VK_INDEX_TYPE_UINT32; break;
+ case Format::R16_UINT: vkGeomData.triangles.indexType = VK_INDEX_TYPE_UINT16; break;
case Format::Unknown:
vkGeomData.triangles.indexType = VK_INDEX_TYPE_NONE_KHR;
break;
diff --git a/tools/gfx/vulkan/vk-util.h b/tools/gfx/vulkan/vk-util.h
index ade62ba59..a22c76fc3 100644
--- a/tools/gfx/vulkan/vk-util.h
+++ b/tools/gfx/vulkan/vk-util.h
@@ -2,44 +2,69 @@
#pragma once
#include "core/slang-basic.h"
-#include "vk-api.h"
#include "slang-gfx.h"
+#include "vk-api.h"
// Macros to make testing vulkan return codes simpler
-/// SLANG_VK_RETURN_ON_FAIL can be used in a similar way to SLANG_RETURN_ON_FAIL macro, except it will turn a vulkan failure into Slang::Result in the process
-/// Calls handleFail which on debug builds asserts
-#define SLANG_VK_RETURN_ON_FAIL(x) { VkResult _res = x; if (_res != VK_SUCCESS) { return VulkanUtil::handleFail(_res); } }
+/// SLANG_VK_RETURN_ON_FAIL can be used in a similar way to SLANG_RETURN_ON_FAIL macro, except it
+/// will turn a vulkan failure into Slang::Result in the process Calls handleFail which on debug
+/// builds asserts
+#define SLANG_VK_RETURN_ON_FAIL(x) \
+ { \
+ VkResult _res = x; \
+ if (_res != VK_SUCCESS) \
+ { \
+ return VulkanUtil::handleFail(_res); \
+ } \
+ }
-#define SLANG_VK_RETURN_NULL_ON_FAIL(x) { VkResult _res = x; if (_res != VK_SUCCESS) { VulkanUtil::handleFail(_res); return nullptr; } }
+#define SLANG_VK_RETURN_NULL_ON_FAIL(x) \
+ { \
+ VkResult _res = x; \
+ if (_res != VK_SUCCESS) \
+ { \
+ VulkanUtil::handleFail(_res); \
+ return nullptr; \
+ } \
+ }
-/// Is similar to SLANG_VK_RETURN_ON_FAIL, but does not return. Will call checkFail on failure - which asserts on debug builds.
-#define SLANG_VK_CHECK(x) { VkResult _res = x; if (_res != VK_SUCCESS) { VulkanUtil::checkFail(_res); } }
+/// Is similar to SLANG_VK_RETURN_ON_FAIL, but does not return. Will call checkFail on failure -
+/// which asserts on debug builds.
+#define SLANG_VK_CHECK(x) \
+ { \
+ VkResult _res = x; \
+ if (_res != VK_SUCCESS) \
+ { \
+ VulkanUtil::checkFail(_res); \
+ } \
+ }
-namespace gfx {
+namespace gfx
+{
// Utility functions for Vulkan
struct VulkanUtil
{
- /// Get the equivalent VkFormat from the format
- /// Returns VK_FORMAT_UNDEFINED if a match is not found
+ /// Get the equivalent VkFormat from the format
+ /// Returns VK_FORMAT_UNDEFINED if a match is not found
static VkFormat getVkFormat(Format format);
static VkImageAspectFlags getAspectMask(TextureAspect aspect, VkFormat format);
- /// Called by SLANG_VK_RETURN_FAIL if a res is a failure.
- /// On debug builds this will cause an assertion on failure.
+ /// Called by SLANG_VK_RETURN_FAIL if a res is a failure.
+ /// On debug builds this will cause an assertion on failure.
static Slang::Result handleFail(VkResult res);
- /// Called when a failure has occurred with SLANG_VK_CHECK - will typically assert.
+ /// Called when a failure has occurred with SLANG_VK_CHECK - will typically assert.
static void checkFail(VkResult res);
- /// Get the VkPrimitiveTopology for the given topology.
- /// Returns VK_PRIMITIVE_TOPOLOGY_MAX_ENUM on failure
+ /// Get the VkPrimitiveTopology for the given topology.
+ /// Returns VK_PRIMITIVE_TOPOLOGY_MAX_ENUM on failure
static VkPrimitiveTopology getVkPrimitiveTopology(PrimitiveTopology topology);
static VkImageLayout mapResourceStateToLayout(ResourceState state);
- /// Returns Slang::Result equivalent of a VkResult
+ /// Returns Slang::Result equivalent of a VkResult
static Slang::Result toSlangResult(VkResult res);
static VkShaderStageFlags getShaderStage(SlangStage stage);
@@ -47,7 +72,10 @@ struct VulkanUtil
static VkImageLayout getImageLayoutFromState(ResourceState state);
/// Calculate size taking into account alignment. Alignment must be a power of 2
- static UInt calcAligned(UInt size, UInt alignment) { return (size + alignment - 1) & ~(alignment - 1); }
+ static UInt calcAligned(UInt size, UInt alignment)
+ {
+ return (size + alignment - 1) & ~(alignment - 1);
+ }
static inline bool isDepthFormat(VkFormat format)
{
@@ -57,8 +85,7 @@ struct VulkanUtil
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_X8_D24_UNORM_PACK32:
case VK_FORMAT_D32_SFLOAT:
- case VK_FORMAT_D32_SFLOAT_S8_UINT:
- return true;
+ case VK_FORMAT_D32_SFLOAT_S8_UINT: return true;
}
return false;
}
@@ -69,8 +96,7 @@ struct VulkanUtil
{
case VK_FORMAT_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
- case VK_FORMAT_D32_SFLOAT_S8_UINT:
- return true;
+ case VK_FORMAT_D32_SFLOAT_S8_UINT: return true;
}
return false;
}
@@ -87,11 +113,10 @@ struct VulkanUtil
static VkBlendOp translateBlendOp(BlendOp op);
- static VkPrimitiveTopology translatePrimitiveTypeToListTopology(
- PrimitiveType primitiveType);
+ static VkPrimitiveTopology translatePrimitiveTypeToListTopology(PrimitiveType primitiveType);
static VkStencilOp translateStencilOp(StencilOp op);
-
+
static VkFilter translateFilterMode(TextureFilteringMode mode);
static VkSamplerMipmapMode translateMipFilterMode(TextureFilteringMode mode);
@@ -103,7 +128,6 @@ struct VulkanUtil
static VkStencilOpState translateStencilState(DepthStencilOpDesc desc);
static VkSamplerReductionMode translateReductionOp(TextureReductionOp op);
-
};
struct AccelerationStructureBuildGeometryInfoBuilder
@@ -124,4 +148,4 @@ private:
};
-} // renderer_test
+} // namespace gfx
diff --git a/tools/platform/gui.cpp b/tools/platform/gui.cpp
index b1cb59517..15d683ec8 100644
--- a/tools/platform/gui.cpp
+++ b/tools/platform/gui.cpp
@@ -2,9 +2,10 @@
#include "gui.h"
#ifdef _WIN32
-#include <windows.h>
#include <examples/imgui_impl_win32.h>
-IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+#include <windows.h>
+IMGUI_IMPL_API LRESULT
+ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
#endif
using namespace gfx;
@@ -16,19 +17,22 @@ namespace platform
LRESULT CALLBACK guiWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT handled = ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam);
- if(handled) return handled;
+ if (handled)
+ return handled;
ImGuiIO& io = ImGui::GetIO();
- switch( msg )
+ switch (msg)
{
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
- if(io.WantCaptureMouse) handled = 1;
+ if (io.WantCaptureMouse)
+ handled = 1;
break;
case WM_KEYDOWN:
case WM_KEYUP:
- if(io.WantCaptureKeyboard) handled = 1;
+ if (io.WantCaptureKeyboard)
+ handled = 1;
break;
}
@@ -42,14 +46,13 @@ GUI::GUI(
IDevice* inDevice,
ICommandQueue* inQueue,
IFramebufferLayout* framebufferLayout)
- : device(inDevice)
- , queue(inQueue)
+ : device(inDevice), queue(inQueue)
{
- ImGui::CreateContext();
- ImGuiIO& io = ImGui::GetIO();
+ ImGui::CreateContext();
+ ImGuiIO& io = ImGui::GetIO();
#ifdef _WIN32
- ImGui_ImplWin32_Init((HWND)window->getNativeHandle().handleValues[0]);
+ ImGui_ImplWin32_Init((HWND)window->getNativeHandle().handleValues[0]);
#endif
// Let's do the initialization work required for our graphics API
@@ -57,8 +60,7 @@ GUI::GUI(
// through the same interface as other work.
//
- static const char* shaderCode =
- "cbuffer U { float4x4 mvp; }; \
+ static const char* shaderCode = "cbuffer U { float4x4 mvp; }; \
Texture2D t; \
SamplerState s; \
struct AssembledVertex { \
@@ -102,9 +104,9 @@ GUI::GUI(
program = device->createProgram(programDesc);
#endif
InputElementDesc inputElements[] = {
- {"U", 0, Format::R32G32_FLOAT, offsetof(ImDrawVert, pos) },
- {"U", 1, Format::R32G32_FLOAT, offsetof(ImDrawVert, uv) },
- {"U", 2, Format::R8G8B8A8_UNORM, offsetof(ImDrawVert, col) },
+ {"U", 0, Format::R32G32_FLOAT, offsetof(ImDrawVert, pos)},
+ {"U", 1, Format::R32G32_FLOAT, offsetof(ImDrawVert, uv)},
+ {"U", 2, Format::R8G8B8A8_UNORM, offsetof(ImDrawVert, col)},
};
auto inputLayout = device->createInputLayout(
sizeof(ImDrawVert),
@@ -163,7 +165,7 @@ GUI::GUI(
viewDesc.type = IResourceView::Type::ShaderResource;
auto textureView = device->createTextureView(texture, viewDesc);
- io.Fonts->TexID = (void*) textureView.detach();
+ io.Fonts->TexID = (void*)textureView.detach();
}
{
@@ -187,7 +189,6 @@ GUI::GUI(
}
-
void GUI::beginFrame()
{
#ifdef _WIN32
@@ -205,9 +206,12 @@ void GUI::endFrame(ITransientResourceHeap* transientHeap, IFramebuffer* framebuf
auto indexCount = draw_data->TotalIdxCount;
int commandListCount = draw_data->CmdListsCount;
- if(!vertexCount) return;
- if(!indexCount) return;
- if(!commandListCount) return;
+ if (!vertexCount)
+ return;
+ if (!indexCount)
+ return;
+ if (!commandListCount)
+ return;
// Allocate transient vertex/index buffers to hold the data for this frame.
@@ -231,7 +235,7 @@ void GUI::endFrame(ITransientResourceHeap* transientHeap, IFramebuffer* framebuf
auto cmdBuf = transientHeap->createCommandBuffer();
auto encoder = cmdBuf->encodeResourceCommands();
{
- for(int ii = 0; ii < commandListCount; ++ii)
+ for (int ii = 0; ii < commandListCount; ++ii)
{
const ImDrawList* commandList = draw_data->CmdLists[ii];
encoder->uploadBufferData(
@@ -262,12 +266,11 @@ void GUI::endFrame(ITransientResourceHeap* transientHeap, IFramebuffer* framebuf
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
- float mvp[4][4] =
- {
- { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
- { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
- { 0.0f, 0.0f, 0.5f, 0.0f },
- { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
+ float mvp[4][4] = {
+ {2.0f / (R - L), 0.0f, 0.0f, 0.0f},
+ {0.0f, 2.0f / (T - B), 0.0f, 0.0f},
+ {0.0f, 0.0f, 0.5f, 0.0f},
+ {(R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f},
};
encoder->uploadBufferData(constantBuffer, 0, sizeof(mvp), mvp);
}
@@ -290,37 +293,39 @@ void GUI::endFrame(ITransientResourceHeap* transientHeap, IFramebuffer* framebuf
renderEncoder->setVertexBuffer(0, vertexBuffer);
renderEncoder->setIndexBuffer(
- indexBuffer, sizeof(ImDrawIdx) == 2 ? Format::R16_UINT : Format::R32_UINT);
+ indexBuffer,
+ sizeof(ImDrawIdx) == 2 ? Format::R16_UINT : Format::R32_UINT);
renderEncoder->setPrimitiveTopology(PrimitiveTopology::TriangleList);
uint32_t vertexOffset = 0;
uint32_t indexOffset = 0;
ImVec2 pos = draw_data->DisplayPos;
- for(int ii = 0; ii < commandListCount; ++ii)
+ for (int ii = 0; ii < commandListCount; ++ii)
{
auto commandList = draw_data->CmdLists[ii];
auto commandCount = commandList->CmdBuffer.Size;
- for(int jj = 0; jj < commandCount; jj++)
+ for (int jj = 0; jj < commandCount; jj++)
{
auto command = &commandList->CmdBuffer[jj];
- if(auto userCallback = command->UserCallback)
+ if (auto userCallback = command->UserCallback)
{
userCallback(commandList, command);
}
else
{
- ScissorRect rect =
- {
+ ScissorRect rect = {
(int32_t)(command->ClipRect.x - pos.x),
(int32_t)(command->ClipRect.y - pos.y),
(int32_t)(command->ClipRect.z - pos.x),
- (int32_t)(command->ClipRect.w - pos.y)
- };
+ (int32_t)(command->ClipRect.w - pos.y)};
renderEncoder->setScissorRects(1, &rect);
// TODO: set parameter into root shader object.
-
- renderEncoder->drawIndexed(command->ElemCount, (uint32_t)indexOffset, (uint32_t)vertexOffset);
+
+ renderEncoder->drawIndexed(
+ command->ElemCount,
+ (uint32_t)indexOffset,
+ (uint32_t)vertexOffset);
}
indexOffset += command->ElemCount;
}
@@ -337,24 +342,24 @@ GUI::~GUI()
{
ComPtr<IResourceView> textureView;
- textureView.attach((IResourceView*) io.Fonts->TexID);
+ textureView.attach((IResourceView*)io.Fonts->TexID);
textureView = nullptr;
}
#ifdef _WIN32
- ImGui_ImplWin32_Shutdown();
+ ImGui_ImplWin32_Shutdown();
#endif
- ImGui::DestroyContext();
+ ImGui::DestroyContext();
}
-} // gfx
+} // namespace platform
#include <imgui.cpp>
#include <imgui_draw.cpp>
#include <imgui_widgets.cpp>
#ifdef _WIN32
-// imgui_impl_win32 defines these, so make sure it doesn't error because
+ // imgui_impl_win32 defines these, so make sure it doesn't error because
// they're already there
#undef WIN32_LEAN_AND_MEAN
#undef NOMINMAX
diff --git a/tools/platform/gui.h b/tools/platform/gui.h
index e3975f3ff..82193cb86 100644
--- a/tools/platform/gui.h
+++ b/tools/platform/gui.h
@@ -1,14 +1,15 @@
// gui.h
#pragma once
+#include "external/imgui/imgui.h"
+#include "slang-com-ptr.h"
#include "slang-gfx.h"
+#include "source/core/slang-basic.h"
#include "vector-math.h"
#include "window.h"
-#include "slang-com-ptr.h"
-#include "external/imgui/imgui.h"
-#include "source/core/slang-basic.h"
-namespace platform {
+namespace platform
+{
struct GUI : Slang::RefObject
{
@@ -25,8 +26,8 @@ private:
Slang::ComPtr<gfx::IDevice> device;
Slang::ComPtr<gfx::ICommandQueue> queue;
Slang::ComPtr<gfx::IRenderPassLayout> renderPass;
- Slang::ComPtr<gfx::IPipelineState> pipelineState;
- Slang::ComPtr<gfx::ISamplerState> samplerState;
+ Slang::ComPtr<gfx::IPipelineState> pipelineState;
+ Slang::ComPtr<gfx::ISamplerState> samplerState;
};
-} // gfx
+} // namespace platform
diff --git a/tools/platform/linux/x11-key-code.cpp b/tools/platform/linux/x11-key-code.cpp
index c078a6d1c..0faafae78 100644
--- a/tools/platform/linux/x11-key-code.cpp
+++ b/tools/platform/linux/x11-key-code.cpp
@@ -1,9 +1,10 @@
#if defined(SLANG_ENABLE_XLIB)
-#include "core/slang-basic.h"
#include "../window.h"
-#include <X11/keysym.h>
+#include "core/slang-basic.h"
+
#include <X11/Xlib.h>
+#include <X11/keysym.h>
#ifdef None
#undef None
@@ -15,233 +16,196 @@ using namespace Slang;
namespace platform
{
- Dictionary<int, KeyCode> keyCodeMap;
+Dictionary<int, KeyCode> keyCodeMap;
- struct Win32KeyCode
- {
- KeyCode vKeyCode;
- int keySym;
- };
+struct Win32KeyCode
+{
+ KeyCode vKeyCode;
+ int keySym;
+};
- Win32KeyCode keys[] =
- {
- {KeyCode::Left, XK_Left},
- {KeyCode::Up, XK_Up},
- {KeyCode::Down, XK_Down},
- {KeyCode::Right, XK_Right},
- {KeyCode::Escape, XK_Escape},
- {KeyCode::Return, XK_Return},
- {KeyCode::Space, XK_space},
- {KeyCode::Shift, XK_Shift_L},
- {KeyCode::Shift, XK_Shift_R},
- {KeyCode::Ctrl, XK_Control_L},
- {KeyCode::Ctrl, XK_Control_R},
- {KeyCode::Alt, XK_Alt_L},
- {KeyCode::Alt, XK_Alt_R},
- {KeyCode::Backspace, XK_BackSpace},
- {KeyCode::Delete, XK_Delete},
- {KeyCode::Home, XK_Home},
- {KeyCode::End, XK_End},
- {KeyCode::PageUp, XK_Page_Up},
- {KeyCode::PageDown, XK_Page_Down},
- {KeyCode::Insert, XK_Insert},
- {KeyCode::Tab, XK_Tab},
- {KeyCode::A, 0x41},
- {KeyCode::B, 0x42},
- {KeyCode::C, 0x43},
- {KeyCode::D, 0x44},
- {KeyCode::E, 0x45},
- {KeyCode::F, 0x46},
- {KeyCode::G, 0x47},
- {KeyCode::H, 0x48},
- {KeyCode::I, 0x49},
- {KeyCode::J, 0x4A},
- {KeyCode::K, 0x4B},
- {KeyCode::L, 0x4C},
- {KeyCode::M, 0x4D},
- {KeyCode::N, 0x4E},
- {KeyCode::O, 0x4F},
- {KeyCode::P, 0x50},
- {KeyCode::Q, 0x51},
- {KeyCode::R, 0x52},
- {KeyCode::S, 0x53},
- {KeyCode::T, 0x54},
- {KeyCode::U, 0x55},
- {KeyCode::V, 0x56},
- {KeyCode::W, 0x57},
- {KeyCode::X, 0x58},
- {KeyCode::Y, 0x59},
- {KeyCode::Z, 0x5A},
- {KeyCode::Semicolon, XK_semicolon},
- {KeyCode::Comma, XK_comma},
- {KeyCode::Dot, XK_period},
- {KeyCode::Slash, XK_slash},
- {KeyCode::Quote, XK_apostrophe},
- {KeyCode::LBracket, XK_bracketleft},
- {KeyCode::RBracket, XK_bracketright},
- {KeyCode::Backslash, XK_backslash},
- {KeyCode::Minus, XK_minus},
- {KeyCode::Plus, XK_equal},
- {KeyCode::Tilde, XK_asciitilde},
- {KeyCode::Key0, 0x30},
- {KeyCode::Key1, 0x31},
- {KeyCode::Key2, 0x32},
- {KeyCode::Key3, 0x33},
- {KeyCode::Key4, 0x34},
- {KeyCode::Key5, 0x35},
- {KeyCode::Key6, 0x36},
- {KeyCode::Key7, 0x37},
- {KeyCode::Key8, 0x38},
- {KeyCode::Key9, 0x39},
- {KeyCode::F1, XK_F1},
- {KeyCode::F2, XK_F2},
- {KeyCode::F3, XK_F3},
- {KeyCode::F4, XK_F4},
- {KeyCode::F5, XK_F5},
- {KeyCode::F6, XK_F6},
- {KeyCode::F7, XK_F7},
- {KeyCode::F8, XK_F8},
- {KeyCode::F9, XK_F9},
- {KeyCode::F10, XK_F10},
- {KeyCode::F11, XK_F11},
- {KeyCode::F12, XK_F12}
- };
+Win32KeyCode keys[] = {
+ {KeyCode::Left, XK_Left},
+ {KeyCode::Up, XK_Up},
+ {KeyCode::Down, XK_Down},
+ {KeyCode::Right, XK_Right},
+ {KeyCode::Escape, XK_Escape},
+ {KeyCode::Return, XK_Return},
+ {KeyCode::Space, XK_space},
+ {KeyCode::Shift, XK_Shift_L},
+ {KeyCode::Shift, XK_Shift_R},
+ {KeyCode::Ctrl, XK_Control_L},
+ {KeyCode::Ctrl, XK_Control_R},
+ {KeyCode::Alt, XK_Alt_L},
+ {KeyCode::Alt, XK_Alt_R},
+ {KeyCode::Backspace, XK_BackSpace},
+ {KeyCode::Delete, XK_Delete},
+ {KeyCode::Home, XK_Home},
+ {KeyCode::End, XK_End},
+ {KeyCode::PageUp, XK_Page_Up},
+ {KeyCode::PageDown, XK_Page_Down},
+ {KeyCode::Insert, XK_Insert},
+ {KeyCode::Tab, XK_Tab},
+ {KeyCode::A, 0x41},
+ {KeyCode::B, 0x42},
+ {KeyCode::C, 0x43},
+ {KeyCode::D, 0x44},
+ {KeyCode::E, 0x45},
+ {KeyCode::F, 0x46},
+ {KeyCode::G, 0x47},
+ {KeyCode::H, 0x48},
+ {KeyCode::I, 0x49},
+ {KeyCode::J, 0x4A},
+ {KeyCode::K, 0x4B},
+ {KeyCode::L, 0x4C},
+ {KeyCode::M, 0x4D},
+ {KeyCode::N, 0x4E},
+ {KeyCode::O, 0x4F},
+ {KeyCode::P, 0x50},
+ {KeyCode::Q, 0x51},
+ {KeyCode::R, 0x52},
+ {KeyCode::S, 0x53},
+ {KeyCode::T, 0x54},
+ {KeyCode::U, 0x55},
+ {KeyCode::V, 0x56},
+ {KeyCode::W, 0x57},
+ {KeyCode::X, 0x58},
+ {KeyCode::Y, 0x59},
+ {KeyCode::Z, 0x5A},
+ {KeyCode::Semicolon, XK_semicolon},
+ {KeyCode::Comma, XK_comma},
+ {KeyCode::Dot, XK_period},
+ {KeyCode::Slash, XK_slash},
+ {KeyCode::Quote, XK_apostrophe},
+ {KeyCode::LBracket, XK_bracketleft},
+ {KeyCode::RBracket, XK_bracketright},
+ {KeyCode::Backslash, XK_backslash},
+ {KeyCode::Minus, XK_minus},
+ {KeyCode::Plus, XK_equal},
+ {KeyCode::Tilde, XK_asciitilde},
+ {KeyCode::Key0, 0x30},
+ {KeyCode::Key1, 0x31},
+ {KeyCode::Key2, 0x32},
+ {KeyCode::Key3, 0x33},
+ {KeyCode::Key4, 0x34},
+ {KeyCode::Key5, 0x35},
+ {KeyCode::Key6, 0x36},
+ {KeyCode::Key7, 0x37},
+ {KeyCode::Key8, 0x38},
+ {KeyCode::Key9, 0x39},
+ {KeyCode::F1, XK_F1},
+ {KeyCode::F2, XK_F2},
+ {KeyCode::F3, XK_F3},
+ {KeyCode::F4, XK_F4},
+ {KeyCode::F5, XK_F5},
+ {KeyCode::F6, XK_F6},
+ {KeyCode::F7, XK_F7},
+ {KeyCode::F8, XK_F8},
+ {KeyCode::F9, XK_F9},
+ {KeyCode::F10, XK_F10},
+ {KeyCode::F11, XK_F11},
+ {KeyCode::F12, XK_F12}};
- void initKeyCodeTranslationTable(Display* display)
+void initKeyCodeTranslationTable(Display* display)
+{
+ for (auto entry : keys)
{
- for (auto entry : keys)
- {
- auto systemKeyCode = XKeysymToKeycode(display, entry.keySym);
- keyCodeMap[systemKeyCode] = entry.vKeyCode;
- }
+ auto systemKeyCode = XKeysymToKeycode(display, entry.keySym);
+ keyCodeMap[systemKeyCode] = entry.vKeyCode;
}
+}
- void freeKeyCodeTranslationTable()
+void freeKeyCodeTranslationTable()
+{
+ keyCodeMap = decltype(keyCodeMap)();
+}
+
+KeyCode translateKeyCode(int keyCode)
+{
+ KeyCode result = KeyCode::None;
+ keyCodeMap.tryGetValue(keyCode, result);
+ return result;
+}
+
+int getKeyChar(KeyCode keyCode, int keyState)
+{
+ bool shift = (keyState & ShiftMask) != 0;
+ if (keyCode >= KeyCode::A && keyCode <= KeyCode::Z)
{
- keyCodeMap = decltype(keyCodeMap)();
+ bool capslock = (keyState & LockMask) != 0;
+ bool isCapital = capslock ^ shift;
+ if (isCapital)
+ return (int)keyCode;
+ else
+ return (int)keyCode + ('a' - 'A');
}
-
- KeyCode translateKeyCode(int keyCode)
+ else if (keyCode == KeyCode::Space)
{
- KeyCode result = KeyCode::None;
- keyCodeMap.tryGetValue(keyCode, result);
- return result;
+ return ' ';
}
-
- int getKeyChar(KeyCode keyCode, int keyState)
+ else if (keyCode == KeyCode::Return)
{
- bool shift = (keyState & ShiftMask) != 0;
- if (keyCode >= KeyCode::A && keyCode <= KeyCode::Z )
- {
- bool capslock = (keyState & LockMask) != 0;
- bool isCapital = capslock ^ shift;
- if (isCapital)
- return (int)keyCode;
- else
- return (int)keyCode + ('a'-'A');
- }
- else if (keyCode == KeyCode::Space)
- {
- return ' ';
- }
- else if (keyCode == KeyCode::Return)
- {
+ return (int)keyCode;
+ }
+ else if (keyCode >= KeyCode::Key0 && keyCode <= KeyCode::Key9)
+ {
+ if (!shift)
return (int)keyCode;
- }
- else if (keyCode >= KeyCode::Key0 && keyCode <= KeyCode::Key9)
+ else
{
- if (!shift)
- return (int)keyCode;
- else
+ switch (keyCode)
{
- switch (keyCode)
- {
- case KeyCode::Key0:
- return ')';
- case KeyCode::Key1:
- return '!';
- case KeyCode::Key2:
- return '@';
- case KeyCode::Key3:
- return '#';
- case KeyCode::Key4:
- return '$';
- case KeyCode::Key5:
- return '%';
- case KeyCode::Key6:
- return '^';
- case KeyCode::Key7:
- return '&';
- case KeyCode::Key8:
- return '*';
- case KeyCode::Key9:
- return '(';
- default:
- return 0;
- }
+ case KeyCode::Key0: return ')';
+ case KeyCode::Key1: return '!';
+ case KeyCode::Key2: return '@';
+ case KeyCode::Key3: return '#';
+ case KeyCode::Key4: return '$';
+ case KeyCode::Key5: return '%';
+ case KeyCode::Key6: return '^';
+ case KeyCode::Key7: return '&';
+ case KeyCode::Key8: return '*';
+ case KeyCode::Key9: return '(';
+ default: return 0;
}
}
- if (shift)
+ }
+ if (shift)
+ {
+ switch (keyCode)
{
- switch (keyCode)
- {
- case KeyCode::Semicolon:
- return ':';
- case KeyCode::Comma:
- return '<';
- case KeyCode::Dot:
- return '>';
- case KeyCode::Slash:
- return '?';
- case KeyCode::Quote:
- return '\"';
- case KeyCode::LBracket:
- return '{';
- case KeyCode::RBracket:
- return '}';
- case KeyCode::Backslash:
- return '|';
- case KeyCode::Minus:
- return '_';
- case KeyCode::Plus:
- return '+';
- case KeyCode::Tilde:
- return '~';
- default:
- return 0;
- }
+ case KeyCode::Semicolon: return ':';
+ case KeyCode::Comma: return '<';
+ case KeyCode::Dot: return '>';
+ case KeyCode::Slash: return '?';
+ case KeyCode::Quote: return '\"';
+ case KeyCode::LBracket: return '{';
+ case KeyCode::RBracket: return '}';
+ case KeyCode::Backslash: return '|';
+ case KeyCode::Minus: return '_';
+ case KeyCode::Plus: return '+';
+ case KeyCode::Tilde: return '~';
+ default: return 0;
}
- else
+ }
+ else
+ {
+ switch (keyCode)
{
- switch (keyCode)
- {
- case KeyCode::Semicolon:
- return ';';
- case KeyCode::Comma:
- return ',';
- case KeyCode::Dot:
- return '.';
- case KeyCode::Slash:
- return '/';
- case KeyCode::Quote:
- return '\'';
- case KeyCode::LBracket:
- return '[';
- case KeyCode::RBracket:
- return ']';
- case KeyCode::Backslash:
- return '\\';
- case KeyCode::Minus:
- return '-';
- case KeyCode::Plus:
- return '=';
- case KeyCode::Tilde:
- return '`';
- default:
- return 0;
- }
+ case KeyCode::Semicolon: return ';';
+ case KeyCode::Comma: return ',';
+ case KeyCode::Dot: return '.';
+ case KeyCode::Slash: return '/';
+ case KeyCode::Quote: return '\'';
+ case KeyCode::LBracket: return '[';
+ case KeyCode::RBracket: return ']';
+ case KeyCode::Backslash: return '\\';
+ case KeyCode::Minus: return '-';
+ case KeyCode::Plus: return '=';
+ case KeyCode::Tilde: return '`';
+ default: return 0;
}
}
+}
} // namespace platform
#endif
diff --git a/tools/platform/linux/x11-window.cpp b/tools/platform/linux/x11-window.cpp
index be807ac33..155801049 100644
--- a/tools/platform/linux/x11-window.cpp
+++ b/tools/platform/linux/x11-window.cpp
@@ -1,9 +1,10 @@
#ifdef SLANG_ENABLE_XLIB
#include "../window.h"
+
#include <X11/Xlib.h>
-#include <X11/Xutil.h>
#include <X11/Xresource.h>
+#include <X11/Xutil.h>
#ifdef None
#undef None
@@ -18,7 +19,7 @@ namespace platform
typedef ::Window X11WindowHandle;
class X11PlatformWindow;
-void initKeyCodeTranslationTable(Display *display);
+void initKeyCodeTranslationTable(Display* display);
void freeKeyCodeTranslationTable();
KeyCode translateKeyCode(int keyCode);
int getKeyChar(KeyCode keyCode, int keyState);
@@ -34,12 +35,16 @@ enum class KeyState
enum class KeyEvent
{
- Press, Release
+ Press,
+ Release
};
enum class MouseEvent
{
- Move, Down, Up, Scroll
+ Move,
+ Down,
+ Up,
+ Scroll
};
class X11AppContext
@@ -51,7 +56,7 @@ public:
static X11WindowHandle mainWindowHandle;
static Display* xdisplay;
static KeyState keyStates[kKeyStateTableSize];
- static X11PlatformWindow *currentMouseEventWindow;
+ static X11PlatformWindow* currentMouseEventWindow;
};
bool X11AppContext::isTerminated = false;
@@ -62,16 +67,19 @@ Display* X11AppContext::xdisplay = nullptr;
KeyState X11AppContext::keyStates[kKeyStateTableSize] = {};
X11PlatformWindow* X11AppContext::currentMouseEventWindow = nullptr;
-void Application::init()
-{
-
-}
+void Application::init() {}
static void doEventsImpl(bool waitForEvents);
-void Application::doEvents() { doEventsImpl(false); }
+void Application::doEvents()
+{
+ doEventsImpl(false);
+}
-void Application::quit() { X11AppContext::isTerminated = true; }
+void Application::quit()
+{
+ X11AppContext::isTerminated = true;
+}
void Application::dispose()
{
@@ -85,7 +93,8 @@ void Application::run(Window* mainWindow, bool waitForEvents)
if (mainWindow)
{
X11AppContext::mainWindow = mainWindow;
- X11AppContext::mainWindowHandle = (X11WindowHandle)mainWindow->getNativeHandle().handleValues[1];
+ X11AppContext::mainWindowHandle =
+ (X11WindowHandle)mainWindow->getNativeHandle().handleValues[1];
mainWindow->show();
while (!X11AppContext::isTerminated)
{
@@ -104,20 +113,33 @@ public:
int currentWidth = 0;
int currentHeight = 0;
bool fixedSized = false;
- X11PlatformWindow(const WindowDesc &desc)
+ X11PlatformWindow(const WindowDesc& desc)
{
currentWidth = desc.width;
currentHeight = desc.height;
- int blackColor = BlackPixel(X11AppContext::xdisplay, DefaultScreen(X11AppContext::xdisplay));
- int whiteColor = WhitePixel(X11AppContext::xdisplay, DefaultScreen(X11AppContext::xdisplay));
- handle = XCreateSimpleWindow(X11AppContext::xdisplay, DefaultRootWindow(X11AppContext::xdisplay), 0, 0,
- desc.width, desc.height, 0, blackColor, blackColor);
+ int blackColor =
+ BlackPixel(X11AppContext::xdisplay, DefaultScreen(X11AppContext::xdisplay));
+ int whiteColor =
+ WhitePixel(X11AppContext::xdisplay, DefaultScreen(X11AppContext::xdisplay));
+ handle = XCreateSimpleWindow(
+ X11AppContext::xdisplay,
+ DefaultRootWindow(X11AppContext::xdisplay),
+ 0,
+ 0,
+ desc.width,
+ desc.height,
+ 0,
+ blackColor,
+ blackColor);
X11AppContext::windows[handle] = this;
Atom wmDelete = XInternAtom(X11AppContext::xdisplay, "WM_DELETE_WINDOW", True);
XSetWMProtocols(X11AppContext::xdisplay, handle, &wmDelete, 1);
- XSelectInput(X11AppContext::xdisplay, handle, StructureNotifyMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
- ButtonPressMask | ButtonReleaseMask | ExposureMask | FocusChangeMask);
+ XSelectInput(
+ X11AppContext::xdisplay,
+ handle,
+ StructureNotifyMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
+ ButtonPressMask | ButtonReleaseMask | ExposureMask | FocusChangeMask);
if (desc.style == WindowStyle::FixedSize)
{
@@ -127,10 +149,7 @@ public:
setText(desc.title);
}
- ~X11PlatformWindow()
- {
- close();
- }
+ ~X11PlatformWindow() { close(); }
void setFixedSizeHint(int w, int h)
{
@@ -158,12 +177,27 @@ public:
X11WindowHandle winRoot = 0, winParent = 0;
X11WindowHandle* winChildren = nullptr;
unsigned int numChilren = 0;
- XQueryTree(X11AppContext::xdisplay, handle, &winRoot, &winParent, &winChildren, &numChilren);
+ XQueryTree(
+ X11AppContext::xdisplay,
+ handle,
+ &winRoot,
+ &winParent,
+ &winChildren,
+ &numChilren);
unsigned borderWidth, depth;
- XGetGeometry(X11AppContext::xdisplay, handle, &winRoot, &rect.x, &rect.y, (uint32_t*)&rect.width, (uint32_t*)&rect.height, &borderWidth, &depth);
+ XGetGeometry(
+ X11AppContext::xdisplay,
+ handle,
+ &winRoot,
+ &rect.x,
+ &rect.y,
+ (uint32_t*)&rect.width,
+ (uint32_t*)&rect.height,
+ &borderWidth,
+ &depth);
return rect;
}
-
+
virtual void centerScreen() override
{
auto currentRect = getClientRect();
@@ -186,7 +220,8 @@ public:
}
virtual bool getFocused() override
{
- if (!handle) return false;
+ if (!handle)
+ return false;
int revertTo;
X11WindowHandle focusedWindow;
XGetInputFocus(X11AppContext::xdisplay, &focusedWindow, &revertTo);
@@ -202,18 +237,16 @@ public:
}
virtual void setText(String text) override
{
- if (!handle) return;
+ if (!handle)
+ return;
XStoreName(X11AppContext::xdisplay, handle, text.getBuffer());
XClassHint* hint = XAllocClassHint();
- hint->res_class = (char *)"Slang platform window";
- hint->res_name = (char *)"Slang platform window";
+ hint->res_class = (char*)"Slang platform window";
+ hint->res_name = (char*)"Slang platform window";
XSetClassHint(X11AppContext::xdisplay, handle, hint);
XFree(hint);
}
- virtual bool getVisible() override
- {
- return visible;
- }
+ virtual bool getVisible() override { return visible; }
virtual void show() override
{
XMapWindow(X11AppContext::xdisplay, handle);
@@ -221,16 +254,17 @@ public:
}
virtual void hide() override
{
- if (!handle) return;
+ if (!handle)
+ return;
XUnmapWindow(X11AppContext::xdisplay, handle);
visible = false;
}
virtual int getCurrentDpi() override
{
- char *resourceString = XResourceManagerString(X11AppContext::xdisplay);
+ char* resourceString = XResourceManagerString(X11AppContext::xdisplay);
XrmDatabase db;
XrmValue value;
- char *type = NULL;
+ char* type = NULL;
double dpi = 96.0;
db = XrmGetStringDatabase(resourceString);
if (resourceString)
@@ -263,12 +297,18 @@ public:
ButtonState::Enum getButtonState(int state)
{
ButtonState::Enum buttonState = ButtonState::Enum::None;
- if (state & ShiftMask) addButtonState(buttonState, ButtonState::Enum::Shift);
- if (state & ControlMask) addButtonState(buttonState, ButtonState::Enum::Control);
- if (state & Mod1Mask) addButtonState(buttonState, ButtonState::Enum::Alt);
- if (state & Button1Mask) addButtonState(buttonState, ButtonState::Enum::LeftButton);
- if (state & Button2Mask) addButtonState(buttonState, ButtonState::Enum::MiddleButton);
- if (state & Button3Mask) addButtonState(buttonState, ButtonState::Enum::RightButton);
+ if (state & ShiftMask)
+ addButtonState(buttonState, ButtonState::Enum::Shift);
+ if (state & ControlMask)
+ addButtonState(buttonState, ButtonState::Enum::Control);
+ if (state & Mod1Mask)
+ addButtonState(buttonState, ButtonState::Enum::Alt);
+ if (state & Button1Mask)
+ addButtonState(buttonState, ButtonState::Enum::LeftButton);
+ if (state & Button2Mask)
+ addButtonState(buttonState, ButtonState::Enum::MiddleButton);
+ if (state & Button3Mask)
+ addButtonState(buttonState, ButtonState::Enum::RightButton);
return buttonState;
}
@@ -291,7 +331,14 @@ public:
}
}
- void handleMouseEvent(MouseEvent eventType, int x, int y, int delta, int button, int state, unsigned long time)
+ void handleMouseEvent(
+ MouseEvent eventType,
+ int x,
+ int y,
+ int delta,
+ int button,
+ int state,
+ unsigned long time)
{
auto buttonState = getButtonState(state);
if (button == Button1)
@@ -308,20 +355,11 @@ public:
switch (eventType)
{
- case MouseEvent::Down:
- events.mouseDown(e);
- break;
- case MouseEvent::Up:
- events.mouseUp(e);
- break;
- case MouseEvent::Move:
- events.mouseMove(e);
- break;
- case MouseEvent::Scroll:
- events.mouseWheel(e);
- break;
- default:
- break;
+ case MouseEvent::Down: events.mouseDown(e); break;
+ case MouseEvent::Up: events.mouseUp(e); break;
+ case MouseEvent::Move: events.mouseMove(e); break;
+ case MouseEvent::Scroll: events.mouseWheel(e); break;
+ default: break;
}
}
@@ -332,14 +370,9 @@ public:
Application::quit();
}
- void handleExposeEvent()
- {
- }
-
- void handleFocus(bool focus)
- {
- }
+ void handleExposeEvent() {}
+ void handleFocus(bool focus) {}
};
Window* Application::createWindow(const WindowDesc& desc)
@@ -361,7 +394,7 @@ void doEventsImpl(bool waitForEvents)
auto xdisplay = X11AppContext::xdisplay;
if (!X11AppContext::xdisplay)
return;
-
+
static bool supressInvokeTasks = false;
X11PlatformWindow* sysWindow = nullptr;
KeyCode vKeyCode = KeyCode::None;
@@ -379,7 +412,7 @@ void doEventsImpl(bool waitForEvents)
{
if (X11AppContext::keyStates[iKeyCode] == KeyState::Released)
X11AppContext::keyStates[iKeyCode] = KeyState::Pressed;
- else if (X11AppContext::keyStates[iKeyCode] == KeyState::Pressed)
+ else if (X11AppContext::keyStates[iKeyCode] == KeyState::Pressed)
X11AppContext::keyStates[iKeyCode] = KeyState::Hold;
}
if (X11AppContext::windows.tryGetValue(nextEvent.xkey.window, sysWindow))
@@ -404,8 +437,14 @@ void doEventsImpl(bool waitForEvents)
if (X11AppContext::windows.tryGetValue(nextEvent.xmotion.window, sysWindow))
{
X11AppContext::currentMouseEventWindow = sysWindow;
- sysWindow->handleMouseEvent(MouseEvent::Move, nextEvent.xmotion.x, nextEvent.xmotion.y, 0,
- 0, nextEvent.xmotion.state, nextEvent.xmotion.time);
+ sysWindow->handleMouseEvent(
+ MouseEvent::Move,
+ nextEvent.xmotion.x,
+ nextEvent.xmotion.y,
+ 0,
+ 0,
+ nextEvent.xmotion.state,
+ nextEvent.xmotion.time);
}
break;
case ButtonPress:
@@ -413,28 +452,54 @@ void doEventsImpl(bool waitForEvents)
{
X11AppContext::currentMouseEventWindow = sysWindow;
if (nextEvent.xbutton.button <= Button3)
- sysWindow->handleMouseEvent(MouseEvent::Down, nextEvent.xbutton.x, nextEvent.xbutton.y, 0,
- nextEvent.xbutton.button, nextEvent.xbutton.state, nextEvent.xbutton.time);
+ sysWindow->handleMouseEvent(
+ MouseEvent::Down,
+ nextEvent.xbutton.x,
+ nextEvent.xbutton.y,
+ 0,
+ nextEvent.xbutton.button,
+ nextEvent.xbutton.state,
+ nextEvent.xbutton.time);
else if (nextEvent.xbutton.button == Button4)
- sysWindow->handleMouseEvent(MouseEvent::Scroll, nextEvent.xbutton.x, nextEvent.xbutton.y, 120,
- nextEvent.xbutton.button, nextEvent.xbutton.state, nextEvent.xbutton.time);
+ sysWindow->handleMouseEvent(
+ MouseEvent::Scroll,
+ nextEvent.xbutton.x,
+ nextEvent.xbutton.y,
+ 120,
+ nextEvent.xbutton.button,
+ nextEvent.xbutton.state,
+ nextEvent.xbutton.time);
else if (nextEvent.xbutton.button == Button5)
- sysWindow->handleMouseEvent(MouseEvent::Scroll, nextEvent.xbutton.x, nextEvent.xbutton.y, -120,
- nextEvent.xbutton.button, nextEvent.xbutton.state, nextEvent.xbutton.time);
+ sysWindow->handleMouseEvent(
+ MouseEvent::Scroll,
+ nextEvent.xbutton.x,
+ nextEvent.xbutton.y,
+ -120,
+ nextEvent.xbutton.button,
+ nextEvent.xbutton.state,
+ nextEvent.xbutton.time);
}
break;
case ButtonRelease:
if (X11AppContext::windows.tryGetValue(nextEvent.xbutton.window, sysWindow))
{
X11AppContext::currentMouseEventWindow = sysWindow;
- sysWindow->handleMouseEvent(MouseEvent::Up, nextEvent.xbutton.x, nextEvent.xbutton.y, 0,
- nextEvent.xbutton.button, nextEvent.xbutton.state, nextEvent.xbutton.time);
+ sysWindow->handleMouseEvent(
+ MouseEvent::Up,
+ nextEvent.xbutton.x,
+ nextEvent.xbutton.y,
+ 0,
+ nextEvent.xbutton.button,
+ nextEvent.xbutton.state,
+ nextEvent.xbutton.time);
}
break;
case ConfigureNotify:
if (X11AppContext::windows.tryGetValue(nextEvent.xconfigure.window, sysWindow))
{
- sysWindow->handleResizeEvent(nextEvent.xconfigure.width, nextEvent.xconfigure.height);
+ sysWindow->handleResizeEvent(
+ nextEvent.xconfigure.width,
+ nextEvent.xconfigure.height);
}
break;
case Expose:
@@ -469,6 +534,6 @@ void doEventsImpl(bool waitForEvents)
}
}
-}
+} // namespace platform
#endif
diff --git a/tools/platform/model.cpp b/tools/platform/model.cpp
index a48d499b9..3649db9dc 100644
--- a/tools/platform/model.cpp
+++ b/tools/platform/model.cpp
@@ -10,17 +10,17 @@
#include "../../external/stb/stb_image.h"
#define STB_IMAGE_RESIZE_IMPLEMENTATION
-#include "../../external/stb/stb_image_resize.h"
-
#include "../../external/glm/glm/glm.hpp"
-#include "../../external/glm/glm/gtc/matrix_transform.hpp"
#include "../../external/glm/glm/gtc/constants.hpp"
+#include "../../external/glm/glm/gtc/matrix_transform.hpp"
+#include "../../external/stb/stb_image_resize.h"
#include <memory>
#include <unordered_map>
#include <unordered_set>
-namespace platform {
+namespace platform
+{
using namespace gfx;
using namespace Slang;
@@ -43,9 +43,9 @@ struct ObjIndexKey
bool operator==(ObjIndexKey const& left, ObjIndexKey const& right)
{
- return left.index.vertex_index == right.index.vertex_index
- && left.index.normal_index == right.index.normal_index
- && left.index.texcoord_index == right.index.texcoord_index;
+ return left.index.vertex_index == right.index.vertex_index &&
+ left.index.normal_index == right.index.normal_index &&
+ left.index.texcoord_index == right.index.texcoord_index;
}
struct Hasher
@@ -65,70 +65,65 @@ struct SmoothingGroupVertexID
};
bool operator==(SmoothingGroupVertexID const& left, SmoothingGroupVertexID const& right)
{
- return left.smoothingGroup == right.smoothingGroup
- && left.positionID == right.positionID;
+ return left.smoothingGroup == right.smoothingGroup && left.positionID == right.positionID;
}
-}
+} // namespace platform
namespace std
{
- template<> struct hash<platform::ObjIndexKey>
+template<>
+struct hash<platform::ObjIndexKey>
+{
+ size_t operator()(platform::ObjIndexKey const& key) const
{
- size_t operator()(platform::ObjIndexKey const& key) const
- {
- platform::Hasher hasher;
- hasher.add(key.index.vertex_index);
- hasher.add(key.index.normal_index);
- hasher.add(key.index.texcoord_index);
- return hasher.state;
- }
- };
+ platform::Hasher hasher;
+ hasher.add(key.index.vertex_index);
+ hasher.add(key.index.normal_index);
+ hasher.add(key.index.texcoord_index);
+ return hasher.state;
+ }
+};
- template <> struct hash<platform::SmoothingGroupVertexID>
+template<>
+struct hash<platform::SmoothingGroupVertexID>
+{
+ size_t operator()(platform::SmoothingGroupVertexID const& id) const
{
- size_t operator()(platform::SmoothingGroupVertexID const& id) const
- {
- platform::Hasher hasher;
- hasher.add(id.smoothingGroup);
- hasher.add(id.positionID);
- return hasher.state;
- }
- };
-}
+ platform::Hasher hasher;
+ hasher.add(id.smoothingGroup);
+ hasher.add(id.positionID);
+ return hasher.state;
+ }
+};
+} // namespace std
namespace platform
{
-ComPtr<ITextureResource> loadTextureImage(
- IDevice* device,
- char const* path)
+ComPtr<ITextureResource> loadTextureImage(IDevice* device, char const* path)
{
int extentX = 0;
int extentY = 0;
int originalChannelCount = 0;
int requestedChannelCount = 4; // force to 4-component result
- stbi_uc* data = stbi_load(
- path,
- &extentX,
- &extentY,
- &originalChannelCount,
- requestedChannelCount);
- if(!data)
+ stbi_uc* data =
+ stbi_load(path, &extentX, &extentY, &originalChannelCount, requestedChannelCount);
+ if (!data)
return nullptr;
int channelCount = requestedChannelCount ? requestedChannelCount : originalChannelCount;
Format format;
- switch(channelCount)
+ switch (channelCount)
{
- default:
- return nullptr;
+ default: return nullptr;
- case 4: format = Format::R8G8B8A8_UNORM;
+ case 4:
+ format = Format::R8G8B8A8_UNORM;
- // TODO: handle other cases here if/when we stop forcing 4-component
- // results when loading the image with stb_image.
+ // TODO: handle other cases here if/when we stop forcing 4-component
+ // results when loading the image with stb_image.
}
std::vector<ITextureResource::SubresourceData> subresourceInitData;
@@ -144,30 +139,39 @@ ComPtr<ITextureResource> loadTextureImage(
// create down-sampled images for the different mip levels
bool generateMips = true;
- if(generateMips)
+ if (generateMips)
{
int prevExtentX = extentX;
int prevExtentY = extentY;
stbi_uc* prevData = data;
int prevStride = int(stride);
- for(;;)
+ for (;;)
{
- if(prevExtentX == 1 && prevExtentY == 1)
+ if (prevExtentX == 1 && prevExtentY == 1)
break;
int newExtentX = prevExtentX / 2;
int newExtentY = prevExtentY / 2;
- if(!newExtentX) newExtentX = 1;
- if(!newExtentY) newExtentY = 1;
+ if (!newExtentX)
+ newExtentX = 1;
+ if (!newExtentY)
+ newExtentY = 1;
- stbi_uc* newData = (stbi_uc*) malloc(newExtentX * newExtentY * channelCount * sizeof(stbi_uc));
+ stbi_uc* newData =
+ (stbi_uc*)malloc(newExtentX * newExtentY * channelCount * sizeof(stbi_uc));
int newStride = int(newExtentX * channelCount * sizeof(stbi_uc));
stbir_resize_uint8_srgb(
- prevData, prevExtentX, prevExtentY, prevStride,
- newData, newExtentX, newExtentY, newStride,
+ prevData,
+ prevExtentX,
+ prevExtentY,
+ prevStride,
+ newData,
+ newExtentX,
+ newExtentY,
+ newStride,
channelCount,
STBIR_ALPHA_CHANNEL_NONE,
STBIR_FLAG_ALPHA_PREMULTIPLIED);
@@ -187,7 +191,7 @@ ComPtr<ITextureResource> loadTextureImage(
}
}
- int mipCount = (int) subresourceInitData.size();
+ int mipCount = (int)subresourceInitData.size();
ITextureResource::Desc desc = {};
desc.type = IResource::Type::Texture2D;
@@ -209,9 +213,7 @@ static std::string makeString(const char* start, const char* end)
return std::string(start, size_t(end - start));
}
-SlangResult ModelLoader::load(
- char const* inputPath,
- void** outModel)
+SlangResult ModelLoader::load(char const* inputPath, void** outModel)
{
// TODO: need to actually allocate/load the data
@@ -220,7 +222,7 @@ SlangResult ModelLoader::load(
std::vector<tinyobj::material_t> objMaterials;
std::string baseDir;
- if( auto lastSlash = strrchr(inputPath, '/') )
+ if (auto lastSlash = strrchr(inputPath, '/'))
{
baseDir = makeString(inputPath, lastSlash);
}
@@ -236,11 +238,11 @@ SlangResult ModelLoader::load(
baseDir.size() ? baseDir.c_str() : nullptr,
shouldTriangulate);
- if(!diagnostics.empty())
+ if (!diagnostics.empty())
{
printf("%s", diagnostics.c_str());
}
- if(!success)
+ if (!success)
{
return SLANG_FAIL;
}
@@ -249,28 +251,22 @@ SlangResult ModelLoader::load(
// we can actually use for rendering.
//
std::vector<void*> materials;
- for(auto& objMaterial : objMaterials)
+ for (auto& objMaterial : objMaterials)
{
MaterialData materialData;
- materialData.diffuseColor = glm::vec3(
- objMaterial.diffuse[0],
- objMaterial.diffuse[1],
- objMaterial.diffuse[2]);
+ materialData.diffuseColor =
+ glm::vec3(objMaterial.diffuse[0], objMaterial.diffuse[1], objMaterial.diffuse[2]);
- materialData.specularColor = glm::vec3(
- objMaterial.specular[0],
- objMaterial.specular[1],
- objMaterial.specular[2]);
+ materialData.specularColor =
+ glm::vec3(objMaterial.specular[0], objMaterial.specular[1], objMaterial.specular[2]);
materialData.specularity = objMaterial.shininess;
// load any referenced textures here
- if(objMaterial.diffuse_texname.length())
+ if (objMaterial.diffuse_texname.length())
{
- materialData.diffuseMap = loadTextureImage(
- device,
- objMaterial.diffuse_texname.c_str());
+ materialData.diffuseMap = loadTextureImage(device, objMaterial.diffuse_texname.c_str());
}
auto material = callbacks->createMaterial(materialData);
@@ -279,20 +275,20 @@ SlangResult ModelLoader::load(
// Flip the winding order on all faces if we are asked to...
//
- if(loadFlags & LoadFlag::FlipWinding)
+ if (loadFlags & LoadFlag::FlipWinding)
{
- for(auto& objShape : objShapes)
+ for (auto& objShape : objShapes)
{
size_t objIndexCounter = 0;
size_t objFaceCounter = 0;
- for(auto objFaceVertexCount : objShape.mesh.num_face_vertices)
+ for (auto objFaceVertexCount : objShape.mesh.num_face_vertices)
{
size_t beginIndex = objIndexCounter;
size_t endIndex = beginIndex + objFaceVertexCount;
objIndexCounter = endIndex;
size_t halfCount = objFaceVertexCount / 2;
- for(size_t ii = 0; ii < halfCount; ++ii)
+ for (size_t ii = 0; ii < halfCount; ++ii)
{
std::swap(
objShape.mesh.indices[beginIndex + ii],
@@ -300,7 +296,6 @@ SlangResult ModelLoader::load(
}
}
}
-
}
// Identify cases where a face has a vertex without a normal, and in that
@@ -311,31 +306,31 @@ SlangResult ModelLoader::load(
std::unordered_map<SmoothingGroupVertexID, size_t> smoothedVertexNormals;
size_t firstSmoothedNormalID = objVertexAttributes.normals.size() / 3;
size_t flatFaceCounter = 0;
- for(auto& objShape : objShapes)
+ for (auto& objShape : objShapes)
{
size_t objIndexCounter = 0;
size_t objFaceCounter = 0;
- for(auto objFaceVertexCount : objShape.mesh.num_face_vertices)
+ for (auto objFaceVertexCount : objShape.mesh.num_face_vertices)
{
const size_t flatFaceIndex = flatFaceCounter++;
const size_t objFaceIndex = objFaceCounter++;
size_t smoothingGroup = objShape.mesh.smoothing_group_ids[objFaceIndex];
- if(!smoothingGroup)
+ if (!smoothingGroup)
{
smoothingGroup = ~flatFaceIndex;
}
- for(size_t objFaceVertex = 0; objFaceVertex < objFaceVertexCount; ++objFaceVertex)
+ for (size_t objFaceVertex = 0; objFaceVertex < objFaceVertexCount; ++objFaceVertex)
{
tinyobj::index_t& objIndex = objShape.mesh.indices[objIndexCounter++];
- if(objIndex.normal_index < 0)
+ if (objIndex.normal_index < 0)
{
SmoothingGroupVertexID smoothVertexID;
smoothVertexID.positionID = objIndex.vertex_index;
smoothVertexID.smoothingGroup = smoothingGroup;
- if(smoothedVertexNormals.find(smoothVertexID) == smoothedVertexNormals.end())
+ if (smoothedVertexNormals.find(smoothVertexID) == smoothedVertexNormals.end())
{
size_t normalID = objVertexAttributes.normals.size() / 3;
objVertexAttributes.normals.push_back(0);
@@ -356,28 +351,29 @@ SlangResult ModelLoader::load(
// to the same smoothing group.
//
flatFaceCounter = 0;
- for(auto& objShape : objShapes)
+ for (auto& objShape : objShapes)
{
size_t objIndexCounter = 0;
size_t objFaceCounter = 0;
- for(auto objFaceVertexCount : objShape.mesh.num_face_vertices)
+ for (auto objFaceVertexCount : objShape.mesh.num_face_vertices)
{
const size_t flatFaceIndex = flatFaceCounter++;
const size_t objFaceIndex = objFaceCounter++;
size_t smoothingGroup = objShape.mesh.smoothing_group_ids[objFaceIndex];
- if(!smoothingGroup)
+ if (!smoothingGroup)
{
smoothingGroup = ~flatFaceIndex;
}
glm::vec3 faceNormal;
- if(objFaceVertexCount >= 3)
+ if (objFaceVertexCount >= 3)
{
glm::vec3 v[3];
- for(size_t objFaceVertex = 0; objFaceVertex < 3; ++objFaceVertex)
+ for (size_t objFaceVertex = 0; objFaceVertex < 3; ++objFaceVertex)
{
- tinyobj::index_t objIndex = objShape.mesh.indices[objIndexCounter + objFaceVertex];
- if(objIndex.vertex_index >= 0)
+ tinyobj::index_t objIndex =
+ objShape.mesh.indices[objIndexCounter + objFaceVertex];
+ if (objIndex.vertex_index >= 0)
{
v[objFaceVertex] = glm::vec3(
objVertexAttributes.vertices[3 * objIndex.vertex_index + 0],
@@ -389,7 +385,7 @@ SlangResult ModelLoader::load(
}
// Add this face normal to any to-be-smoothed vertex on the face.
- for(size_t objFaceVertex = 0; objFaceVertex < objFaceVertexCount; ++objFaceVertex)
+ for (size_t objFaceVertex = 0; objFaceVertex < objFaceVertexCount; ++objFaceVertex)
{
tinyobj::index_t objIndex = objShape.mesh.indices[objIndexCounter++];
@@ -398,7 +394,7 @@ SlangResult ModelLoader::load(
smoothVertexID.smoothingGroup = smoothingGroup;
auto ii = smoothedVertexNormals.find(smoothVertexID);
- if(ii != smoothedVertexNormals.end())
+ if (ii != smoothedVertexNormals.end())
{
size_t normalID = ii->second;
objVertexAttributes.normals[normalID * 3 + 0] += faceNormal.x;
@@ -413,7 +409,7 @@ SlangResult ModelLoader::load(
// we can normalize the normals to compute the area-weighted average.
//
size_t normalCount = objVertexAttributes.normals.size() / 3;
- for(size_t ii = firstSmoothedNormalID; ii < normalCount; ++ii)
+ for (size_t ii = firstSmoothedNormalID; ii < normalCount; ++ii)
{
glm::vec3 normal = glm::vec3(
objVertexAttributes.normals[3 * ii + 0],
@@ -445,18 +441,18 @@ SlangResult ModelLoader::load(
void* defaultMaterial = nullptr;
- for(auto& objShape : objShapes)
+ for (auto& objShape : objShapes)
{
size_t objIndexCounter = 0;
size_t objFaceCounter = 0;
- for(auto objFaceVertexCount : objShape.mesh.num_face_vertices)
+ for (auto objFaceVertexCount : objShape.mesh.num_face_vertices)
{
size_t objFaceIndex = objFaceCounter++;
int faceMaterialID = objShape.mesh.material_ids[objFaceIndex];
void* faceMaterial = nullptr;
- if( faceMaterialID < 0 )
+ if (faceMaterialID < 0)
{
- if( !defaultMaterial )
+ if (!defaultMaterial)
{
MaterialData defaultMaterialData;
defaultMaterialData.diffuseColor = glm::vec3(0.5, 0.5, 0.5);
@@ -469,10 +465,10 @@ SlangResult ModelLoader::load(
faceMaterial = materials[faceMaterialID];
}
- if(!currentMesh || (faceMaterial != currentMesh->material))
+ if (!currentMesh || (faceMaterial != currentMesh->material))
{
// finish old mesh.
- if(currentMesh)
+ if (currentMesh)
{
meshes.push_back(callbacks->createMesh(*currentMesh));
}
@@ -484,36 +480,39 @@ SlangResult ModelLoader::load(
currentMesh->indexCount = 0;
}
- for(size_t objFaceVertex = 0; objFaceVertex < objFaceVertexCount; ++objFaceVertex)
+ for (size_t objFaceVertex = 0; objFaceVertex < objFaceVertexCount; ++objFaceVertex)
{
tinyobj::index_t objIndex = objShape.mesh.indices[objIndexCounter++];
- ObjIndexKey objIndexKey; objIndexKey.index = objIndex;
+ ObjIndexKey objIndexKey;
+ objIndexKey.index = objIndex;
Index flatIndex = Index(-1);
auto iter = mapObjIndexToFlatIndex.find(objIndexKey);
- if(iter != mapObjIndexToFlatIndex.end())
+ if (iter != mapObjIndexToFlatIndex.end())
{
flatIndex = iter->second;
}
else
{
Vertex flatVertex;
- if(objIndex.vertex_index >= 0)
+ if (objIndex.vertex_index >= 0)
{
- flatVertex.position = scale * glm::vec3(
- objVertexAttributes.vertices[3 * objIndex.vertex_index + 0],
- objVertexAttributes.vertices[3 * objIndex.vertex_index + 1],
- objVertexAttributes.vertices[3 * objIndex.vertex_index + 2]);
+ flatVertex.position =
+ scale *
+ glm::vec3(
+ objVertexAttributes.vertices[3 * objIndex.vertex_index + 0],
+ objVertexAttributes.vertices[3 * objIndex.vertex_index + 1],
+ objVertexAttributes.vertices[3 * objIndex.vertex_index + 2]);
}
- if(objIndex.normal_index >= 0)
+ if (objIndex.normal_index >= 0)
{
flatVertex.normal = glm::vec3(
objVertexAttributes.normals[3 * objIndex.normal_index + 0],
objVertexAttributes.normals[3 * objIndex.normal_index + 1],
objVertexAttributes.normals[3 * objIndex.normal_index + 2]);
}
- if(objIndex.texcoord_index >= 0)
+ if (objIndex.texcoord_index >= 0)
{
flatVertex.uv = glm::vec2(
objVertexAttributes.texcoords[2 * objIndex.texcoord_index + 0],
@@ -532,7 +531,7 @@ SlangResult ModelLoader::load(
}
// finish last mesh.
- if(currentMesh)
+ if (currentMesh)
{
meshes.push_back(callbacks->createMesh(*currentMesh));
}
@@ -553,7 +552,8 @@ SlangResult ModelLoader::load(
vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
modelData.vertexBuffer = device->createBufferResource(vertexBufferDesc, flatVertices.data());
- if(!modelData.vertexBuffer) return SLANG_FAIL;
+ if (!modelData.vertexBuffer)
+ return SLANG_FAIL;
IBufferResource::Desc indexBufferDesc;
indexBufferDesc.type = IResource::Type::Buffer;
@@ -563,11 +563,12 @@ SlangResult ModelLoader::load(
indexBufferDesc.defaultState = ResourceState::IndexBuffer;
modelData.indexBuffer = device->createBufferResource(indexBufferDesc, flatIndices.data());
- if(!modelData.indexBuffer) return SLANG_FAIL;
+ if (!modelData.indexBuffer)
+ return SLANG_FAIL;
*outModel = callbacks->createModel(modelData);
return SLANG_OK;
}
-} // gfx
+} // namespace platform
diff --git a/tools/platform/model.h b/tools/platform/model.h
index b4aff9273..b0c625ec9 100644
--- a/tools/platform/model.h
+++ b/tools/platform/model.h
@@ -1,25 +1,26 @@
// model.h
#pragma once
+#include "platform-api.h"
+#include "slang-com-ptr.h"
#include "slang-gfx.h"
#include "vector-math.h"
-#include "slang-com-ptr.h"
-#include <vector>
-#include <string>
-#include "platform-api.h"
+#include <string>
+#include <vector>
-namespace platform {
+namespace platform
+{
struct ModelLoader
{
struct MaterialData
{
- glm::vec3 diffuseColor;
- glm::vec3 specularColor;
- float specularity;
+ glm::vec3 diffuseColor;
+ glm::vec3 specularColor;
+ float specularity;
- Slang::ComPtr<gfx::ITextureResource> diffuseMap;
+ Slang::ComPtr<gfx::ITextureResource> diffuseMap;
};
struct Vertex
@@ -36,18 +37,18 @@ struct ModelLoader
int firstIndex;
int indexCount;
- void* material;
+ void* material;
};
struct ModelData
{
Slang::ComPtr<gfx::IBufferResource> vertexBuffer;
Slang::ComPtr<gfx::IBufferResource> indexBuffer;
- gfx::PrimitiveTopology primitiveTopology;
- int vertexCount;
- int indexCount;
- int meshCount;
- void* const* meshes;
+ gfx::PrimitiveTopology primitiveTopology;
+ int vertexCount;
+ int indexCount;
+ int meshCount;
+ void* const* meshes;
};
struct ICallbacks
@@ -76,4 +77,4 @@ struct ModelLoader
};
-} // gfx
+} // namespace platform
diff --git a/tools/platform/performance-counter.h b/tools/platform/performance-counter.h
index e9e990f45..e90c2fb99 100644
--- a/tools/platform/performance-counter.h
+++ b/tools/platform/performance-counter.h
@@ -11,10 +11,7 @@ typedef std::chrono::high_resolution_clock::duration Duration;
class PerformanceCounter
{
public:
- static inline TimePoint now()
- {
- return std::chrono::high_resolution_clock::now();
- }
+ static inline TimePoint now() { return std::chrono::high_resolution_clock::now(); }
static inline Duration getElapsedTime(TimePoint counter) { return now() - counter; }
static inline float getElapsedTimeInSeconds(TimePoint counter)
{
diff --git a/tools/platform/placeholder/placeholder-window.cpp b/tools/platform/placeholder/placeholder-window.cpp
index ae4f413f8..43494d898 100644
--- a/tools/platform/placeholder/placeholder-window.cpp
+++ b/tools/platform/placeholder/placeholder-window.cpp
@@ -7,17 +7,13 @@ using namespace Slang;
namespace platform
{
-void Application::init()
-{
-}
+void Application::init() {}
-void Application::doEvents() { }
+void Application::doEvents() {}
-void Application::quit() { }
+void Application::quit() {}
-void Application::dispose()
-{
-}
+void Application::dispose() {}
void Application::run(Window* mainWindow, bool waitForEvents)
{
@@ -25,7 +21,10 @@ void Application::run(Window* mainWindow, bool waitForEvents)
SLANG_UNUSED(waitForEvents);
}
-Window* Application::createWindow(const WindowDesc& desc) { return nullptr; }
+Window* Application::createWindow(const WindowDesc& desc)
+{
+ return nullptr;
+}
} // namespace platform
diff --git a/tools/platform/platform-api.h b/tools/platform/platform-api.h
index b04e5ffce..1b95e677c 100644
--- a/tools/platform/platform-api.h
+++ b/tools/platform/platform-api.h
@@ -2,22 +2,22 @@
#define SLANG_PLATFORM_API_H
#if defined(SLANG_PLATFORM_DYNAMIC)
-# if defined(_MSC_VER)
-# ifdef SLANG_PLATFORM_DYNAMIC_EXPORT
-# define SLANG_PLATFORM_API SLANG_DLL_EXPORT
-# else
-# define SLANG_PLATFORM_API __declspec(dllimport)
-# endif
-# else
+#if defined(_MSC_VER)
+#ifdef SLANG_PLATFORM_DYNAMIC_EXPORT
+#define SLANG_PLATFORM_API SLANG_DLL_EXPORT
+#else
+#define SLANG_PLATFORM_API __declspec(dllimport)
+#endif
+#else
// TODO: need to consider compiler capabilities
-//# ifdef SLANG_DYNAMIC_EXPORT
-# define SLANG_PLATFORM_API SLANG_DLL_EXPORT
-//# endif
-# endif
+// # ifdef SLANG_DYNAMIC_EXPORT
+#define SLANG_PLATFORM_API SLANG_DLL_EXPORT
+// # endif
+#endif
#endif
#ifndef SLANG_PLATFORM_API
-# define SLANG_PLATFORM_API
+#define SLANG_PLATFORM_API
#endif
#endif
diff --git a/tools/platform/vector-math.h b/tools/platform/vector-math.h
index e35cb46ac..2e24833eb 100644
--- a/tools/platform/vector-math.h
+++ b/tools/platform/vector-math.h
@@ -4,12 +4,13 @@
// We will use the GLM library for our vector math types, just for simplicity.
#include "../../external/glm/glm/glm.hpp"
-#include "../../external/glm/glm/gtc/matrix_transform.hpp"
#include "../../external/glm/glm/gtc/constants.hpp"
+#include "../../external/glm/glm/gtc/matrix_transform.hpp"
#include "../../external/glm/glm/gtc/quaternion.hpp"
-namespace gfx {
+namespace gfx
+{
using namespace glm;
-} // gfx
+} // namespace gfx
diff --git a/tools/platform/window.h b/tools/platform/window.h
index 29327def3..a419f85b9 100644
--- a/tools/platform/window.h
+++ b/tools/platform/window.h
@@ -1,13 +1,13 @@
// window.h
#pragma once
+#include "platform-api.h"
#include "slang-com-ptr.h"
#include "source/core/slang-basic.h"
#include "source/core/slang-func-ptr.h"
-#include "platform-api.h"
-
-namespace platform {
+namespace platform
+{
enum class KeyCode : uint32_t
{
@@ -139,8 +139,13 @@ struct ButtonState
{
enum Enum
{
- None = 0, LeftButton = 1, RightButton = 2, MiddleButton = 4,
- Shift = 8, Control = 16, Alt = 32
+ None = 0,
+ LeftButton = 1,
+ RightButton = 2,
+ MiddleButton = 4,
+ Shift = 8,
+ Control = 16,
+ Alt = 32
};
};
@@ -167,7 +172,8 @@ struct Rect
enum class WindowStyle
{
- Default, FixedSize,
+ Default,
+ FixedSize,
};
struct WindowDesc
@@ -226,37 +232,38 @@ public:
#ifdef _WIN32
-# ifdef _MSC_VER
-# ifdef _DEBUG
-# define GFX_DUMP_LEAK _CrtDumpMemoryLeaks();
-# endif
-# endif
-# ifndef GFX_DUMP_LEAK
-# define GFX_DUMP_LEAK
-# endif
-# define PLATFORM_UI_MAIN(APPLICATION_ENTRY) \
- int __stdcall wWinMain( \
- void* /*instance*/, \
- void* /* prevInstance */, \
- void* /* commandLine */, \
- int /*showCommand*/) \
- { \
- platform::Application::init(); \
- auto result = APPLICATION_ENTRY(0, nullptr); \
- platform::Application::dispose(); \
- GFX_DUMP_LEAK \
- return result; \
- }
+#ifdef _MSC_VER
+#ifdef _DEBUG
+#define GFX_DUMP_LEAK _CrtDumpMemoryLeaks();
+#endif
+#endif
+#ifndef GFX_DUMP_LEAK
+#define GFX_DUMP_LEAK
+#endif
+#define PLATFORM_UI_MAIN(APPLICATION_ENTRY) \
+ int __stdcall wWinMain( \
+ void* /*instance*/, \
+ void* /* prevInstance */, \
+ void* /* commandLine */, \
+ int /*showCommand*/ \
+ ) \
+ { \
+ platform::Application::init(); \
+ auto result = APPLICATION_ENTRY(0, nullptr); \
+ platform::Application::dispose(); \
+ GFX_DUMP_LEAK \
+ return result; \
+ }
#else
-#define PLATFORM_UI_MAIN(APPLICATION_ENTRY) \
- int main(int argc, char** argv) \
- { \
- platform::Application::init(); \
- auto rs = APPLICATION_ENTRY(argc, argv); \
- platform::Application::dispose(); \
- return rs; \
+#define PLATFORM_UI_MAIN(APPLICATION_ENTRY) \
+ int main(int argc, char** argv) \
+ { \
+ platform::Application::init(); \
+ auto rs = APPLICATION_ENTRY(argc, argv); \
+ platform::Application::dispose(); \
+ return rs; \
}
#endif
diff --git a/tools/platform/windows/win-window.cpp b/tools/platform/windows/win-window.cpp
index 896bbd2c6..9c4b79b39 100644
--- a/tools/platform/windows/win-window.cpp
+++ b/tools/platform/windows/win-window.cpp
@@ -83,10 +83,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
bool processed = false;
if (window)
{
- window->events.mouseUp(MouseEventArgs{
- mx,
- my,
- 0, getModifierState(wParam)});
+ window->events.mouseUp(MouseEventArgs{mx, my, 0, getModifierState(wParam)});
}
}
break;
@@ -126,8 +123,8 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (window)
{
- KeyEventArgs keyEventArgs = {
- KeyCode::None, (wchar_t)(wParam), ButtonState::Enum::None, false};
+ KeyEventArgs keyEventArgs =
+ {KeyCode::None, (wchar_t)(wParam), ButtonState::Enum::None, false};
window->events.keyPress(keyEventArgs);
if (keyEventArgs.cancelEvent)
useDefProc = false;
@@ -187,8 +184,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
- default:
- break;
+ default: break;
}
if (message == WM_DESTROY && hWnd == Win32AppContext::mainWindowHandle)
{
@@ -221,9 +217,13 @@ void registerWindowClass()
RegisterClassExW(&wcex);
}
-void unregisterWindowClass() { UnregisterClassW(kWindowClassName, GetModuleHandle(NULL)); }
+void unregisterWindowClass()
+{
+ UnregisterClassW(kWindowClassName, GetModuleHandle(NULL));
+}
-HRESULT(WINAPI* getDpiForMonitor) (void* hmonitor, int dpiType, unsigned int* dpiX, unsigned int* dpiY);
+HRESULT(WINAPI* getDpiForMonitor)
+(void* hmonitor, int dpiType, unsigned int* dpiX, unsigned int* dpiY);
void Application::init()
{
@@ -272,9 +272,15 @@ void doEventsImpl(bool waitForEvents)
} while (!Win32AppContext::isTerminated && hasMsg);
}
-void Application::doEvents() { doEventsImpl(false); }
+void Application::doEvents()
+{
+ doEventsImpl(false);
+}
-void Application::quit() { Win32AppContext::isTerminated = true; }
+void Application::quit()
+{
+ Win32AppContext::isTerminated = true;
+}
void Application::dispose()
{
@@ -407,10 +413,7 @@ public:
}
virtual bool getFocused() override { return GetFocus() == handle; }
virtual bool getVisible() override { return visible; }
- virtual WindowHandle getNativeHandle() override
- {
- return WindowHandle::fromHwnd(handle);
- }
+ virtual WindowHandle getNativeHandle() override { return WindowHandle::fromHwnd(handle); }
virtual void setText(Slang::String text) override
{
SetWindowText(handle, text.toWString().begin());
@@ -442,9 +445,12 @@ public:
}
};
-Window* Application::createWindow(const WindowDesc& desc) { return new Win32PlatformWindow(desc); }
+Window* Application::createWindow(const WindowDesc& desc)
+{
+ return new Win32PlatformWindow(desc);
+}
-} // namespace gfx
+} // namespace platform
#endif
diff --git a/tools/render-test/diagnostic-defs.h b/tools/render-test/diagnostic-defs.h
index e48012550..58f1fe6a6 100644
--- a/tools/render-test/diagnostic-defs.h
+++ b/tools/render-test/diagnostic-defs.h
@@ -14,7 +14,7 @@
// for any arguments.
#ifndef DIAGNOSTIC
-#error Need to #define DIAGNOSTIC(...) before including
+#error Need to #define DIAGNOSTIC(...) before including
#define DIAGNOSTIC(id, severity, name, messageFormat) /* */
#endif
@@ -23,8 +23,16 @@
//
-DIAGNOSTIC(1001, Error, expectingCommaComputeDispatch, "expected 3 comma separated integers for compute dispatch size")
-DIAGNOSTIC(1002, Error, expectingPositiveComputeDispatch, "expected 3 comma positive integers for compute dispatch size")
+DIAGNOSTIC(
+ 1001,
+ Error,
+ expectingCommaComputeDispatch,
+ "expected 3 comma separated integers for compute dispatch size")
+DIAGNOSTIC(
+ 1002,
+ Error,
+ expectingPositiveComputeDispatch,
+ "expected 3 comma positive integers for compute dispatch size")
DIAGNOSTIC(1003, Error, unknownSourceLanguage, "unknown source language name")
DIAGNOSTIC(1003, Error, unknown, "unknown source language name")
DIAGNOSTIC(1004, Error, unknownCommandLineOption, "unknown command-line option '$0'")
diff --git a/tools/render-test/diagnostics.cpp b/tools/render-test/diagnostics.cpp
index 2bc337256..929642976 100644
--- a/tools/render-test/diagnostics.cpp
+++ b/tools/render-test/diagnostics.cpp
@@ -1,18 +1,19 @@
// diagnostics.cpp
#include "diagnostics.h"
-namespace Slang {
+namespace Slang
+{
namespace RenderTestDiagnostics
{
-#define DIAGNOSTIC(id, severity, name, messageFormat) const DiagnosticInfo name = { id, Severity::severity, #name, messageFormat };
+#define DIAGNOSTIC(id, severity, name, messageFormat) \
+ const DiagnosticInfo name = {id, Severity::severity, #name, messageFormat};
#include "diagnostic-defs.h"
#undef DIAGNOSTIC
-}
+} // namespace RenderTestDiagnostics
-static const DiagnosticInfo* const kDiagnostics[] =
-{
-#define DIAGNOSTIC(id, severity, name, messageFormat) &RenderTestDiagnostics::name,
+static const DiagnosticInfo* const kDiagnostics[] = {
+#define DIAGNOSTIC(id, severity, name, messageFormat) &RenderTestDiagnostics::name,
#include "diagnostic-defs.h"
#undef DIAGNOSTIC
};
diff --git a/tools/render-test/diagnostics.h b/tools/render-test/diagnostics.h
index fa4c8a389..26872f5fa 100644
--- a/tools/render-test/diagnostics.h
+++ b/tools/render-test/diagnostics.h
@@ -1,12 +1,10 @@
#ifndef SLANG_CORE_DIAGNOSTICS_H
#define SLANG_CORE_DIAGNOSTICS_H
+#include "../../source/compiler-core/slang-diagnostic-sink.h"
+#include "../../source/compiler-core/slang-source-loc.h"
#include "../../source/core/slang-basic.h"
#include "../../source/core/slang-writer.h"
-
-#include "../../source/compiler-core/slang-source-loc.h"
-#include "../../source/compiler-core/slang-diagnostic-sink.h"
-
#include "slang.h"
namespace Slang
@@ -18,8 +16,8 @@ namespace RenderTestDiagnostics
{
#define DIAGNOSTIC(id, severity, name, messageFormat) extern const DiagnosticInfo name;
#include "diagnostic-defs.h"
-}
+} // namespace RenderTestDiagnostics
-}
+} // namespace Slang
#endif
diff --git a/tools/render-test/options.cpp b/tools/render-test/options.cpp
index 07e8b0e2a..68efacca3 100644
--- a/tools/render-test/options.cpp
+++ b/tools/render-test/options.cpp
@@ -2,24 +2,22 @@
#include "options.h"
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "../../source/core/slang-writer.h"
-#include "../../source/core/slang-render-api-util.h"
-
#include "../../source/core/slang-list.h"
+#include "../../source/core/slang-render-api-util.h"
#include "../../source/core/slang-string-util.h"
-//#include "../../source/core/slang-downstream-compiler.h"
+#include "../../source/core/slang-writer.h"
-#include "../../source/core/slang-type-text-util.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+// #include "../../source/core/slang-downstream-compiler.h"
#include "../../source/compiler-core/slang-command-line-args.h"
-
+#include "../../source/core/slang-type-text-util.h"
#include "diagnostics.h"
-namespace renderer_test {
+namespace renderer_test
+{
using namespace Slang;
static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
@@ -34,12 +32,15 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
case RenderApiType::CPU: return rhi::DeviceType::CPU;
case RenderApiType::CUDA: return rhi::DeviceType::CUDA;
case RenderApiType::WebGPU: return rhi::DeviceType::WGPU;
- default:
- return rhi::DeviceType::Default;
+ default: return rhi::DeviceType::Default;
}
}
-/* static */SlangResult Options::parse(int argc, const char*const* argv, Slang::WriterHelper stdError, Options& outOptions)
+/* static */ SlangResult Options::parse(
+ int argc,
+ const char* const* argv,
+ Slang::WriterHelper stdError,
+ Options& outOptions)
{
using namespace Slang;
@@ -48,7 +49,7 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
DiagnosticSink sink(cmdLineContext->getSourceManager(), nullptr);
sink.writer = stdError.getWriter();
sink.setFlag(DiagnosticSink::Flag::SourceLocationLine);
-
+
outOptions = Options();
CommandLineArgs args(cmdLineContext);
@@ -78,7 +79,7 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
CommandLineArg arg = reader.getArgAndAdvance();
const auto& argValue = arg.value;
- if(!argValue.startsWith("-"))
+ if (!argValue.startsWith("-"))
{
positionalArgs.add(arg);
continue;
@@ -92,7 +93,7 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
}
break;
}
- else if(argValue == "-o")
+ else if (argValue == "-o")
{
SLANG_RETURN_ON_FAIL(reader.expectArg(outOptions.outputPath));
}
@@ -113,7 +114,7 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
outOptions.renderFeatures.add(value);
}
}
- else if( argValue == "-xslang" || argValue == "-compile-arg")
+ else if (argValue == "-xslang" || argValue == "-compile-arg")
{
// This is legacy support, should use -Xslang now
// This is an option that we want to pass along to Slang
@@ -121,14 +122,14 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
SLANG_RETURN_ON_FAIL(reader.expectArg(slangArg));
outOptions.downstreamArgs.getArgsByName("slang").add(slangArg);
}
- else if (argValue == "-compute")
- {
- outOptions.shaderType = ShaderProgramType::Compute;
- }
- else if (argValue == "-graphics")
- {
- outOptions.shaderType = ShaderProgramType::Graphics;
- }
+ else if (argValue == "-compute")
+ {
+ outOptions.shaderType = ShaderProgramType::Compute;
+ }
+ else if (argValue == "-graphics")
+ {
+ outOptions.shaderType = ShaderProgramType::Graphics;
+ }
else if (argValue == "-gcompute")
{
outOptions.shaderType = ShaderProgramType::GraphicsCompute;
@@ -145,17 +146,17 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
{
outOptions.shaderType = ShaderProgramType::GraphicsTaskMeshCompute;
}
- else if(argValue == "-use-dxil")
+ else if (argValue == "-use-dxil")
{
outOptions.useDXIL = true;
}
else if (argValue == "-emit-spirv-directly")
{
- outOptions.generateSPIRVDirectly= true;
+ outOptions.generateSPIRVDirectly = true;
}
else if (argValue == "-emit-spirv-via-glsl")
{
- outOptions.generateSPIRVDirectly= false;
+ outOptions.generateSPIRVDirectly = false;
}
else if (argValue == "-only-startup")
{
@@ -178,10 +179,12 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
StringUtil::split(dispatchSize.value.getUnownedSlice(), ',', slices);
if (slices.getCount() != 3)
{
- sink.diagnose(dispatchSize.loc, RenderTestDiagnostics::expectingCommaComputeDispatch);
+ sink.diagnose(
+ dispatchSize.loc,
+ RenderTestDiagnostics::expectingCommaComputeDispatch);
return SLANG_FAIL;
}
-
+
String string;
for (Index i = 0; i < 3; ++i)
{
@@ -189,7 +192,9 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
int v = stringToInt(string);
if (v < 1)
{
- sink.diagnose(dispatchSize.loc, RenderTestDiagnostics::expectingPositiveComputeDispatch);
+ sink.diagnose(
+ dispatchSize.loc,
+ RenderTestDiagnostics::expectingPositiveComputeDispatch);
return SLANG_FAIL;
}
outOptions.computeDispatchSize[i] = v;
@@ -199,8 +204,9 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
{
CommandLineArg sourceLanguageName;
SLANG_RETURN_ON_FAIL(reader.expectArg(sourceLanguageName));
-
- const SlangSourceLanguage sourceLanguage = TypeTextUtil::findSourceLanguage(sourceLanguageName.value.getUnownedSlice());
+
+ const SlangSourceLanguage sourceLanguage =
+ TypeTextUtil::findSourceLanguage(sourceLanguageName.value.getUnownedSlice());
if (sourceLanguage == SLANG_SOURCE_LANGUAGE_UNKNOWN)
{
sink.diagnose(sourceLanguageName.loc, RenderTestDiagnostics::unknownSourceLanguage);
@@ -209,7 +215,7 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
outOptions.sourceLanguage = sourceLanguage;
}
- else if(argValue == "-no-default-entry-point")
+ else if (argValue == "-no-default-entry-point")
{
outOptions.dontAddDefaultEntryPoints = true;
}
@@ -252,12 +258,17 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
}
// Lookup the target language type
- DeviceType targetLanguageDeviceType = _toRenderType(RenderApiUtil::findImplicitLanguageRenderApiType(argName));
-
+ DeviceType targetLanguageDeviceType =
+ _toRenderType(RenderApiUtil::findImplicitLanguageRenderApiType(argName));
+
if (targetLanguageDeviceType != DeviceType::Default || argName == "glsl")
{
outOptions.targetLanguageDeviceType = targetLanguageDeviceType;
- outOptions.inputLanguageID = (argName == "hlsl" || argName == "glsl" || argName == "cpp" || argName == "cxx" || argName == "c") ? InputLanguageID::Native : InputLanguageID::Slang;
+ outOptions.inputLanguageID =
+ (argName == "hlsl" || argName == "glsl" || argName == "cpp" ||
+ argName == "cxx" || argName == "c")
+ ? InputLanguageID::Native
+ : InputLanguageID::Slang;
continue;
}
}
@@ -266,26 +277,26 @@ static rhi::DeviceType _toRenderType(Slang::RenderApiType apiType)
}
}
- // If a render option isn't set use defaultRenderType
+ // If a render option isn't set use defaultRenderType
outOptions.deviceType = (outOptions.deviceType == DeviceType::Default)
? outOptions.targetLanguageDeviceType
: outOptions.deviceType;
// first positional argument is source shader path
- if(positionalArgs.getCount())
+ if (positionalArgs.getCount())
{
outOptions.sourcePath = positionalArgs[0].value;
positionalArgs.removeAt(0);
}
// any remaining arguments represent an error
- if(positionalArgs.getCount() != 0)
+ if (positionalArgs.getCount() != 0)
{
sink.diagnose(positionalArgs[0].loc, RenderTestDiagnostics::unexpectedPositionalArg);
return SLANG_FAIL;
}
- return SLANG_OK;
+ return SLANG_OK;
}
-} // renderer_test
+} // namespace renderer_test
diff --git a/tools/render-test/options.h b/tools/render-test/options.h
index bd5e65a1a..2497ce782 100644
--- a/tools/render-test/options.h
+++ b/tools/render-test/options.h
@@ -7,16 +7,15 @@
#define SLANG_HANDLE_RESULT_FAIL(x) assert(!"failure")
#endif
-#include "slang-com-helper.h"
-#include "../../source/core/slang-writer.h"
-
-#include "../../source/core/slang-process-util.h"
-
#include "../../source/compiler-core/slang-command-line-args.h"
+#include "../../source/core/slang-process-util.h"
+#include "../../source/core/slang-writer.h"
+#include "slang-com-helper.h"
#include <slang-rhi.h>
-namespace renderer_test {
+namespace renderer_test
+{
using namespace rhi;
@@ -50,16 +49,17 @@ struct Options
Slang::String appName = "render-test";
Slang::String sourcePath;
Slang::String outputPath;
- ShaderProgramType shaderType = ShaderProgramType::Graphics;
+ ShaderProgramType shaderType = ShaderProgramType::Graphics;
- /// The renderer type inferred from the target language type. Used if a rendererType is not explicitly set.
+ /// The renderer type inferred from the target language type. Used if a rendererType is not
+ /// explicitly set.
DeviceType targetLanguageDeviceType = DeviceType::Default;
- /// The set render type
+ /// The set render type
DeviceType deviceType = DeviceType::Default;
InputLanguageID inputLanguageID = InputLanguageID::Slang;
SlangSourceLanguage sourceLanguage = SLANG_SOURCE_LANGUAGE_UNKNOWN;
- /// Can be used for overriding the profile
+ /// Can be used for overriding the profile
Slang::String profileName;
bool outputUsingType = false;
@@ -77,19 +77,23 @@ struct Options
Slang::String entryPointName;
- Slang::List<Slang::String> renderFeatures; /// Required render features for this test to run
+ Slang::List<Slang::String> renderFeatures; /// Required render features for this test to run
- uint32_t computeDispatchSize[3] = { 1, 1, 1 };
+ uint32_t computeDispatchSize[3] = {1, 1, 1};
- Slang::String nvapiExtnSlot; ///< The nvapiRegister to use.
+ Slang::String nvapiExtnSlot; ///< The nvapiRegister to use.
- Slang::DownstreamArgs downstreamArgs; ///< Args to downstream tools. Here it's just slang
+ Slang::DownstreamArgs downstreamArgs; ///< Args to downstream tools. Here it's just slang
bool generateSPIRVDirectly = true;
Options() { downstreamArgs.addName("slang"); }
- static SlangResult parse(int argc, const char*const* argv, Slang::WriterHelper stdError, Options& outOptions);
+ static SlangResult parse(
+ int argc,
+ const char* const* argv,
+ Slang::WriterHelper stdError,
+ Options& outOptions);
};
-} // renderer_test
+} // namespace renderer_test
diff --git a/tools/render-test/png-serialize-util.cpp b/tools/render-test/png-serialize-util.cpp
index dc1a9f241..8a649ee87 100644
--- a/tools/render-test/png-serialize-util.cpp
+++ b/tools/render-test/png-serialize-util.cpp
@@ -3,13 +3,14 @@
#include "png-serialize-util.h"
-#include <stdlib.h>
#include <stdio.h>
+#include <stdlib.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "external/stb/stb_image_write.h"
-namespace renderer_test {
+namespace renderer_test
+{
using namespace Slang;
/* static */ Slang::Result PngSerializeUtil::write(
@@ -24,4 +25,4 @@ using namespace Slang;
return stbResult ? SLANG_OK : SLANG_FAIL;
}
-} // renderer_test
+} // namespace renderer_test
diff --git a/tools/render-test/png-serialize-util.h b/tools/render-test/png-serialize-util.h
index 80eda3729..4eb119b30 100644
--- a/tools/render-test/png-serialize-util.h
+++ b/tools/render-test/png-serialize-util.h
@@ -3,12 +3,16 @@
#include "core/slang-blob.h"
-namespace renderer_test {
+namespace renderer_test
+{
struct PngSerializeUtil
{
- static Slang::Result write(const char* filename, ISlangBlob* pixels, uint32_t width, uint32_t height);
-
+ static Slang::Result write(
+ const char* filename,
+ ISlangBlob* pixels,
+ uint32_t width,
+ uint32_t height);
};
-} // renderer_test
+} // namespace renderer_test
diff --git a/tools/render-test/render-test-main.cpp b/tools/render-test/render-test-main.cpp
index 7d8f3a8aa..a36121af0 100644
--- a/tools/render-test/render-test-main.cpp
+++ b/tools/render-test/render-test-main.cpp
@@ -2,35 +2,32 @@
#define _CRT_SECURE_NO_WARNINGS 1
-#include "options.h"
-#include <slang-rhi.h>
-#include <slang-rhi/shader-cursor.h>
-#include <slang-rhi/acceleration-structure-utils.h>
-#include "slang-support.h"
-#include "png-serialize-util.h"
-
-#include "shader-renderer-util.h"
-
+#include "../../source/core/slang-test-tool-util.h"
#include "../source/core/slang-io.h"
#include "../source/core/slang-string-util.h"
-
#include "core/slang-token-reader.h"
-
+#include "options.h"
+#include "png-serialize-util.h"
#include "shader-input-layout.h"
-#include <stdio.h>
-#include <stdlib.h>
-
+#include "shader-renderer-util.h"
+#include "slang-support.h"
#include "window.h"
-#include "../../source/core/slang-test-tool-util.h"
+#include <slang-rhi.h>
+#include <slang-rhi/acceleration-structure-utils.h>
+#include <slang-rhi/shader-cursor.h>
+#include <stdio.h>
+#include <stdlib.h>
#define ENABLE_RENDERDOC_INTEGRATION 0
#if ENABLE_RENDERDOC_INTEGRATION
-# include "external/renderdoc_app.h"
-# include <windows.h>
+#include "external/renderdoc_app.h"
+
+#include <windows.h>
#endif
-namespace renderer_test {
+namespace renderer_test
+{
using Slang::Result;
@@ -50,11 +47,10 @@ struct Vertex
float uv[2];
};
-static const Vertex kVertexData[] =
-{
- { { 0, 0, 0.5 }, {1, 0, 0} , {0, 0} },
- { { 0, 1, 0.5 }, {0, 0, 1} , {1, 0} },
- { { 1, 0, 0.5 }, {0, 1, 0} , {1, 1} },
+static const Vertex kVertexData[] = {
+ {{0, 0, 0.5}, {1, 0, 0}, {0, 0}},
+ {{0, 1, 0.5}, {0, 0, 1}, {1, 0}},
+ {{1, 0, 0.5}, {0, 1, 0}, {1, 1}},
};
static const int kVertexCount = SLANG_COUNT_OF(kVertexData);
@@ -73,8 +69,8 @@ struct ShaderOutputPlan
{
struct Item
{
- ComPtr<IResource> resource;
- slang::TypeLayoutReflection* typeLayout = nullptr;
+ ComPtr<IResource> resource;
+ slang::TypeLayoutReflection* typeLayout = nullptr;
};
List<Item> items;
@@ -153,28 +149,32 @@ protected:
struct AssignValsFromLayoutContext
{
- IDevice* device;
- slang::ISession* slangSession;
- ShaderOutputPlan& outputPlan;
- slang::ProgramLayout* slangReflection;
+ IDevice* device;
+ slang::ISession* slangSession;
+ ShaderOutputPlan& outputPlan;
+ slang::ProgramLayout* slangReflection;
IAccelerationStructure* accelerationStructure;
AssignValsFromLayoutContext(
- IDevice* device,
- slang::ISession* slangSession,
- ShaderOutputPlan& outputPlan,
- slang::ProgramLayout* slangReflection,
- IAccelerationStructure* accelerationStructure)
+ IDevice* device,
+ slang::ISession* slangSession,
+ ShaderOutputPlan& outputPlan,
+ slang::ProgramLayout* slangReflection,
+ IAccelerationStructure* accelerationStructure)
: device(device)
, slangSession(slangSession)
, outputPlan(outputPlan)
, slangReflection(slangReflection)
, accelerationStructure(accelerationStructure)
- {}
+ {
+ }
- void maybeAddOutput(ShaderCursor const& dstCursor, ShaderInputLayout::Val* srcVal, IResource* resource)
+ void maybeAddOutput(
+ ShaderCursor const& dstCursor,
+ ShaderInputLayout::Val* srcVal,
+ IResource* resource)
{
- if(srcVal->isOutput)
+ if (srcVal->isOutput)
{
ShaderOutputPlan::Item item;
item.resource = resource;
@@ -188,16 +188,14 @@ struct AssignValsFromLayoutContext
const size_t bufferSize = srcVal->bufferData.getCount() * sizeof(uint32_t);
ShaderCursor dataCursor = dstCursor;
- switch(dataCursor.getTypeLayout()->getKind())
+ switch (dataCursor.getTypeLayout()->getKind())
{
case slang::TypeReflection::Kind::ConstantBuffer:
case slang::TypeReflection::Kind::ParameterBlock:
dataCursor = dataCursor.getDereferenced();
break;
- default:
- break;
-
+ default: break;
}
SLANG_RETURN_ON_FAIL(dataCursor.setData(srcVal->bufferData.getBuffer(), bufferSize));
@@ -208,19 +206,26 @@ struct AssignValsFromLayoutContext
{
const InputBufferDesc& srcBuffer = srcVal->bufferDesc;
auto& bufferData = srcVal->bufferData;
- const size_t bufferSize = Math::Max((size_t)bufferData.getCount() * sizeof(uint32_t), (size_t)(srcBuffer.elementCount * srcBuffer.stride));
+ const size_t bufferSize = Math::Max(
+ (size_t)bufferData.getCount() * sizeof(uint32_t),
+ (size_t)(srcBuffer.elementCount * srcBuffer.stride));
bufferData.reserve(bufferSize / sizeof(uint32_t));
for (size_t i = bufferData.getCount(); i < bufferSize / sizeof(uint32_t); i++)
bufferData.add(0);
ComPtr<IBuffer> bufferResource;
- SLANG_RETURN_ON_FAIL(ShaderRendererUtil::createBuffer(srcBuffer, /*entry.isOutput,*/ bufferSize, bufferData.getBuffer(), device, bufferResource));
+ SLANG_RETURN_ON_FAIL(ShaderRendererUtil::createBuffer(
+ srcBuffer,
+ /*entry.isOutput,*/ bufferSize,
+ bufferData.getBuffer(),
+ device,
+ bufferResource));
ComPtr<IBuffer> counterResource;
const auto explicitCounterCursor = dstCursor.getExplicitCounter();
- if(srcBuffer.counter != ~0u)
+ if (srcBuffer.counter != ~0u)
{
- if(explicitCounterCursor.isValid())
+ if (explicitCounterCursor.isValid())
{
// If this cursor has a full buffer object associated with the
// resource, then assign to that.
@@ -244,11 +249,10 @@ struct AssignValsFromLayoutContext
sizeof(srcBuffer.counter),
&srcBuffer.counter,
device,
- counterResource
- ));
+ counterResource));
}
}
- else if(explicitCounterCursor.isValid())
+ else if (explicitCounterCursor.isValid())
{
// If we know we require a counter for this resource but haven't
// been given one, error
@@ -268,14 +272,19 @@ struct AssignValsFromLayoutContext
return SLANG_OK;
}
- SlangResult assignCombinedTextureSampler(ShaderCursor const& dstCursor, ShaderInputLayout::CombinedTextureSamplerVal* srcVal)
+ SlangResult assignCombinedTextureSampler(
+ ShaderCursor const& dstCursor,
+ ShaderInputLayout::CombinedTextureSamplerVal* srcVal)
{
auto& textureEntry = srcVal->textureVal;
auto& samplerEntry = srcVal->samplerVal;
ComPtr<ITexture> texture;
SLANG_RETURN_ON_FAIL(ShaderRendererUtil::generateTexture(
- textureEntry->textureDesc, ResourceState::ShaderResource, device, texture));
+ textureEntry->textureDesc,
+ ResourceState::ShaderResource,
+ device,
+ texture));
auto sampler = _createSampler(device, samplerEntry->samplerDesc);
@@ -288,11 +297,15 @@ struct AssignValsFromLayoutContext
SlangResult assignTexture(ShaderCursor const& dstCursor, ShaderInputLayout::TextureVal* srcVal)
{
ComPtr<ITexture> texture;
- ResourceState defaultState = srcVal->textureDesc.isRWTexture ?
- ResourceState::UnorderedAccess : ResourceState::ShaderResource;
+ ResourceState defaultState = srcVal->textureDesc.isRWTexture
+ ? ResourceState::UnorderedAccess
+ : ResourceState::ShaderResource;
SLANG_RETURN_ON_FAIL(ShaderRendererUtil::generateTexture(
- srcVal->textureDesc, defaultState, device, texture));
+ srcVal->textureDesc,
+ defaultState,
+ device,
+ texture));
dstCursor.setBinding(texture);
maybeAddOutput(dstCursor, srcVal, texture);
@@ -310,17 +323,19 @@ struct AssignValsFromLayoutContext
SlangResult assignAggregate(ShaderCursor const& dstCursor, ShaderInputLayout::AggVal* srcVal)
{
Index fieldCount = srcVal->fields.getCount();
- for(Index fieldIndex = 0; fieldIndex < fieldCount; ++fieldIndex)
+ for (Index fieldIndex = 0; fieldIndex < fieldCount; ++fieldIndex)
{
auto& field = srcVal->fields[fieldIndex];
- if(field.name.getLength() == 0)
+ if (field.name.getLength() == 0)
{
// If no name was given, assume by-indexing matching is requested
auto fieldCursor = dstCursor.getElement((GfxIndex)fieldIndex);
- if(!fieldCursor.isValid())
+ if (!fieldCursor.isValid())
{
- StdWriters::getError().print("error: could not find shader parameter at index %d\n", (int)fieldIndex);
+ StdWriters::getError().print(
+ "error: could not find shader parameter at index %d\n",
+ (int)fieldIndex);
return SLANG_E_INVALID_ARG;
}
SLANG_RETURN_ON_FAIL(assign(fieldCursor, field.val));
@@ -328,9 +343,11 @@ struct AssignValsFromLayoutContext
else
{
auto fieldCursor = dstCursor.getPath(field.name.getBuffer());
- if(!fieldCursor.isValid())
+ if (!fieldCursor.isValid())
{
- StdWriters::getError().print("error: could not find shader parameter matching '%s'\n", field.name.begin());
+ StdWriters::getError().print(
+ "error: could not find shader parameter matching '%s'\n",
+ field.name.begin());
return SLANG_E_INVALID_ARG;
}
SLANG_RETURN_ON_FAIL(assign(fieldCursor, field.val));
@@ -343,7 +360,7 @@ struct AssignValsFromLayoutContext
{
auto typeName = srcVal->typeName;
slang::TypeReflection* slangType = nullptr;
- if(typeName.getLength() != 0)
+ if (typeName.getLength() != 0)
{
// If the input line specified the name of the type
// to allocate, then we use it directly.
@@ -357,10 +374,9 @@ struct AssignValsFromLayoutContext
// value pointed to by `entryCursor`.
//
auto slangTypeLayout = dstCursor.getTypeLayout();
- switch(slangTypeLayout->getKind())
+ switch (slangTypeLayout->getKind())
{
- default:
- break;
+ default: break;
case slang::TypeReflection::Kind::ConstantBuffer:
case slang::TypeReflection::Kind::ParameterBlock:
@@ -376,7 +392,11 @@ struct AssignValsFromLayoutContext
}
ComPtr<IShaderObject> shaderObject;
- device->createShaderObject2(slangSession, slangType, ShaderObjectContainerType::None, shaderObject.writeRef());
+ device->createShaderObject2(
+ slangSession,
+ slangType,
+ ShaderObjectContainerType::None,
+ shaderObject.writeRef());
SLANG_RETURN_ON_FAIL(assign(ShaderCursor(shaderObject), srcVal->contentVal));
dstCursor.setObject(shaderObject);
@@ -394,7 +414,9 @@ struct AssignValsFromLayoutContext
auto slangType = slangReflection->findTypeByName(typeName.getBuffer());
if (!slangType)
{
- StdWriters::getError().print("error: could not find shader type '%s'\n", typeName.getBuffer());
+ StdWriters::getError().print(
+ "error: could not find shader type '%s'\n",
+ typeName.getBuffer());
return SLANG_E_INVALID_ARG;
}
args.add(slang::SpecializationArg::fromType(slangType));
@@ -405,7 +427,7 @@ struct AssignValsFromLayoutContext
SlangResult assignArray(ShaderCursor const& dstCursor, ShaderInputLayout::ArrayVal* srcVal)
{
Index elementCounter = 0;
- for(auto elementVal : srcVal->vals)
+ for (auto elementVal : srcVal->vals)
{
Index elementIndex = elementCounter++;
SLANG_RETURN_ON_FAIL(assign(dstCursor[elementIndex], elementVal));
@@ -424,57 +446,59 @@ struct AssignValsFromLayoutContext
SlangResult assign(ShaderCursor const& dstCursor, ShaderInputLayout::ValPtr const& srcVal)
{
auto& entryCursor = dstCursor;
- switch(srcVal->kind)
+ switch (srcVal->kind)
{
case ShaderInputType::UniformData:
- return assignData(dstCursor, (ShaderInputLayout::DataVal*) srcVal.Ptr());
+ return assignData(dstCursor, (ShaderInputLayout::DataVal*)srcVal.Ptr());
case ShaderInputType::Buffer:
- return assignBuffer(dstCursor, (ShaderInputLayout::BufferVal*) srcVal.Ptr());
+ return assignBuffer(dstCursor, (ShaderInputLayout::BufferVal*)srcVal.Ptr());
case ShaderInputType::CombinedTextureSampler:
- return assignCombinedTextureSampler(dstCursor, (ShaderInputLayout::CombinedTextureSamplerVal*) srcVal.Ptr());
+ return assignCombinedTextureSampler(
+ dstCursor,
+ (ShaderInputLayout::CombinedTextureSamplerVal*)srcVal.Ptr());
case ShaderInputType::Texture:
- return assignTexture(dstCursor, (ShaderInputLayout::TextureVal*) srcVal.Ptr());
+ return assignTexture(dstCursor, (ShaderInputLayout::TextureVal*)srcVal.Ptr());
case ShaderInputType::Sampler:
- return assignSampler(dstCursor, (ShaderInputLayout::SamplerVal*) srcVal.Ptr());
+ return assignSampler(dstCursor, (ShaderInputLayout::SamplerVal*)srcVal.Ptr());
case ShaderInputType::Object:
- return assignObject(dstCursor, (ShaderInputLayout::ObjectVal*) srcVal.Ptr());
+ return assignObject(dstCursor, (ShaderInputLayout::ObjectVal*)srcVal.Ptr());
case ShaderInputType::Specialize:
return assignValWithSpecializationArg(
- dstCursor, (ShaderInputLayout::SpecializeVal*)srcVal.Ptr());
+ dstCursor,
+ (ShaderInputLayout::SpecializeVal*)srcVal.Ptr());
case ShaderInputType::Aggregate:
- return assignAggregate(dstCursor, (ShaderInputLayout::AggVal*) srcVal.Ptr());
+ return assignAggregate(dstCursor, (ShaderInputLayout::AggVal*)srcVal.Ptr());
case ShaderInputType::Array:
- return assignArray(dstCursor, (ShaderInputLayout::ArrayVal*) srcVal.Ptr());
+ return assignArray(dstCursor, (ShaderInputLayout::ArrayVal*)srcVal.Ptr());
case ShaderInputType::AccelerationStructure:
return assignAccelerationStructure(
- dstCursor, (ShaderInputLayout::AccelerationStructureVal*)srcVal.Ptr());
- default:
- assert(!"Unhandled type");
- return SLANG_FAIL;
+ dstCursor,
+ (ShaderInputLayout::AccelerationStructureVal*)srcVal.Ptr());
+ default: assert(!"Unhandled type"); return SLANG_FAIL;
}
}
};
SlangResult _assignVarsFromLayout(
- IDevice* device,
- slang::ISession* slangSession,
- IShaderObject* shaderObject,
- ShaderInputLayout const& layout,
- ShaderOutputPlan& ioOutputPlan,
- slang::ProgramLayout* slangReflection,
- IAccelerationStructure* accelerationStructure)
+ IDevice* device,
+ slang::ISession* slangSession,
+ IShaderObject* shaderObject,
+ ShaderInputLayout const& layout,
+ ShaderOutputPlan& ioOutputPlan,
+ slang::ProgramLayout* slangReflection,
+ IAccelerationStructure* accelerationStructure)
{
- AssignValsFromLayoutContext context(
- device, slangSession, ioOutputPlan, slangReflection, accelerationStructure);
+ AssignValsFromLayoutContext
+ context(device, slangSession, ioOutputPlan, slangReflection, accelerationStructure);
ShaderCursor rootCursor = ShaderCursor(shaderObject);
return context.assign(rootCursor, layout.rootVal);
}
@@ -517,8 +541,7 @@ Result RenderTestApp::applyBinding(PipelineType pipelineType, IPassEncoder* enco
setProjectionMatrix(rootObject);
}
break;
- default:
- throw "unknown pipeline type";
+ default: throw "unknown pipeline type";
}
return SLANG_OK;
}
@@ -533,35 +556,40 @@ SlangResult RenderTestApp::initialize(
// We begin by compiling the shader file and entry points that specified via the options.
//
- SLANG_RETURN_ON_FAIL(ShaderCompilerUtil::compileWithLayout(device->getSlangSession()->getGlobalSession(), options, input, m_compilationOutput));
+ SLANG_RETURN_ON_FAIL(ShaderCompilerUtil::compileWithLayout(
+ device->getSlangSession()->getGlobalSession(),
+ options,
+ input,
+ m_compilationOutput));
m_shaderInputLayout = m_compilationOutput.layout;
// Once the shaders have been compiled we load them via the underlying API.
//
ComPtr<ISlangBlob> outDiagnostics;
- auto result = device->createShaderProgram(m_compilationOutput.output.desc, m_shaderProgram.writeRef(), outDiagnostics.writeRef());
+ auto result = device->createShaderProgram(
+ m_compilationOutput.output.desc,
+ m_shaderProgram.writeRef(),
+ outDiagnostics.writeRef());
// If there was a failure creating a program, we can't continue
// Special case SLANG_E_NOT_AVAILABLE error code to make it a failure,
- // as it is also used to indicate an attempt setup something failed gracefully (because it couldn't be supported)
- // but that's not this.
+ // as it is also used to indicate an attempt setup something failed gracefully (because it
+ // couldn't be supported) but that's not this.
if (SLANG_FAILED(result))
{
result = (result == SLANG_E_NOT_AVAILABLE) ? SLANG_FAIL : result;
return result;
}
- m_device = device;
+ m_device = device;
_initializeRenderPass();
_initializeAccelerationStructure();
{
- switch(m_options.shaderType)
+ switch (m_options.shaderType)
{
- default:
- assert(!"unexpected test shader type");
- return SLANG_FAIL;
+ default: assert(!"unexpected test shader type"); return SLANG_FAIL;
case Options::ShaderProgramType::Compute:
{
@@ -585,14 +613,17 @@ SlangResult RenderTestApp::initialize(
// fixed/known set of attributes.
//
const InputElementDesc inputElements[] = {
- { "A", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position) },
- { "A", 1, Format::R32G32B32_FLOAT, offsetof(Vertex, color) },
- { "A", 2, Format::R32G32_FLOAT, offsetof(Vertex, uv) },
+ {"A", 0, Format::R32G32B32_FLOAT, offsetof(Vertex, position)},
+ {"A", 1, Format::R32G32B32_FLOAT, offsetof(Vertex, color)},
+ {"A", 2, Format::R32G32_FLOAT, offsetof(Vertex, uv)},
};
ComPtr<IInputLayout> inputLayout;
SLANG_RETURN_ON_FAIL(device->createInputLayout(
- sizeof(Vertex), inputElements, SLANG_COUNT_OF(inputElements), inputLayout.writeRef()));
+ sizeof(Vertex),
+ inputElements,
+ SLANG_COUNT_OF(inputElements),
+ inputLayout.writeRef()));
BufferDesc vertexBufferDesc;
vertexBufferDesc.size = kVertexCount * sizeof(Vertex);
@@ -600,10 +631,8 @@ SlangResult RenderTestApp::initialize(
vertexBufferDesc.usage = BufferUsage::VertexBuffer;
vertexBufferDesc.defaultState = ResourceState::VertexBuffer;
- SLANG_RETURN_ON_FAIL(device->createBuffer(
- vertexBufferDesc,
- kVertexData,
- m_vertexBuffer.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ device->createBuffer(vertexBufferDesc, kVertexData, m_vertexBuffer.writeRef()));
ColorTargetState colorTarget;
colorTarget.format = Format::R8G8B8A8_UNORM;
@@ -640,7 +669,11 @@ Result RenderTestApp::_initializeShaders(
Options::ShaderProgramType shaderType,
const ShaderCompilerUtil::Input& input)
{
- SLANG_RETURN_ON_FAIL(ShaderCompilerUtil::compileWithLayout(device->getSlangSession()->getGlobalSession(), m_options, input, m_compilationOutput));
+ SLANG_RETURN_ON_FAIL(ShaderCompilerUtil::compileWithLayout(
+ device->getSlangSession()->getGlobalSession(),
+ m_options,
+ input,
+ m_compilationOutput));
m_shaderInputLayout = m_compilationOutput.layout;
m_shaderProgram = device->createShaderProgram(m_compilationOutput.output.desc);
return m_shaderProgram ? SLANG_OK : SLANG_FAIL;
@@ -655,7 +688,7 @@ void RenderTestApp::_initializeRenderPass()
m_queue = m_device->getQueue(QueueType::Graphics);
SLANG_ASSERT(m_queue);
-
+
rhi::TextureDesc depthBufferDesc;
depthBufferDesc.type = TextureType::Texture2D;
depthBufferDesc.size.width = gWindowWidth;
@@ -693,17 +726,15 @@ void RenderTestApp::_initializeAccelerationStructure()
vertexBufferDesc.size = kVertexCount * sizeof(Vertex);
vertexBufferDesc.usage = BufferUsage::AccelerationStructureBuildInput;
vertexBufferDesc.defaultState = ResourceState::AccelerationStructureBuildInput;
- ComPtr<IBuffer> vertexBuffer =
- m_device->createBuffer(vertexBufferDesc, &kVertexData[0]);
+ ComPtr<IBuffer> vertexBuffer = m_device->createBuffer(vertexBufferDesc, &kVertexData[0]);
BufferDesc transformBufferDesc = {};
transformBufferDesc.size = sizeof(float) * 12;
transformBufferDesc.usage = BufferUsage::AccelerationStructureBuildInput;
transformBufferDesc.defaultState = ResourceState::AccelerationStructureBuildInput;
- float transformData[12] = {
- 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
- ComPtr<IBuffer> transformBuffer =
- m_device->createBuffer(transformBufferDesc, &transformData);
+ float transformData[12] =
+ {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
+ ComPtr<IBuffer> transformBuffer = m_device->createBuffer(transformBufferDesc, &transformData);
// Build bottom level acceleration structure.
{
@@ -750,7 +781,13 @@ void RenderTestApp::_initializeAccelerationStructure()
AccelerationStructureQueryDesc compactedSizeQueryDesc = {};
compactedSizeQueryDesc.queryPool = compactedSizeQuery;
compactedSizeQueryDesc.queryType = QueryType::AccelerationStructureCompactedSize;
- passEncoder->buildAccelerationStructure(buildDesc, draftAS, nullptr, scratchBuffer, 1, &compactedSizeQueryDesc);
+ passEncoder->buildAccelerationStructure(
+ buildDesc,
+ draftAS,
+ nullptr,
+ scratchBuffer,
+ 1,
+ &compactedSizeQueryDesc);
passEncoder->end();
commandBuffer->close();
m_queue->submit(commandBuffer);
@@ -760,12 +797,16 @@ void RenderTestApp::_initializeAccelerationStructure()
compactedSizeQuery->getResult(0, 1, &compactedSize);
AccelerationStructureDesc finalDesc;
finalDesc.size = compactedSize;
- m_device->createAccelerationStructure(finalDesc, m_bottomLevelAccelerationStructure.writeRef());
+ m_device->createAccelerationStructure(
+ finalDesc,
+ m_bottomLevelAccelerationStructure.writeRef());
commandBuffer = m_transientHeap->createCommandBuffer();
passEncoder = commandBuffer->beginRayTracingPass();
passEncoder->copyAccelerationStructure(
- m_bottomLevelAccelerationStructure, draftAS, AccelerationStructureCopyMode::Compact);
+ m_bottomLevelAccelerationStructure,
+ draftAS,
+ AccelerationStructureCopyMode::Compact);
passEncoder->end();
commandBuffer->close();
m_queue->submit(commandBuffer);
@@ -776,17 +817,20 @@ void RenderTestApp::_initializeAccelerationStructure()
{
AccelerationStructureInstanceDescType nativeInstanceDescType =
getAccelerationStructureInstanceDescType(m_device);
- Size nativeInstanceDescSize = getAccelerationStructureInstanceDescSize(nativeInstanceDescType);
+ Size nativeInstanceDescSize =
+ getAccelerationStructureInstanceDescSize(nativeInstanceDescType);
List<AccelerationStructureInstanceDescGeneric> genericInstanceDescs;
genericInstanceDescs.setCount(1);
- genericInstanceDescs[0].accelerationStructure = m_bottomLevelAccelerationStructure->getHandle();
- genericInstanceDescs[0].flags = AccelerationStructureInstanceFlags::TriangleFacingCullDisable;
+ genericInstanceDescs[0].accelerationStructure =
+ m_bottomLevelAccelerationStructure->getHandle();
+ genericInstanceDescs[0].flags =
+ AccelerationStructureInstanceFlags::TriangleFacingCullDisable;
genericInstanceDescs[0].instanceContributionToHitGroupIndex = 0;
genericInstanceDescs[0].instanceID = 0;
genericInstanceDescs[0].instanceMask = 0xFF;
- float transformMatrix[] = {
- 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
+ float transformMatrix[] =
+ {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
memcpy(&genericInstanceDescs[0].transform[0][0], transformMatrix, sizeof(float) * 12);
List<unsigned char> nativeInstanceDescs;
@@ -797,8 +841,7 @@ void RenderTestApp::_initializeAccelerationStructure()
nativeInstanceDescs.getBuffer(),
nativeInstanceDescSize,
genericInstanceDescs.getBuffer(),
- sizeof(AccelerationStructureInstanceDescGeneric)
- );
+ sizeof(AccelerationStructureInstanceDescGeneric));
BufferDesc instanceBufferDesc = {};
instanceBufferDesc.size = nativeInstanceDescs.getCount();
@@ -828,11 +871,18 @@ void RenderTestApp::_initializeAccelerationStructure()
AccelerationStructureDesc createDesc = {};
createDesc.size = accelerationStructureSizes.accelerationStructureSize;
m_device->createAccelerationStructure(
- createDesc, m_topLevelAccelerationStructure.writeRef());
+ createDesc,
+ m_topLevelAccelerationStructure.writeRef());
auto commandBuffer = m_transientHeap->createCommandBuffer();
auto passEncoder = commandBuffer->beginRayTracingPass();
- passEncoder->buildAccelerationStructure(buildDesc, m_topLevelAccelerationStructure, nullptr, scratchBuffer, 0, nullptr);
+ passEncoder->buildAccelerationStructure(
+ buildDesc,
+ m_topLevelAccelerationStructure,
+ nullptr,
+ scratchBuffer,
+ 0,
+ nullptr);
passEncoder->end();
commandBuffer->close();
m_queue->submit(commandBuffer);
@@ -853,11 +903,10 @@ void RenderTestApp::renderFrameMesh(IRenderPassEncoder* encoder)
{
auto pipelineType = PipelineType::Graphics;
applyBinding(pipelineType, encoder);
- encoder->drawMeshTasks(
+ encoder->drawMeshTasks(
m_options.computeDispatchSize[0],
m_options.computeDispatchSize[1],
- m_options.computeDispatchSize[2]
- );
+ m_options.computeDispatchSize[2]);
}
void RenderTestApp::renderFrame(IRenderPassEncoder* encoder)
@@ -865,16 +914,16 @@ void RenderTestApp::renderFrame(IRenderPassEncoder* encoder)
auto pipelineType = PipelineType::Graphics;
applyBinding(pipelineType, encoder);
- encoder->setVertexBuffer(0, m_vertexBuffer);
+ encoder->setVertexBuffer(0, m_vertexBuffer);
- encoder->draw(3);
+ encoder->draw(3);
}
void RenderTestApp::runCompute(IComputePassEncoder* encoder)
{
auto pipelineType = PipelineType::Compute;
applyBinding(pipelineType, encoder);
- encoder->dispatchCompute(
+ encoder->dispatchCompute(
m_options.computeDispatchSize[0],
m_options.computeDispatchSize[1],
m_options.computeDispatchSize[2]);
@@ -890,14 +939,14 @@ Result RenderTestApp::writeBindingOutput(const String& fileName)
// Wait until everything is complete
m_queue->waitOnHost();
- FILE * f = fopen(fileName.getBuffer(), "wb");
+ FILE* f = fopen(fileName.getBuffer(), "wb");
if (!f)
{
return SLANG_FAIL;
}
FileWriter writer(f, WriterFlags(0));
- for(auto outputItem : m_outputPlan.items)
+ for (auto outputItem : m_outputPlan.items)
{
auto resource = outputItem.resource;
IBuffer* buffer = nullptr;
@@ -916,7 +965,8 @@ Result RenderTestApp::writeBindingOutput(const String& fileName)
return SLANG_FAIL;
}
const SlangResult res = ShaderInputLayout::writeBinding(
- m_options.outputUsingType ? outputItem.typeLayout : nullptr, // TODO: always output using type
+ m_options.outputUsingType ? outputItem.typeLayout
+ : nullptr, // TODO: always output using type
blob->getBufferPointer(),
bufferSize,
&writer);
@@ -935,7 +985,8 @@ Result RenderTestApp::writeScreen(const String& filename)
{
size_t rowPitch, pixelSize;
ComPtr<ISlangBlob> blob;
- SLANG_RETURN_ON_FAIL(m_device->readTexture(m_colorBuffer, blob.writeRef(), &rowPitch, &pixelSize));
+ SLANG_RETURN_ON_FAIL(
+ m_device->readTexture(m_colorBuffer, blob.writeRef(), &rowPitch, &pixelSize));
auto bufferSize = blob->getBufferSize();
uint32_t width = static_cast<uint32_t>(rowPitch / pixelSize);
uint32_t height = static_cast<uint32_t>(bufferSize / rowPitch);
@@ -972,8 +1023,8 @@ Result RenderTestApp::update()
viewport.extentX = (float)gWindowWidth;
viewport.extentY = (float)gWindowHeight;
passEncoder->setViewportAndScissor(viewport);
- if(m_options.shaderType == Options::ShaderProgramType::GraphicsMeshCompute
- || m_options.shaderType == Options::ShaderProgramType::GraphicsTaskMeshCompute)
+ if (m_options.shaderType == Options::ShaderProgramType::GraphicsMeshCompute ||
+ m_options.shaderType == Options::ShaderProgramType::GraphicsTaskMeshCompute)
renderFrameMesh(passEncoder);
else
renderFrame(passEncoder);
@@ -1017,8 +1068,9 @@ Result RenderTestApp::update()
}
#endif
- // Note we don't do the same with screen rendering -> as that will do a lot of work, which may swamp any computation
- // so can only really profile compute shaders at the moment
+ // Note we don't do the same with screen rendering -> as that will do a lot of work,
+ // which may swamp any computation so can only really profile compute shaders at the
+ // moment
const uint64_t endTicks = Process::getClockTick();
@@ -1027,13 +1079,13 @@ Result RenderTestApp::update()
if (m_options.outputPath.getLength())
{
- if (m_options.shaderType == Options::ShaderProgramType::Compute
- || m_options.shaderType == Options::ShaderProgramType::GraphicsCompute
- || m_options.shaderType == Options::ShaderProgramType::GraphicsMeshCompute
- || m_options.shaderType == Options::ShaderProgramType::GraphicsTaskMeshCompute)
+ if (m_options.shaderType == Options::ShaderProgramType::Compute ||
+ m_options.shaderType == Options::ShaderProgramType::GraphicsCompute ||
+ m_options.shaderType == Options::ShaderProgramType::GraphicsMeshCompute ||
+ m_options.shaderType == Options::ShaderProgramType::GraphicsTaskMeshCompute)
{
auto request = m_compilationOutput.output.getRequestForReflection();
- auto slangReflection = (slang::ShaderReflection*) spGetReflection(request);
+ auto slangReflection = (slang::ShaderReflection*)spGetReflection(request);
SLANG_RETURN_ON_FAIL(writeBindingOutput(m_options.outputPath));
}
@@ -1053,7 +1105,10 @@ Result RenderTestApp::update()
}
-static SlangResult _setSessionPrelude(const Options& options, const char* exePath, SlangSession* session)
+static SlangResult _setSessionPrelude(
+ const Options& options,
+ const char* exePath,
+ SlangSession* session)
{
// Let's see if we need to set up special prelude for HLSL
if (options.nvapiExtnSlot.getLength())
@@ -1066,15 +1121,19 @@ static SlangResult _setSessionPrelude(const Options& options, const char* exePat
String rootPath;
SLANG_RETURN_ON_FAIL(TestToolUtil::getRootPath(exePath, rootPath));
String includePath;
- SLANG_RETURN_ON_FAIL(TestToolUtil::getIncludePath(rootPath, "external/nvapi/nvHLSLExtns.h", includePath))
+ SLANG_RETURN_ON_FAIL(
+ TestToolUtil::getIncludePath(rootPath, "external/nvapi/nvHLSLExtns.h", includePath))
StringBuilder buf;
- // We have to choose a slot that NVAPI will use.
+ // We have to choose a slot that NVAPI will use.
buf << "#define NV_SHADER_EXTN_SLOT " << options.nvapiExtnSlot << "\n";
// Include the NVAPI header
buf << "#include ";
- StringEscapeUtil::appendQuoted(StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp), includePath.getUnownedSlice(), buf);
+ StringEscapeUtil::appendQuoted(
+ StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp),
+ includePath.getUnownedSlice(),
+ buf);
buf << "\n\n";
session->setLanguagePrelude(SLANG_SOURCE_LANGUAGE_HLSL, buf.getBuffer());
@@ -1102,7 +1161,11 @@ static void initializeRenderDoc()
assert(ret == 1);
}
}
-static void renderDocBeginFrame() { if (rdoc_api) rdoc_api->StartFrameCapture(nullptr, nullptr); }
+static void renderDocBeginFrame()
+{
+ if (rdoc_api)
+ rdoc_api->StartFrameCapture(nullptr, nullptr);
+}
static void renderDocEndFrame()
{
if (rdoc_api)
@@ -1110,9 +1173,9 @@ static void renderDocEndFrame()
_fgetchar();
}
#else
-static void initializeRenderDoc(){}
-static void renderDocBeginFrame(){}
-static void renderDocEndFrame(){}
+static void initializeRenderDoc() {}
+static void renderDocBeginFrame() {}
+static void renderDocEndFrame() {}
#endif
class StdWritersDebugCallback : public rhi::IDebugCallback
@@ -1132,7 +1195,11 @@ public:
}
};
-static SlangResult _innerMain(Slang::StdWriters* stdWriters, SlangSession* session, int argcIn, const char*const* argvIn)
+static SlangResult _innerMain(
+ Slang::StdWriters* stdWriters,
+ SlangSession* session,
+ int argcIn,
+ const char* const* argvIn)
{
using namespace renderer_test;
using namespace Slang;
@@ -1143,102 +1210,100 @@ static SlangResult _innerMain(Slang::StdWriters* stdWriters, SlangSession* sessi
Options options;
- // Parse command-line options
- SLANG_RETURN_ON_FAIL(Options::parse(argcIn, argvIn, StdWriters::getError(), options));
+ // Parse command-line options
+ SLANG_RETURN_ON_FAIL(Options::parse(argcIn, argvIn, StdWriters::getError(), options));
if (options.deviceType == DeviceType::Default)
{
return SLANG_OK;
}
ShaderCompilerUtil::Input input;
-
+
input.profile = "";
input.target = SLANG_TARGET_NONE;
- SlangSourceLanguage nativeLanguage = SLANG_SOURCE_LANGUAGE_UNKNOWN;
- SlangPassThrough slangPassThrough = SLANG_PASS_THROUGH_NONE;
+ SlangSourceLanguage nativeLanguage = SLANG_SOURCE_LANGUAGE_UNKNOWN;
+ SlangPassThrough slangPassThrough = SLANG_PASS_THROUGH_NONE;
char const* profileName = "";
- switch (options.deviceType)
- {
- case DeviceType::D3D11:
- input.target = SLANG_DXBC;
- input.profile = "sm_5_0";
- nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
- slangPassThrough = SLANG_PASS_THROUGH_FXC;
-
- break;
-
- case DeviceType::D3D12:
- input.target = SLANG_DXBC;
- input.profile = "sm_5_0";
- nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
- slangPassThrough = SLANG_PASS_THROUGH_FXC;
-
- if( options.useDXIL )
- {
- input.target = SLANG_DXIL;
- input.profile = "sm_6_5";
- slangPassThrough = SLANG_PASS_THROUGH_DXC;
- }
- break;
-
- case DeviceType::Vulkan:
- input.target = SLANG_SPIRV;
- input.profile = "";
- nativeLanguage = SLANG_SOURCE_LANGUAGE_GLSL;
- slangPassThrough = SLANG_PASS_THROUGH_GLSLANG;
- break;
- case DeviceType::Metal:
- input.target = SLANG_METAL_LIB;
- input.profile = "";
- nativeLanguage = SLANG_SOURCE_LANGUAGE_METAL;
- slangPassThrough = SLANG_PASS_THROUGH_METAL;
- break;
- case DeviceType::CPU:
- input.target = SLANG_SHADER_HOST_CALLABLE;
- input.profile = "";
- nativeLanguage = SLANG_SOURCE_LANGUAGE_CPP;
- slangPassThrough = SLANG_PASS_THROUGH_GENERIC_C_CPP;
- break;
- case DeviceType::CUDA:
- input.target = SLANG_PTX;
- input.profile = "";
- nativeLanguage = SLANG_SOURCE_LANGUAGE_CUDA;
- slangPassThrough = SLANG_PASS_THROUGH_NVRTC;
- break;
- case DeviceType::WGPU:
- input.target = SLANG_WGSL;
- input.profile = "";
- nativeLanguage = SLANG_SOURCE_LANGUAGE_WGSL;
- slangPassThrough = SLANG_PASS_THROUGH_NONE;
- break;
+ switch (options.deviceType)
+ {
+ case DeviceType::D3D11:
+ input.target = SLANG_DXBC;
+ input.profile = "sm_5_0";
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
+ slangPassThrough = SLANG_PASS_THROUGH_FXC;
+
+ break;
+
+ case DeviceType::D3D12:
+ input.target = SLANG_DXBC;
+ input.profile = "sm_5_0";
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
+ slangPassThrough = SLANG_PASS_THROUGH_FXC;
+
+ if (options.useDXIL)
+ {
+ input.target = SLANG_DXIL;
+ input.profile = "sm_6_5";
+ slangPassThrough = SLANG_PASS_THROUGH_DXC;
+ }
+ break;
+
+ case DeviceType::Vulkan:
+ input.target = SLANG_SPIRV;
+ input.profile = "";
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_GLSL;
+ slangPassThrough = SLANG_PASS_THROUGH_GLSLANG;
+ break;
+ case DeviceType::Metal:
+ input.target = SLANG_METAL_LIB;
+ input.profile = "";
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_METAL;
+ slangPassThrough = SLANG_PASS_THROUGH_METAL;
+ break;
+ case DeviceType::CPU:
+ input.target = SLANG_SHADER_HOST_CALLABLE;
+ input.profile = "";
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_CPP;
+ slangPassThrough = SLANG_PASS_THROUGH_GENERIC_C_CPP;
+ break;
+ case DeviceType::CUDA:
+ input.target = SLANG_PTX;
+ input.profile = "";
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_CUDA;
+ slangPassThrough = SLANG_PASS_THROUGH_NVRTC;
+ break;
+ case DeviceType::WGPU:
+ input.target = SLANG_WGSL;
+ input.profile = "";
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_WGSL;
+ slangPassThrough = SLANG_PASS_THROUGH_NONE;
+ break;
- default:
- fprintf(stderr, "error: unexpected\n");
- return SLANG_FAIL;
- }
+ default: fprintf(stderr, "error: unexpected\n"); return SLANG_FAIL;
+ }
switch (options.inputLanguageID)
{
- case Options::InputLanguageID::Slang:
- input.sourceLanguage = SLANG_SOURCE_LANGUAGE_SLANG;
- input.passThrough = SLANG_PASS_THROUGH_NONE;
- break;
+ case Options::InputLanguageID::Slang:
+ input.sourceLanguage = SLANG_SOURCE_LANGUAGE_SLANG;
+ input.passThrough = SLANG_PASS_THROUGH_NONE;
+ break;
- case Options::InputLanguageID::Native:
- input.sourceLanguage = nativeLanguage;
- input.passThrough = slangPassThrough;
- break;
+ case Options::InputLanguageID::Native:
+ input.sourceLanguage = nativeLanguage;
+ input.passThrough = slangPassThrough;
+ break;
- default:
- break;
+ default: break;
}
if (options.sourceLanguage != SLANG_SOURCE_LANGUAGE_UNKNOWN)
{
input.sourceLanguage = options.sourceLanguage;
- if (input.sourceLanguage == SLANG_SOURCE_LANGUAGE_C || input.sourceLanguage == SLANG_SOURCE_LANGUAGE_CPP)
+ if (input.sourceLanguage == SLANG_SOURCE_LANGUAGE_C ||
+ input.sourceLanguage == SLANG_SOURCE_LANGUAGE_CPP)
{
input.passThrough = SLANG_PASS_THROUGH_GENERIC_C_CPP;
}
@@ -1251,28 +1316,28 @@ static SlangResult _innerMain(Slang::StdWriters* stdWriters, SlangSession* sessi
input.profile = options.profileName.getLength() ? options.profileName : input.profile;
StringBuilder rendererName;
- auto info =
- rendererName << "[" << getRHI()->getDeviceTypeName(options.deviceType) << "] ";
+ auto info = rendererName << "[" << getRHI()->getDeviceTypeName(options.deviceType) << "] ";
if (options.onlyStartup)
{
switch (options.deviceType)
{
- case DeviceType::CUDA:
+ case DeviceType::CUDA:
{
#if RENDER_TEST_CUDA
- if(SLANG_FAILED(spSessionCheckPassThroughSupport(session, SLANG_PASS_THROUGH_NVRTC)))
+ if (SLANG_FAILED(
+ spSessionCheckPassThroughSupport(session, SLANG_PASS_THROUGH_NVRTC)))
return SLANG_FAIL;
#else
return SLANG_FAIL;
#endif
}
- case DeviceType::CPU:
+ case DeviceType::CPU:
{
// As long as we have CPU, then this should work
return spSessionCheckPassThroughSupport(session, SLANG_PASS_THROUGH_GENERIC_C_CPP);
}
- default: break;
+ default: break;
}
}
@@ -1284,14 +1349,15 @@ static SlangResult _innerMain(Slang::StdWriters* stdWriters, SlangSession* sessi
//
Slang::Int value;
UnownedStringSlice slice = options.nvapiExtnSlot.getUnownedSlice();
- UnownedStringSlice indexText(slice.begin() + 1 , slice.end());
+ UnownedStringSlice indexText(slice.begin() + 1, slice.end());
if (SLANG_SUCCEEDED(StringUtil::parseInt(indexText, value)))
{
nvapiExtnSlot = Index(value);
}
}
- // If can't set up a necessary prelude make not available (which will lead to the test being ignored)
+ // If can't set up a necessary prelude make not available (which will lead to the test being
+ // ignored)
if (SLANG_FAILED(_setSessionPrelude(options, argvIn[0], session)))
{
return SLANG_E_NOT_AVAILABLE;
@@ -1333,7 +1399,7 @@ static SlangResult _innerMain(Slang::StdWriters* stdWriters, SlangSession* sessi
}
}
}
-
+
desc.nvapiExtnSlot = int(nvapiExtnSlot);
desc.slang.slangGlobalSession = session;
desc.slang.targetProfile = options.profileName.getBuffer();
@@ -1341,13 +1407,16 @@ static SlangResult _innerMain(Slang::StdWriters* stdWriters, SlangSession* sessi
SlangResult res = getRHI()->createDevice(desc, device.writeRef());
if (SLANG_FAILED(res))
{
- // We need to be careful here about SLANG_E_NOT_AVAILABLE. This return value means that the renderer couldn't
- // be created because it required *features* that were *not available*. It does not mean the renderer in general couldn't
- // be constructed.
+ // We need to be careful here about SLANG_E_NOT_AVAILABLE. This return value means
+ // that the renderer couldn't be created because it required *features* that were
+ // *not available*. It does not mean the renderer in general couldn't be
+ // constructed.
//
- // Returning SLANG_E_NOT_AVAILABLE will lead to the test infrastructure ignoring this test.
+ // Returning SLANG_E_NOT_AVAILABLE will lead to the test infrastructure ignoring
+ // this test.
//
- // We also don't want to output the 'Unable to create renderer' error, as this isn't an error.
+ // We also don't want to output the 'Unable to create renderer' error, as this isn't
+ // an error.
if (res == SLANG_E_NOT_AVAILABLE)
{
return res;
@@ -1372,25 +1441,29 @@ static SlangResult _innerMain(Slang::StdWriters* stdWriters, SlangSession* sessi
}
}
}
-
+
// If the only test is we can startup, then we are done
if (options.onlyStartup)
{
return SLANG_OK;
}
- {
+ {
RenderTestApp app;
renderDocBeginFrame();
SLANG_RETURN_ON_FAIL(app.initialize(session, device, options, input));
app.update();
renderDocEndFrame();
app.finalize();
- }
+ }
return SLANG_OK;
}
-SLANG_TEST_TOOL_API SlangResult innerMain(Slang::StdWriters* stdWriters, SlangSession* sharedSession, int inArgc, const char*const* inArgv)
+SLANG_TEST_TOOL_API SlangResult innerMain(
+ Slang::StdWriters* stdWriters,
+ SlangSession* sharedSession,
+ int inArgc,
+ const char* const* inArgv)
{
using namespace Slang;
@@ -1399,10 +1472,12 @@ SLANG_TEST_TOOL_API SlangResult innerMain(Slang::StdWriters* stdWriters, SlangSe
// The sharedSession always has a pre-loaded core module.
// This differed test checks if the command line has an option to setup the core module.
- // If so we *don't* use the sharedSession, and create a new session without the core module just for this compilation.
+ // If so we *don't* use the sharedSession, and create a new session without the core module just
+ // for this compilation.
if (TestToolUtil::hasDeferredCoreModule(Index(inArgc - 1), inArgv + 1))
{
- SLANG_RETURN_ON_FAIL(slang_createGlobalSessionWithoutCoreModule(SLANG_API_VERSION, session.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ slang_createGlobalSessionWithoutCoreModule(SLANG_API_VERSION, session.writeRef()));
}
SlangResult res = SLANG_FAIL;
@@ -1424,19 +1499,18 @@ SLANG_TEST_TOOL_API SlangResult innerMain(Slang::StdWriters* stdWriters, SlangSe
return res;
}
-int main(int argc, char** argv)
+int main(int argc, char** argv)
{
using namespace Slang;
SlangSession* session = spCreateSession(nullptr);
TestToolUtil::setSessionDefaultPreludeFromExePath(argv[0], session);
-
+
auto stdWriters = StdWriters::initDefaultSingleton();
-
+
SlangResult res = innerMain(stdWriters, session, argc, argv);
spDestroySession(session);
slang::shutdown();
- return (int)TestToolUtil::getReturnCode(res);
+ return (int)TestToolUtil::getReturnCode(res);
}
-
diff --git a/tools/render-test/shader-input-layout.cpp b/tools/render-test/shader-input-layout.cpp
index 013e86c37..e2cf25809 100644
--- a/tools/render-test/shader-input-layout.cpp
+++ b/tools/render-test/shader-input-layout.cpp
@@ -2,6 +2,7 @@
#define _CRT_SECURE_NO_WARNINGS 1
#include "shader-input-layout.h"
+
#include "core/slang-token-reader.h"
#include "core/slang-type-text-util.h"
@@ -9,7 +10,7 @@
namespace renderer_test
{
- using namespace Slang;
+using namespace Slang;
// clang-format off
#define SLANG_SCALAR_TYPES(x) \
@@ -19,1177 +20,1229 @@ namespace renderer_test
// clang-format on
- Format _getFormatFromName(const UnownedStringSlice& slice)
+Format _getFormatFromName(const UnownedStringSlice& slice)
+{
+ for (int i = 0; i < int(Format::_Count); ++i)
{
- for (int i = 0; i < int(Format::_Count); ++i)
+ const FormatInfo& info = getFormatInfo(Format(i));
+ if (slice == info.name)
{
- const FormatInfo& info = getFormatInfo(Format(i));
- if (slice == info.name)
- {
- return Format(i);
- }
+ return Format(i);
}
- return Format::Unknown;
}
+ return Format::Unknown;
+}
- struct TypeInfo
- {
- UnownedStringSlice name;
- SlangScalarType type;
- };
+struct TypeInfo
+{
+ UnownedStringSlice name;
+ SlangScalarType type;
+};
-#define SLANG_SCALAR_TYPE_INFO(name, value) { UnownedStringSlice::fromLiteral(name), SLANG_SCALAR_TYPE_##value },
- static const TypeInfo g_scalarTypeInfos[] =
- {
- SLANG_SCALAR_TYPES(SLANG_SCALAR_TYPE_INFO)
- };
+#define SLANG_SCALAR_TYPE_INFO(name, value) \
+ {UnownedStringSlice::fromLiteral(name), SLANG_SCALAR_TYPE_##value},
+static const TypeInfo g_scalarTypeInfos[] = {SLANG_SCALAR_TYPES(SLANG_SCALAR_TYPE_INFO)};
#undef SLANG_SCALAR_TYPES
#undef SLANG_SCALAR_TYPE_INFO
- static SlangScalarType _getScalarType(const UnownedStringSlice& slice)
+static SlangScalarType _getScalarType(const UnownedStringSlice& slice)
+{
+ for (const auto& info : g_scalarTypeInfos)
{
- for (const auto& info : g_scalarTypeInfos)
+ if (info.name == slice)
{
- if (info.name == slice)
- {
- return info.type;
- }
+ return info.type;
}
- return SLANG_SCALAR_TYPE_NONE;
}
+ return SLANG_SCALAR_TYPE_NONE;
+}
- void ShaderInputLayout::AggVal::addField(ShaderInputLayout::Field const& field)
- {
- fields.add(field);
- }
+void ShaderInputLayout::AggVal::addField(ShaderInputLayout::Field const& field)
+{
+ fields.add(field);
+}
- void ShaderInputLayout::ArrayVal::addField(ShaderInputLayout::Field const& field)
+void ShaderInputLayout::ArrayVal::addField(ShaderInputLayout::Field const& field)
+{
+ vals.add(field.val);
+}
+
+class ShaderInputLayoutFormatException : public Exception
+{
+public:
+ ShaderInputLayoutFormatException(String message)
+ : Exception(message)
{
- vals.add(field.val);
}
+};
- class ShaderInputLayoutFormatException : public Exception
- {
- public:
- ShaderInputLayoutFormatException(String message)
- : Exception(message)
- {}
- };
+struct ShaderInputLayoutParser
+{
+ ShaderInputLayout* layout;
+ RandomGenerator* rand;
- struct ShaderInputLayoutParser
+ ShaderInputLayoutParser(ShaderInputLayout* layout, RandomGenerator* rand)
+ : layout(layout), rand(rand)
{
- ShaderInputLayout* layout;
- RandomGenerator* rand;
-
- ShaderInputLayoutParser(ShaderInputLayout* layout, RandomGenerator* rand)
- : layout(layout)
- , rand(rand)
- {}
+ }
- RefPtr<ShaderInputLayout::ParentVal> parentVal;
- List<RefPtr<ShaderInputLayout::ParentVal>> parentValStack;
+ RefPtr<ShaderInputLayout::ParentVal> parentVal;
+ List<RefPtr<ShaderInputLayout::ParentVal>> parentValStack;
- SlangResult parseOption(Misc::TokenReader& parser, String const& word, ShaderInputLayout::TextureVal* val)
+ SlangResult parseOption(
+ Misc::TokenReader& parser,
+ String const& word,
+ ShaderInputLayout::TextureVal* val)
+ {
+ if (word == "depth")
{
- if (word == "depth")
- {
- val->textureDesc.isDepthTexture = true;
- }
- else if (word == "arrayLength")
- {
- parser.Read("=");
- val->textureDesc.arrayLength = parser.ReadInt();
- }
- else if (word == "size")
- {
- parser.Read("=");
- auto size = parser.ReadInt();
- val->textureDesc.size = size;
- }
- else if (word == "content")
- {
- parser.Read("=");
- auto contentWord = parser.ReadWord();
- if (contentWord == "zero")
- val->textureDesc.content = InputTextureContent::Zero;
- else if (contentWord == "one")
- val->textureDesc.content = InputTextureContent::One;
- else if (contentWord == "chessboard")
- val->textureDesc.content = InputTextureContent::ChessBoard;
- else
- val->textureDesc.content = InputTextureContent::Gradient;
- }
- else if (word == "sampleCount")
- {
- parser.Read("=");
- auto contentWord = parser.ReadWord();
- if(contentWord == "one")
- val->textureDesc.sampleCount = InputTextureSampleCount::One;
- else if(contentWord == "two")
- val->textureDesc.sampleCount = InputTextureSampleCount::Two;
- else if(contentWord == "four")
- val->textureDesc.sampleCount = InputTextureSampleCount::Four;
- else if(contentWord == "eight")
- val->textureDesc.sampleCount = InputTextureSampleCount::Eight;
- else if(contentWord == "sixteen")
- val->textureDesc.sampleCount = InputTextureSampleCount::Sixteen;
- else if(contentWord == "thirtyTwo")
- val->textureDesc.sampleCount = InputTextureSampleCount::ThirtyTwo;
- else if(contentWord == "sixtyFour")
- val->textureDesc.sampleCount = InputTextureSampleCount::SixtyFour;
- }
- else if(word == "mipMaps")
- {
- parser.Read("=");
- val->textureDesc.mipMapCount = int(parser.ReadInt());
- }
- else if(word == "format")
- {
- val->textureDesc.format = parseFormatOption(parser);
-
- if (val->textureDesc.format == Format::Unknown)
- {
- return SLANG_FAIL;
- }
- }
- else
- {
- return SLANG_FAIL;
- }
- return SLANG_OK;
+ val->textureDesc.isDepthTexture = true;
}
-
- SlangResult parseOption(Misc::TokenReader& parser, String const& word, ShaderInputLayout::SamplerVal* val)
+ else if (word == "arrayLength")
{
- if (word == "depthCompare")
- {
- val->samplerDesc.isCompareSampler = true;
- }
+ parser.Read("=");
+ val->textureDesc.arrayLength = parser.ReadInt();
+ }
+ else if (word == "size")
+ {
+ parser.Read("=");
+ auto size = parser.ReadInt();
+ val->textureDesc.size = size;
+ }
+ else if (word == "content")
+ {
+ parser.Read("=");
+ auto contentWord = parser.ReadWord();
+ if (contentWord == "zero")
+ val->textureDesc.content = InputTextureContent::Zero;
+ else if (contentWord == "one")
+ val->textureDesc.content = InputTextureContent::One;
+ else if (contentWord == "chessboard")
+ val->textureDesc.content = InputTextureContent::ChessBoard;
else
+ val->textureDesc.content = InputTextureContent::Gradient;
+ }
+ else if (word == "sampleCount")
+ {
+ parser.Read("=");
+ auto contentWord = parser.ReadWord();
+ if (contentWord == "one")
+ val->textureDesc.sampleCount = InputTextureSampleCount::One;
+ else if (contentWord == "two")
+ val->textureDesc.sampleCount = InputTextureSampleCount::Two;
+ else if (contentWord == "four")
+ val->textureDesc.sampleCount = InputTextureSampleCount::Four;
+ else if (contentWord == "eight")
+ val->textureDesc.sampleCount = InputTextureSampleCount::Eight;
+ else if (contentWord == "sixteen")
+ val->textureDesc.sampleCount = InputTextureSampleCount::Sixteen;
+ else if (contentWord == "thirtyTwo")
+ val->textureDesc.sampleCount = InputTextureSampleCount::ThirtyTwo;
+ else if (contentWord == "sixtyFour")
+ val->textureDesc.sampleCount = InputTextureSampleCount::SixtyFour;
+ }
+ else if (word == "mipMaps")
+ {
+ parser.Read("=");
+ val->textureDesc.mipMapCount = int(parser.ReadInt());
+ }
+ else if (word == "format")
+ {
+ val->textureDesc.format = parseFormatOption(parser);
+
+ if (val->textureDesc.format == Format::Unknown)
{
return SLANG_FAIL;
}
- return SLANG_OK;
}
+ else
+ {
+ return SLANG_FAIL;
+ }
+ return SLANG_OK;
+ }
-
- SlangResult parseOption(Misc::TokenReader& parser, String const& word, ShaderInputLayout::CombinedTextureSamplerVal* val)
+ SlangResult parseOption(
+ Misc::TokenReader& parser,
+ String const& word,
+ ShaderInputLayout::SamplerVal* val)
+ {
+ if (word == "depthCompare")
+ {
+ val->samplerDesc.isCompareSampler = true;
+ }
+ else
{
- auto result = parseOption(parser, word, val->textureVal);
- if(SLANG_SUCCEEDED(result)) return result;
+ return SLANG_FAIL;
+ }
+ return SLANG_OK;
+ }
+
- result = parseOption(parser, word, val->samplerVal);
+ SlangResult parseOption(
+ Misc::TokenReader& parser,
+ String const& word,
+ ShaderInputLayout::CombinedTextureSamplerVal* val)
+ {
+ auto result = parseOption(parser, word, val->textureVal);
+ if (SLANG_SUCCEEDED(result))
return result;
- }
- SlangResult parseOption(Misc::TokenReader& parser, String const& word, ShaderInputLayout::DataValBase* val)
+ result = parseOption(parser, word, val->samplerVal);
+ return result;
+ }
+
+ SlangResult parseOption(
+ Misc::TokenReader& parser,
+ String const& word,
+ ShaderInputLayout::DataValBase* val)
+ {
+ if (word == "data")
{
- if (word == "data")
- {
- parser.Read("=");
+ parser.Read("=");
- parser.Read("[");
- uint32_t offset = 0;
- while (!parser.IsEnd() && !parser.LookAhead("]"))
+ parser.Read("[");
+ uint32_t offset = 0;
+ while (!parser.IsEnd() && !parser.LookAhead("]"))
+ {
+ bool negate = false;
+ if (parser.NextToken().Type == Misc::TokenType::OpSub)
{
- bool negate = false;
- if(parser.NextToken().Type == Misc::TokenType::OpSub)
- {
- parser.ReadToken();
- negate = true;
- }
+ parser.ReadToken();
+ negate = true;
+ }
- if (parser.NextToken().Type == Misc::TokenType::IntLiteral)
- {
- uint32_t value = parser.ReadUInt();
- if(negate) value = uint32_t(-int32_t(value));
- val->bufferData.add(value);
- }
- else
- {
- auto floatNum = parser.ReadFloat();
- if(negate) floatNum = -floatNum;
- val->bufferData.add(*(unsigned int*)&floatNum);
- }
- offset += 4;
+ if (parser.NextToken().Type == Misc::TokenType::IntLiteral)
+ {
+ uint32_t value = parser.ReadUInt();
+ if (negate)
+ value = uint32_t(-int32_t(value));
+ val->bufferData.add(value);
}
- parser.Read("]");
- }
- else
- {
- return SLANG_FAIL;
+ else
+ {
+ auto floatNum = parser.ReadFloat();
+ if (negate)
+ floatNum = -floatNum;
+ val->bufferData.add(*(unsigned int*)&floatNum);
+ }
+ offset += 4;
}
- return SLANG_OK;
+ parser.Read("]");
}
+ else
+ {
+ return SLANG_FAIL;
+ }
+ return SLANG_OK;
+ }
- SlangResult parseOption(Misc::TokenReader& parser, String const& word, ShaderInputLayout::BufferVal* val)
+ SlangResult parseOption(
+ Misc::TokenReader& parser,
+ String const& word,
+ ShaderInputLayout::BufferVal* val)
+ {
+ if (word == "stride")
{
- if (word == "stride")
- {
- parser.Read("=");
- val->bufferDesc.stride = parser.ReadInt();
- }
- else if (word == "count")
- {
- parser.Read("=");
- val->bufferDesc.elementCount = parser.ReadInt();
- }
- else if (word == "counter")
- {
- parser.Read("=");
- val->bufferDesc.counter = parser.ReadInt();
- }
- else if (word == "random")
- {
- parser.Read("(");
- // Read the type
- String type = parser.ReadWord();
- SlangScalarType scalarType = _getScalarType(type.getUnownedSlice());
- if (scalarType == SLANG_SCALAR_TYPE_NONE)
+ parser.Read("=");
+ val->bufferDesc.stride = parser.ReadInt();
+ }
+ else if (word == "count")
+ {
+ parser.Read("=");
+ val->bufferDesc.elementCount = parser.ReadInt();
+ }
+ else if (word == "counter")
+ {
+ parser.Read("=");
+ val->bufferDesc.counter = parser.ReadInt();
+ }
+ else if (word == "random")
+ {
+ parser.Read("(");
+ // Read the type
+ String type = parser.ReadWord();
+ SlangScalarType scalarType = _getScalarType(type.getUnownedSlice());
+ if (scalarType == SLANG_SCALAR_TYPE_NONE)
+ {
+ StringBuilder scalarTypeNames;
+ for (const auto& info : g_scalarTypeInfos)
{
- StringBuilder scalarTypeNames;
- for (const auto& info : g_scalarTypeInfos)
+ if (scalarTypeNames.getLength() != 0)
{
- if (scalarTypeNames.getLength() != 0)
- {
- scalarTypeNames << ", ";
- }
- scalarTypeNames << info.name;
+ scalarTypeNames << ", ";
}
-
- throw ShaderInputLayoutFormatException(StringBuilder() << "Expecting " << scalarTypeNames << " " << parser.NextToken().Position.Line);
+ scalarTypeNames << info.name;
}
- parser.Read(",");
- const int size = int(parser.ReadUInt());
+ throw ShaderInputLayoutFormatException(
+ StringBuilder()
+ << "Expecting " << scalarTypeNames << " " << parser.NextToken().Position.Line);
+ }
+
+ parser.Read(",");
+ const int size = int(parser.ReadUInt());
- switch (scalarType)
+ switch (scalarType)
+ {
+ case SLANG_SCALAR_TYPE_INT32:
{
- case SLANG_SCALAR_TYPE_INT32:
- {
- bool hasRange = false;
+ bool hasRange = false;
+
+ int32_t minValue = -0x7fffffff - 1;
+ int32_t maxValue = 0x7fffffff;
- int32_t minValue = -0x7fffffff - 1;
- int32_t maxValue = 0x7fffffff;
+ if (parser.LookAhead(","))
+ {
+ hasRange = true;
+ parser.ReadToken();
+ minValue = parser.ReadInt();
if (parser.LookAhead(","))
{
- hasRange = true;
parser.ReadToken();
- minValue = parser.ReadInt();
-
- if (parser.LookAhead(","))
- {
- parser.ReadToken();
- maxValue = parser.ReadInt();
- }
+ maxValue = parser.ReadInt();
}
- SLANG_ASSERT(minValue <= maxValue);
- maxValue = (maxValue >= minValue) ? maxValue : minValue;
+ }
+ SLANG_ASSERT(minValue <= maxValue);
+ maxValue = (maxValue >= minValue) ? maxValue : minValue;
- // Generate the data
- val->bufferData.setCount(size);
+ // Generate the data
+ val->bufferData.setCount(size);
- int32_t* dst = (int32_t*)val->bufferData.getBuffer();
- for (int i = 0; i < size; ++i)
- {
- dst[i] = hasRange ? rand->nextInt32InRange(minValue, maxValue) : rand->nextInt32();
- }
- break;
+ int32_t* dst = (int32_t*)val->bufferData.getBuffer();
+ for (int i = 0; i < size; ++i)
+ {
+ dst[i] = hasRange ? rand->nextInt32InRange(minValue, maxValue)
+ : rand->nextInt32();
}
- case SLANG_SCALAR_TYPE_UINT32:
+ break;
+ }
+ case SLANG_SCALAR_TYPE_UINT32:
+ {
+ bool hasRange = false;
+ uint32_t minValue = 0;
+ uint32_t maxValue = 0xffffffff;
+
+ if (parser.LookAhead(","))
{
- bool hasRange = false;
- uint32_t minValue = 0;
- uint32_t maxValue = 0xffffffff;
+ parser.ReadToken();
+ minValue = parser.ReadUInt();
+
+ hasRange = true;
if (parser.LookAhead(","))
{
parser.ReadToken();
- minValue = parser.ReadUInt();
-
- hasRange = true;
-
- if (parser.LookAhead(","))
- {
- parser.ReadToken();
- maxValue = parser.ReadUInt();
- }
+ maxValue = parser.ReadUInt();
}
+ }
- SLANG_ASSERT(minValue <= maxValue);
- maxValue = (maxValue >= minValue) ? maxValue : minValue;
+ SLANG_ASSERT(minValue <= maxValue);
+ maxValue = (maxValue >= minValue) ? maxValue : minValue;
- // Generate the data
- val->bufferData.setCount(size);
+ // Generate the data
+ val->bufferData.setCount(size);
- uint32_t* dst = (uint32_t*)val->bufferData.getBuffer();
- for (int i = 0; i < size; ++i)
- {
- dst[i] = hasRange ? rand->nextUInt32InRange(minValue, maxValue) : rand->nextUInt32();
- }
-
- break;
+ uint32_t* dst = (uint32_t*)val->bufferData.getBuffer();
+ for (int i = 0; i < size; ++i)
+ {
+ dst[i] = hasRange ? rand->nextUInt32InRange(minValue, maxValue)
+ : rand->nextUInt32();
}
- case SLANG_SCALAR_TYPE_FLOAT32:
+
+ break;
+ }
+ case SLANG_SCALAR_TYPE_FLOAT32:
+ {
+ float minValue = -1.0f;
+ float maxValue = 1.0f;
+
+ if (parser.LookAhead(","))
{
- float minValue = -1.0f;
- float maxValue = 1.0f;
-
+ parser.ReadToken();
+ minValue = parser.ReadFloat();
+
if (parser.LookAhead(","))
{
parser.ReadToken();
- minValue = parser.ReadFloat();
-
- if (parser.LookAhead(","))
- {
- parser.ReadToken();
- maxValue = parser.ReadFloat();
- }
+ maxValue = parser.ReadFloat();
}
+ }
- SLANG_ASSERT(minValue <= maxValue);
- maxValue = (maxValue >= minValue) ? maxValue : minValue;
+ SLANG_ASSERT(minValue <= maxValue);
+ maxValue = (maxValue >= minValue) ? maxValue : minValue;
- // Generate the data
- val->bufferData.setCount(size);
+ // Generate the data
+ val->bufferData.setCount(size);
- float* dst = (float*)val->bufferData.getBuffer();
- for (int i = 0; i < size; ++i)
- {
- dst[i] = (rand->nextUnitFloat32() * (maxValue - minValue)) + minValue;
- }
- break;
+ float* dst = (float*)val->bufferData.getBuffer();
+ for (int i = 0; i < size; ++i)
+ {
+ dst[i] = (rand->nextUnitFloat32() * (maxValue - minValue)) + minValue;
}
+ break;
}
+ }
- // Read the range
+ // Read the range
- parser.Read(")");
- }
- else if(word == "format")
- {
- val->bufferDesc.format = parseFormatOption(parser);
- }
- else
- {
- return parseOption(parser, word, static_cast<ShaderInputLayout::DataValBase*>(val));
- }
- return SLANG_OK;
+ parser.Read(")");
}
-
- SlangResult parseOption(Misc::TokenReader& parser, String const& word, ShaderInputLayout::ObjectVal* val)
+ else if (word == "format")
{
- if( word == "type" )
- {
- parser.Read("=");
- val->typeName = parser.ReadWord();
- }
- else
- {
- return SLANG_FAIL;
- }
- return SLANG_OK;
+ val->bufferDesc.format = parseFormatOption(parser);
+ }
+ else
+ {
+ return parseOption(parser, word, static_cast<ShaderInputLayout::DataValBase*>(val));
}
+ return SLANG_OK;
+ }
- Format parseFormatOption(Misc::TokenReader& parser)
+ SlangResult parseOption(
+ Misc::TokenReader& parser,
+ String const& word,
+ ShaderInputLayout::ObjectVal* val)
+ {
+ if (word == "type")
{
parser.Read("=");
- auto formatWord = parser.ReadWord();
-
- return _getFormatFromName(formatWord.getUnownedSlice());
+ val->typeName = parser.ReadWord();
}
+ else
+ {
+ return SLANG_FAIL;
+ }
+ return SLANG_OK;
+ }
- template<typename T>
- void maybeParseOptions(Misc::TokenReader& parser, T* val)
+ Format parseFormatOption(Misc::TokenReader& parser)
+ {
+ parser.Read("=");
+ auto formatWord = parser.ReadWord();
+
+ return _getFormatFromName(formatWord.getUnownedSlice());
+ }
+
+ template<typename T>
+ void maybeParseOptions(Misc::TokenReader& parser, T* val)
+ {
+ // parse options
+ if (parser.LookAhead("("))
{
- // parse options
- if (parser.LookAhead("("))
+ parser.Read("(");
+ while (!parser.IsEnd() && !parser.LookAhead(")"))
{
- parser.Read("(");
- while (!parser.IsEnd() && !parser.LookAhead(")"))
+ auto word = parser.ReadWord();
+ if (SLANG_FAILED(parseOption(parser, word, val)))
{
- auto word = parser.ReadWord();
- if( SLANG_FAILED(parseOption(parser, word, val)) )
- {
- throw ShaderInputLayoutFormatException(String("Unsupported option '") + word + String("' at line ") + String(parser.NextToken().Position.Line));
- }
-
- if (parser.LookAhead(","))
- parser.Read(",");
- else
- break;
+ throw ShaderInputLayoutFormatException(
+ String("Unsupported option '") + word + String("' at line ") +
+ String(parser.NextToken().Position.Line));
}
- parser.Read(")");
+
+ if (parser.LookAhead(","))
+ parser.Read(",");
+ else
+ break;
}
+ parser.Read(")");
}
+ }
- RefPtr<ShaderInputLayout::Val> parseNumericValExpr(Misc::TokenReader& parser, bool negate = false)
+ RefPtr<ShaderInputLayout::Val> parseNumericValExpr(
+ Misc::TokenReader& parser,
+ bool negate = false)
+ {
+ switch (parser.NextToken().Type)
{
- switch(parser.NextToken().Type)
+ case Misc::TokenType::IntLiteral:
{
- case Misc::TokenType::IntLiteral:
- {
- RefPtr<ShaderInputLayout::DataVal> val = new ShaderInputLayout::DataVal;
-
- uint32_t value = parser.ReadUInt();
- if(negate) value = uint32_t(-int32_t(value));
- val->bufferData.add(value);
+ RefPtr<ShaderInputLayout::DataVal> val = new ShaderInputLayout::DataVal;
- return val;
- }
- break;
+ uint32_t value = parser.ReadUInt();
+ if (negate)
+ value = uint32_t(-int32_t(value));
+ val->bufferData.add(value);
- case Misc::TokenType::DoubleLiteral:
- {
- RefPtr<ShaderInputLayout::DataVal> val = new ShaderInputLayout::DataVal;
+ return val;
+ }
+ break;
- float floatValue = parser.ReadFloat();
- if(negate) floatValue = -floatValue;
+ case Misc::TokenType::DoubleLiteral:
+ {
+ RefPtr<ShaderInputLayout::DataVal> val = new ShaderInputLayout::DataVal;
- uint32_t value = 0;
- memcpy(&value, &floatValue, sizeof(floatValue));
- val->bufferData.add(value);
+ float floatValue = parser.ReadFloat();
+ if (negate)
+ floatValue = -floatValue;
- return val;
- }
- break;
+ uint32_t value = 0;
+ memcpy(&value, &floatValue, sizeof(floatValue));
+ val->bufferData.add(value);
- default:
- throw ShaderInputLayoutFormatException(String("Expected a numeric literal but found '") + parser.NextToken().Content + String("' at line") + String(parser.NextToken().Position.Line));
+ return val;
}
+ break;
+
+ default:
+ throw ShaderInputLayoutFormatException(
+ String("Expected a numeric literal but found '") + parser.NextToken().Content +
+ String("' at line") + String(parser.NextToken().Position.Line));
}
+ }
- String parseTypeName(Misc::TokenReader& parser)
+ String parseTypeName(Misc::TokenReader& parser)
+ {
+ String typeName = parser.ReadWord();
+ if (parser.AdvanceIf("<"))
{
- String typeName = parser.ReadWord();
- if (parser.AdvanceIf("<"))
+ StringBuilder sb;
+ sb << typeName << "<";
+ for (;;)
{
- StringBuilder sb;
- sb << typeName << "<";
- for (;;)
- {
- if (parser.LookAhead(Misc::TokenType::IntLiteral))
- sb << parser.ReadInt();
- else
- sb << parseTypeName(parser);
- if (!parser.AdvanceIf(","))
- break;
- sb << ",";
- }
- sb << ">";
- parser.Read(">");
- return sb.produceString();
+ if (parser.LookAhead(Misc::TokenType::IntLiteral))
+ sb << parser.ReadInt();
+ else
+ sb << parseTypeName(parser);
+ if (!parser.AdvanceIf(","))
+ break;
+ sb << ",";
}
- return typeName;
+ sb << ">";
+ parser.Read(">");
+ return sb.produceString();
}
+ return typeName;
+ }
- RefPtr<ShaderInputLayout::Val> parseValExpr(Misc::TokenReader& parser)
- {
- typedef Misc::TokenType TokenType;
+ RefPtr<ShaderInputLayout::Val> parseValExpr(Misc::TokenReader& parser)
+ {
+ typedef Misc::TokenType TokenType;
- switch(parser.NextToken().Type)
+ switch (parser.NextToken().Type)
+ {
+ case TokenType::OpSub:
{
- case TokenType::OpSub:
- {
- parser.ReadToken();
- return parseNumericValExpr(parser, true);
- }
- break;
-
- case TokenType::IntLiteral:
- case TokenType::DoubleLiteral:
- return parseNumericValExpr(parser);
-
- case TokenType::LBrace:
- {
- // aggregate
- parser.ReadToken();
- RefPtr<ShaderInputLayout::AggVal> val = new ShaderInputLayout::AggVal;
-
- while( !parser.IsEnd() && !parser.LookAhead(TokenType::RBrace) )
- {
- ShaderInputLayout::Field field;
-
- if( parser.LookAhead(TokenType::Identifier) && parser.NextToken(1).Type == TokenType::Colon )
- {
- field.name = parser.ReadWord();
- parser.Read(TokenType::Colon);
- }
-
- field.val = parseValExpr(parser);
-
- val->fields.add(field);
-
- if(parser.LookAhead(TokenType::RBrace))
- break;
-
- parser.Read(TokenType::Comma);
- }
- parser.Read(TokenType::RBrace);
+ parser.ReadToken();
+ return parseNumericValExpr(parser, true);
+ }
+ break;
+ case TokenType::IntLiteral:
+ case TokenType::DoubleLiteral: return parseNumericValExpr(parser);
- return val;
- }
- break;
+ case TokenType::LBrace:
+ {
+ // aggregate
+ parser.ReadToken();
+ RefPtr<ShaderInputLayout::AggVal> val = new ShaderInputLayout::AggVal;
- case TokenType::LBracket:
+ while (!parser.IsEnd() && !parser.LookAhead(TokenType::RBrace))
{
- // array
- parser.ReadToken();
- RefPtr<ShaderInputLayout::ArrayVal> val = new ShaderInputLayout::ArrayVal;
+ ShaderInputLayout::Field field;
- while( !parser.IsEnd() && !parser.LookAhead(TokenType::RBracket) )
+ if (parser.LookAhead(TokenType::Identifier) &&
+ parser.NextToken(1).Type == TokenType::Colon)
{
- val->vals.add(parseValExpr(parser));
-
- if(parser.LookAhead(TokenType::RBracket))
- break;
-
- parser.Read(TokenType::Comma);
+ field.name = parser.ReadWord();
+ parser.Read(TokenType::Colon);
}
- parser.Read(TokenType::RBracket);
-
- return val;
- }
- break;
- case TokenType::Identifier:
- {
- if( parser.AdvanceIf("new") )
- {
- RefPtr<ShaderInputLayout::ObjectVal> val = new ShaderInputLayout::ObjectVal;
+ field.val = parseValExpr(parser);
- if( parser.NextToken().Type == TokenType::Identifier )
- {
- val->typeName = parseTypeName(parser);
- }
+ val->fields.add(field);
- val->contentVal = parseValExpr(parser);
- return val;
- }
- else if( parser.AdvanceIf("out") )
- {
- auto val = parseValExpr(parser);
- val->isOutput = true;
- return val;
- }
- else if (parser.AdvanceIf("specialize"))
- {
- RefPtr<ShaderInputLayout::SpecializeVal> val =
- new ShaderInputLayout::SpecializeVal();
+ if (parser.LookAhead(TokenType::RBrace))
+ break;
- parser.Read(Misc::TokenType::LParent);
- while (!parser.IsEnd() &&
- parser.NextToken().Type != Misc::TokenType::RParent)
- {
- val->typeArgs.add(parseTypeName(parser));
- if (!parser.AdvanceIf(","))
- break;
- }
- parser.Read(Misc::TokenType::RParent);
- val->contentVal = parseValExpr(parser);
- return val;
- }
- else if (parser.AdvanceIf("dynamic"))
- {
- RefPtr<ShaderInputLayout::SpecializeVal> val =
- new ShaderInputLayout::SpecializeVal();
- val->typeArgs.add("__Dynamic");
- val->contentVal = parseValExpr(parser);
- return val;
- }
- else
- {
- // We assume that any other word is introducing one of the other
- // cases for a parse-able value.
- return parseVal(parser);
- }
+ parser.Read(TokenType::Comma);
}
- break;
+ parser.Read(TokenType::RBrace);
- default:
- throw ShaderInputLayoutFormatException(String("Unexpected '") + parser.NextToken().Content + String("' at line") + String(parser.NextToken().Position.Line));
- }
- }
- RefPtr<ShaderInputLayout::Val> parseVal(Misc::TokenReader& parser)
- {
- auto word = parser.NextToken().Content;
- if (parser.AdvanceIf("begin_array"))
- {
- RefPtr<ShaderInputLayout::ArrayVal> val = new ShaderInputLayout::ArrayVal;
- pushParentVal(val);
return val;
}
- else if (parser.AdvanceIf("begin_object"))
- {
- RefPtr<ShaderInputLayout::ObjectVal> val = new ShaderInputLayout::ObjectVal;
- maybeParseOptions(parser, val.Ptr());
-
- RefPtr<ShaderInputLayout::AggVal> contentVal = new ShaderInputLayout::AggVal;
- val->contentVal = contentVal;
- pushParentVal(contentVal);
+ break;
- return val;
- }
- else if (parser.AdvanceIf("uniform"))
+ case TokenType::LBracket:
{
- RefPtr<ShaderInputLayout::DataVal> val = new ShaderInputLayout::DataVal;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("cbuffer"))
- {
- // A `cbuffer` is basically just an object where the content of
- // the object is being provided by `uniform` data instead.
+ // array
+ parser.ReadToken();
+ RefPtr<ShaderInputLayout::ArrayVal> val = new ShaderInputLayout::ArrayVal;
- RefPtr<ShaderInputLayout::ObjectVal> objVal = new ShaderInputLayout::ObjectVal;
+ while (!parser.IsEnd() && !parser.LookAhead(TokenType::RBracket))
+ {
+ val->vals.add(parseValExpr(parser));
- RefPtr<ShaderInputLayout::DataVal> dataVal = new ShaderInputLayout::DataVal;
- maybeParseOptions(parser, dataVal.Ptr());
+ if (parser.LookAhead(TokenType::RBracket))
+ break;
- objVal->contentVal = dataVal;
+ parser.Read(TokenType::Comma);
+ }
+ parser.Read(TokenType::RBracket);
- return objVal;
- }
- else if (parser.AdvanceIf("ubuffer"))
- {
- RefPtr<ShaderInputLayout::BufferVal> val = new ShaderInputLayout::BufferVal;
- val->bufferDesc.type = InputBufferType::StorageBuffer;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("Texture1D"))
- {
- RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
- val->textureDesc.dimension = 1;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("RWTextureBuffer"))
- {
- RefPtr<ShaderInputLayout::BufferVal> val = new ShaderInputLayout::BufferVal;
- val->bufferDesc.type = InputBufferType::StorageBuffer;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("Texture2D"))
- {
- RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
- val->textureDesc.dimension = 2;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("Texture3D"))
- {
- RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
- val->textureDesc.dimension = 3;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("TextureCube"))
- {
- RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
- val->textureDesc.dimension = 2;
- val->textureDesc.isCube = true;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("RWTexture1D"))
- {
- RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
- val->textureDesc.dimension = 1;
- val->textureDesc.isRWTexture = true;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("RWTexture2D"))
- {
- RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
- val->textureDesc.dimension = 2;
- val->textureDesc.isRWTexture = true;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("RWTexture3D"))
- {
- RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
- val->textureDesc.dimension = 3;
- val->textureDesc.isRWTexture = true;
- maybeParseOptions(parser, val.Ptr());
return val;
}
- else if (parser.AdvanceIf("RWTextureCube"))
- {
- RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
- val->textureDesc.dimension = 2;
- val->textureDesc.isCube = true;
- val->textureDesc.isRWTexture = true;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("Sampler"))
- {
- RefPtr<ShaderInputLayout::SamplerVal> val = new ShaderInputLayout::SamplerVal;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("TextureSampler1D"))
- {
- RefPtr<ShaderInputLayout::CombinedTextureSamplerVal> val = new ShaderInputLayout::CombinedTextureSamplerVal;
- val->textureVal = new ShaderInputLayout::TextureVal;
- val->samplerVal = new ShaderInputLayout::SamplerVal;
- val->textureVal->textureDesc.dimension = 1;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("TextureSampler2D"))
- {
- RefPtr<ShaderInputLayout::CombinedTextureSamplerVal> val = new ShaderInputLayout::CombinedTextureSamplerVal;
- val->textureVal = new ShaderInputLayout::TextureVal;
- val->samplerVal = new ShaderInputLayout::SamplerVal;
- val->textureVal->textureDesc.dimension = 2;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("TextureSampler3D"))
- {
- RefPtr<ShaderInputLayout::CombinedTextureSamplerVal> val = new ShaderInputLayout::CombinedTextureSamplerVal;
- val->textureVal = new ShaderInputLayout::TextureVal;
- val->samplerVal = new ShaderInputLayout::SamplerVal;
- val->textureVal->textureDesc.dimension = 3;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("TextureSamplerCube"))
- {
- RefPtr<ShaderInputLayout::CombinedTextureSamplerVal> val = new ShaderInputLayout::CombinedTextureSamplerVal;
- val->textureVal = new ShaderInputLayout::TextureVal;
- val->samplerVal = new ShaderInputLayout::SamplerVal;
- val->textureVal->textureDesc.dimension = 2;
- val->textureVal->textureDesc.isCube = true;
- maybeParseOptions(parser, val.Ptr());
- return val;
- }
- else if (parser.AdvanceIf("AccelerationStructure"))
- {
- RefPtr<ShaderInputLayout::AccelerationStructureVal> val =
- new ShaderInputLayout::AccelerationStructureVal();
- return val;
- }
- else
- {
- throw ShaderInputLayoutFormatException(String("Unknown shader input type '") + word + String("' at line") + String(parser.NextToken().Position.Line));
- }
- parser.ReadToken();
- return nullptr;
- }
-
- String parseName(Misc::TokenReader& parser)
- {
- typedef Misc::Token Token;
- typedef Misc::TokenType TokenType;
-
- StringBuilder builder;
+ break;
- Token nameToken = parser.ReadToken();
- if (nameToken.Type != TokenType::Identifier)
+ case TokenType::Identifier:
{
- throw ShaderInputLayoutFormatException(StringBuilder() << "Invalid input syntax at line " << parser.NextToken().Position.Line);
- }
- builder << nameToken.Content;
+ if (parser.AdvanceIf("new"))
+ {
+ RefPtr<ShaderInputLayout::ObjectVal> val = new ShaderInputLayout::ObjectVal;
- for(;;)
- {
- Token token = parser.NextToken(0);
+ if (parser.NextToken().Type == TokenType::Identifier)
+ {
+ val->typeName = parseTypeName(parser);
+ }
- if (token.Type == TokenType::LBracket)
+ val->contentVal = parseValExpr(parser);
+ return val;
+ }
+ else if (parser.AdvanceIf("out"))
{
- parser.ReadToken();
- int index = parser.ReadInt();
- SLANG_ASSERT(index >= 0);
- parser.ReadMatchingToken(TokenType::RBracket);
-
- builder << "[" << index << "]";
+ auto val = parseValExpr(parser);
+ val->isOutput = true;
+ return val;
}
- else if (token.Type == TokenType::Dot)
+ else if (parser.AdvanceIf("specialize"))
{
- parser.ReadToken();
- Token identifierToken = parser.ReadMatchingToken(TokenType::Identifier);
+ RefPtr<ShaderInputLayout::SpecializeVal> val =
+ new ShaderInputLayout::SpecializeVal();
- builder << "." << identifierToken.Content;
+ parser.Read(Misc::TokenType::LParent);
+ while (!parser.IsEnd() && parser.NextToken().Type != Misc::TokenType::RParent)
+ {
+ val->typeArgs.add(parseTypeName(parser));
+ if (!parser.AdvanceIf(","))
+ break;
+ }
+ parser.Read(Misc::TokenType::RParent);
+ val->contentVal = parseValExpr(parser);
+ return val;
+ }
+ else if (parser.AdvanceIf("dynamic"))
+ {
+ RefPtr<ShaderInputLayout::SpecializeVal> val =
+ new ShaderInputLayout::SpecializeVal();
+ val->typeArgs.add("__Dynamic");
+ val->contentVal = parseValExpr(parser);
+ return val;
}
else
{
- return builder;
+ // We assume that any other word is introducing one of the other
+ // cases for a parse-able value.
+ return parseVal(parser);
}
}
+ break;
+
+ default:
+ throw ShaderInputLayoutFormatException(
+ String("Unexpected '") + parser.NextToken().Content + String("' at line") +
+ String(parser.NextToken().Position.Line));
}
+ }
- void parseFieldBindings(Misc::TokenReader& parser, ShaderInputLayout::Field& ioField)
+ RefPtr<ShaderInputLayout::Val> parseVal(Misc::TokenReader& parser)
+ {
+ auto word = parser.NextToken().Content;
+ if (parser.AdvanceIf("begin_array"))
{
- // parse bindings
- if (parser.LookAhead(":"))
- {
- parser.Read(":");
- while (!parser.IsEnd())
- {
- if (parser.AdvanceIf("out"))
- {
- ioField.val->isOutput = true;
- }
- else if (parser.AdvanceIf("name"))
- {
- // Optionally consume '='
- if (parser.NextToken().Type == Misc::TokenType::OpAssign)
- {
- parser.ReadToken();
- }
+ RefPtr<ShaderInputLayout::ArrayVal> val = new ShaderInputLayout::ArrayVal;
+ pushParentVal(val);
+ return val;
+ }
+ else if (parser.AdvanceIf("begin_object"))
+ {
+ RefPtr<ShaderInputLayout::ObjectVal> val = new ShaderInputLayout::ObjectVal;
+ maybeParseOptions(parser, val.Ptr());
- ioField.name = parseName(parser);
- }
- else
- {
- fprintf(stderr, "Invalid TEST_INPUT syntax '%s'\n", parser.NextToken().Content.getBuffer());
- break;
- }
+ RefPtr<ShaderInputLayout::AggVal> contentVal = new ShaderInputLayout::AggVal;
+ val->contentVal = contentVal;
+ pushParentVal(contentVal);
- if (parser.LookAhead(","))
- parser.Read(",");
- }
- }
+ return val;
}
-
- void pushParentVal(ShaderInputLayout::ParentVal* val)
+ else if (parser.AdvanceIf("uniform"))
{
- parentValStack.add(parentVal);
- parentVal = val;
+ RefPtr<ShaderInputLayout::DataVal> val = new ShaderInputLayout::DataVal;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
}
-
- void parseValEntry(Misc::TokenReader& parser)
+ else if (parser.AdvanceIf("cbuffer"))
{
- auto parentForNewVal = parentVal;
+ // A `cbuffer` is basically just an object where the content of
+ // the object is being provided by `uniform` data instead.
- ShaderInputLayout::Field field;
- field.val = parseVal(parser);
- parseFieldBindings(parser, field);
+ RefPtr<ShaderInputLayout::ObjectVal> objVal = new ShaderInputLayout::ObjectVal;
- parentForNewVal->addField(field);
- }
+ RefPtr<ShaderInputLayout::DataVal> dataVal = new ShaderInputLayout::DataVal;
+ maybeParseOptions(parser, dataVal.Ptr());
+
+ objVal->contentVal = dataVal;
- void parseSetEntry(Misc::TokenReader& parser)
+ return objVal;
+ }
+ else if (parser.AdvanceIf("ubuffer"))
+ {
+ RefPtr<ShaderInputLayout::BufferVal> val = new ShaderInputLayout::BufferVal;
+ val->bufferDesc.type = InputBufferType::StorageBuffer;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("Texture1D"))
+ {
+ RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
+ val->textureDesc.dimension = 1;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("RWTextureBuffer"))
+ {
+ RefPtr<ShaderInputLayout::BufferVal> val = new ShaderInputLayout::BufferVal;
+ val->bufferDesc.type = InputBufferType::StorageBuffer;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("Texture2D"))
+ {
+ RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
+ val->textureDesc.dimension = 2;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("Texture3D"))
+ {
+ RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
+ val->textureDesc.dimension = 3;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("TextureCube"))
+ {
+ RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
+ val->textureDesc.dimension = 2;
+ val->textureDesc.isCube = true;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("RWTexture1D"))
+ {
+ RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
+ val->textureDesc.dimension = 1;
+ val->textureDesc.isRWTexture = true;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("RWTexture2D"))
+ {
+ RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
+ val->textureDesc.dimension = 2;
+ val->textureDesc.isRWTexture = true;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("RWTexture3D"))
+ {
+ RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
+ val->textureDesc.dimension = 3;
+ val->textureDesc.isRWTexture = true;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("RWTextureCube"))
+ {
+ RefPtr<ShaderInputLayout::TextureVal> val = new ShaderInputLayout::TextureVal;
+ val->textureDesc.dimension = 2;
+ val->textureDesc.isCube = true;
+ val->textureDesc.isRWTexture = true;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("Sampler"))
+ {
+ RefPtr<ShaderInputLayout::SamplerVal> val = new ShaderInputLayout::SamplerVal;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("TextureSampler1D"))
+ {
+ RefPtr<ShaderInputLayout::CombinedTextureSamplerVal> val =
+ new ShaderInputLayout::CombinedTextureSamplerVal;
+ val->textureVal = new ShaderInputLayout::TextureVal;
+ val->samplerVal = new ShaderInputLayout::SamplerVal;
+ val->textureVal->textureDesc.dimension = 1;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("TextureSampler2D"))
+ {
+ RefPtr<ShaderInputLayout::CombinedTextureSamplerVal> val =
+ new ShaderInputLayout::CombinedTextureSamplerVal;
+ val->textureVal = new ShaderInputLayout::TextureVal;
+ val->samplerVal = new ShaderInputLayout::SamplerVal;
+ val->textureVal->textureDesc.dimension = 2;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("TextureSampler3D"))
{
- auto parentForNewVal = parentVal;
+ RefPtr<ShaderInputLayout::CombinedTextureSamplerVal> val =
+ new ShaderInputLayout::CombinedTextureSamplerVal;
+ val->textureVal = new ShaderInputLayout::TextureVal;
+ val->samplerVal = new ShaderInputLayout::SamplerVal;
+ val->textureVal->textureDesc.dimension = 3;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("TextureSamplerCube"))
+ {
+ RefPtr<ShaderInputLayout::CombinedTextureSamplerVal> val =
+ new ShaderInputLayout::CombinedTextureSamplerVal;
+ val->textureVal = new ShaderInputLayout::TextureVal;
+ val->samplerVal = new ShaderInputLayout::SamplerVal;
+ val->textureVal->textureDesc.dimension = 2;
+ val->textureVal->textureDesc.isCube = true;
+ maybeParseOptions(parser, val.Ptr());
+ return val;
+ }
+ else if (parser.AdvanceIf("AccelerationStructure"))
+ {
+ RefPtr<ShaderInputLayout::AccelerationStructureVal> val =
+ new ShaderInputLayout::AccelerationStructureVal();
+ return val;
+ }
+ else
+ {
+ throw ShaderInputLayoutFormatException(
+ String("Unknown shader input type '") + word + String("' at line") +
+ String(parser.NextToken().Position.Line));
+ }
+ parser.ReadToken();
+ return nullptr;
+ }
- ShaderInputLayout::Field field;
- field.name = parseName(parser);
- parser.Read(Misc::TokenType::OpAssign);
- field.val = parseValExpr(parser);
+ String parseName(Misc::TokenReader& parser)
+ {
+ typedef Misc::Token Token;
+ typedef Misc::TokenType TokenType;
- parentForNewVal->addField(field);
- }
+ StringBuilder builder;
- void parseTypeConformance(Misc::TokenReader& parser)
+ Token nameToken = parser.ReadToken();
+ if (nameToken.Type != TokenType::Identifier)
{
- ShaderInputLayout::TypeConformanceVal conformance;
- conformance.derivedTypeName = parseTypeName(parser);
- parser.Read(":");
- conformance.baseTypeName = parseTypeName(parser);
- if (parser.AdvanceIf("="))
- conformance.idOverride = parser.ReadInt();
- layout->typeConformances.add(conformance);
+ throw ShaderInputLayoutFormatException(
+ StringBuilder() << "Invalid input syntax at line "
+ << parser.NextToken().Position.Line);
}
+ builder << nameToken.Content;
- void parseLine(Misc::TokenReader& parser)
+ for (;;)
{
- if (parser.LookAhead("entryPointSpecializationArg")
- || parser.LookAhead("type")
- || parser.LookAhead("entryPointExistentialType"))
+ Token token = parser.NextToken(0);
+
+ if (token.Type == TokenType::LBracket)
{
parser.ReadToken();
- StringBuilder typeExp;
- while (!parser.IsEnd())
- typeExp << parser.ReadToken().Content;
- layout->entryPointSpecializationArgs.add(typeExp);
+ int index = parser.ReadInt();
+ SLANG_ASSERT(index >= 0);
+ parser.ReadMatchingToken(TokenType::RBracket);
+
+ builder << "[" << index << "]";
}
- else if (parser.LookAhead("globalSpecializationArg")
- || parser.LookAhead("global_type")
- || parser.LookAhead("globalExistentialType"))
+ else if (token.Type == TokenType::Dot)
{
parser.ReadToken();
- StringBuilder typeExp;
- while (!parser.IsEnd())
- typeExp << parser.ReadToken().Content;
- layout->globalSpecializationArgs.add(typeExp);
- }
- else if (parser.AdvanceIf("render_targets"))
- {
- layout->numRenderTargets = parser.ReadInt();
- }
- else if( parser.AdvanceIf("end") )
- {
- parentVal = parentValStack.getLast();
- parentValStack.removeLast();
- }
- else if( parser.AdvanceIf("set") )
- {
- parseSetEntry(parser);
- }
- else if (parser.AdvanceIf("type_conformance"))
- {
- parseTypeConformance(parser);
+ Token identifierToken = parser.ReadMatchingToken(TokenType::Identifier);
+
+ builder << "." << identifierToken.Content;
}
else
{
- parseValEntry(parser);
+ return builder;
}
}
+ }
- RefPtr<ShaderInputLayout::AggVal> parse(const char * source)
+ void parseFieldBindings(Misc::TokenReader& parser, ShaderInputLayout::Field& ioField)
+ {
+ // parse bindings
+ if (parser.LookAhead(":"))
{
- RefPtr<ShaderInputLayout::AggVal> rootVal = new ShaderInputLayout::AggVal;
- parentVal = rootVal;
-
- auto lines = Misc::Split(source, '\n');
- for (auto & line : lines)
+ parser.Read(":");
+ while (!parser.IsEnd())
{
- if (line.startsWith("//TEST_INPUT:"))
+ if (parser.AdvanceIf("out"))
{
- auto lineContent = line.subString(13, line.getLength() - 13);
- Misc::TokenReader parser(lineContent);
- try
- {
- parseLine(parser);
- }
- catch (const Misc::TextFormatException&)
+ ioField.val->isOutput = true;
+ }
+ else if (parser.AdvanceIf("name"))
+ {
+ // Optionally consume '='
+ if (parser.NextToken().Type == Misc::TokenType::OpAssign)
{
- StringBuilder msg;
- msg << "Invalid input syntax at line " << parser.NextToken().Position.Line;
- throw ShaderInputLayoutFormatException(msg);
+ parser.ReadToken();
}
+
+ ioField.name = parseName(parser);
}
+ else
+ {
+ fprintf(
+ stderr,
+ "Invalid TEST_INPUT syntax '%s'\n",
+ parser.NextToken().Content.getBuffer());
+ break;
+ }
+
+ if (parser.LookAhead(","))
+ parser.Read(",");
}
+ }
+ }
- // TODO: check that stack has been maintained correctly...
+ void pushParentVal(ShaderInputLayout::ParentVal* val)
+ {
+ parentValStack.add(parentVal);
+ parentVal = val;
+ }
- return rootVal;
- }
- };
+ void parseValEntry(Misc::TokenReader& parser)
+ {
+ auto parentForNewVal = parentVal;
+
+ ShaderInputLayout::Field field;
+ field.val = parseVal(parser);
+ parseFieldBindings(parser, field);
+
+ parentForNewVal->addField(field);
+ }
- void ShaderInputLayout::parse(RandomGenerator* rand, const char * source)
+ void parseSetEntry(Misc::TokenReader& parser)
{
- rootVal = nullptr;
- globalSpecializationArgs.clear();
- entryPointSpecializationArgs.clear();
+ auto parentForNewVal = parentVal;
+
+ ShaderInputLayout::Field field;
+ field.name = parseName(parser);
+ parser.Read(Misc::TokenType::OpAssign);
+ field.val = parseValExpr(parser);
- ShaderInputLayoutParser parser(this, rand);
- rootVal = parser.parse(source);
+ parentForNewVal->addField(field);
}
- /* static */SlangResult ShaderInputLayout::writeBinding(slang::TypeLayoutReflection* typeLayout, const void* data, size_t sizeInBytes, WriterHelper writer)
+ void parseTypeConformance(Misc::TokenReader& parser)
{
- typedef slang::TypeReflection::ScalarType ScalarType;
+ ShaderInputLayout::TypeConformanceVal conformance;
+ conformance.derivedTypeName = parseTypeName(parser);
+ parser.Read(":");
+ conformance.baseTypeName = parseTypeName(parser);
+ if (parser.AdvanceIf("="))
+ conformance.idOverride = parser.ReadInt();
+ layout->typeConformances.add(conformance);
+ }
- slang::TypeReflection::ScalarType scalarType = slang::TypeReflection::ScalarType::None;
+ void parseLine(Misc::TokenReader& parser)
+ {
+ if (parser.LookAhead("entryPointSpecializationArg") || parser.LookAhead("type") ||
+ parser.LookAhead("entryPointExistentialType"))
+ {
+ parser.ReadToken();
+ StringBuilder typeExp;
+ while (!parser.IsEnd())
+ typeExp << parser.ReadToken().Content;
+ layout->entryPointSpecializationArgs.add(typeExp);
+ }
+ else if (
+ parser.LookAhead("globalSpecializationArg") || parser.LookAhead("global_type") ||
+ parser.LookAhead("globalExistentialType"))
+ {
+ parser.ReadToken();
+ StringBuilder typeExp;
+ while (!parser.IsEnd())
+ typeExp << parser.ReadToken().Content;
+ layout->globalSpecializationArgs.add(typeExp);
+ }
+ else if (parser.AdvanceIf("render_targets"))
+ {
+ layout->numRenderTargets = parser.ReadInt();
+ }
+ else if (parser.AdvanceIf("end"))
+ {
+ parentVal = parentValStack.getLast();
+ parentValStack.removeLast();
+ }
+ else if (parser.AdvanceIf("set"))
+ {
+ parseSetEntry(parser);
+ }
+ else if (parser.AdvanceIf("type_conformance"))
+ {
+ parseTypeConformance(parser);
+ }
+ else
+ {
+ parseValEntry(parser);
+ }
+ }
- slang::TypeLayoutReflection* elementTypeLayout = nullptr;
+ RefPtr<ShaderInputLayout::AggVal> parse(const char* source)
+ {
+ RefPtr<ShaderInputLayout::AggVal> rootVal = new ShaderInputLayout::AggVal;
+ parentVal = rootVal;
- if (typeLayout)
+ auto lines = Misc::Split(source, '\n');
+ for (auto& line : lines)
{
- switch (typeLayout->getKind())
+ if (line.startsWith("//TEST_INPUT:"))
{
-
- //case slang::TypeReflection::Kind::Struct:
- case slang::TypeReflection::Kind::Array:
- case slang::TypeReflection::Kind::Matrix:
- case slang::TypeReflection::Kind::Vector:
+ auto lineContent = line.subString(13, line.getLength() - 13);
+ Misc::TokenReader parser(lineContent);
+ try
{
- elementTypeLayout = typeLayout->getElementTypeLayout();
- break;
+ parseLine(parser);
}
- case slang::TypeReflection::Kind::Scalar:
+ catch (const Misc::TextFormatException&)
{
- elementTypeLayout = typeLayout;
- break;
- }
- case slang::TypeReflection::Kind::Resource:
- {
- elementTypeLayout = typeLayout->getElementTypeLayout();
- break;
- }
- case slang::TypeReflection::Kind::TextureBuffer:
- case slang::TypeReflection::Kind::ShaderStorageBuffer:
- {
- elementTypeLayout = typeLayout->getElementTypeLayout();
- break;
+ StringBuilder msg;
+ msg << "Invalid input syntax at line " << parser.NextToken().Position.Line;
+ throw ShaderInputLayoutFormatException(msg);
}
}
}
- if (elementTypeLayout)
- {
- scalarType = elementTypeLayout->getScalarType();
- }
+ // TODO: check that stack has been maintained correctly...
- if (scalarType != ScalarType::None && scalarType != ScalarType::Void)
- {
- UnownedStringSlice text = TypeTextUtil::getScalarTypeName(scalarType);
- // Write out the type
- writer.put("type: ");
- writer.put(text);
- writer.put("\n");
- }
+ return rootVal;
+ }
+};
+
+void ShaderInputLayout::parse(RandomGenerator* rand, const char* source)
+{
+ rootVal = nullptr;
+ globalSpecializationArgs.clear();
+ entryPointSpecializationArgs.clear();
+
+ ShaderInputLayoutParser parser(this, rand);
+ rootVal = parser.parse(source);
+}
+
+/* static */ SlangResult ShaderInputLayout::writeBinding(
+ slang::TypeLayoutReflection* typeLayout,
+ const void* data,
+ size_t sizeInBytes,
+ WriterHelper writer)
+{
+ typedef slang::TypeReflection::ScalarType ScalarType;
- switch (scalarType)
+ slang::TypeReflection::ScalarType scalarType = slang::TypeReflection::ScalarType::None;
+
+ slang::TypeLayoutReflection* elementTypeLayout = nullptr;
+
+ if (typeLayout)
+ {
+ switch (typeLayout->getKind())
{
- // TODO(JS):
- // Bool is here, because it's not clear across APIs how bool is laid out in memory
- default:
- case ScalarType::None:
- case ScalarType::Void:
- case ScalarType::Bool:
+
+ // case slang::TypeReflection::Kind::Struct:
+ case slang::TypeReflection::Kind::Array:
+ case slang::TypeReflection::Kind::Matrix:
+ case slang::TypeReflection::Kind::Vector:
{
- auto ptr = (const uint32_t*)data;
- const size_t size = sizeInBytes / sizeof(ptr[0]);
- for (size_t i = 0; i < size; ++i)
- {
- uint32_t v = ptr[i];
- writer.print("%X\n", v);
- }
+ elementTypeLayout = typeLayout->getElementTypeLayout();
break;
}
- case ScalarType::Float16:
+ case slang::TypeReflection::Kind::Scalar:
{
- auto ptr = (const uint16_t*)data;
- const size_t size = sizeInBytes / sizeof(ptr[0]);
- for (size_t i = 0; i < size; ++i)
- {
- const float v = HalfToFloat(ptr[i]);
- writer.print("%f\n", v);
- }
+ elementTypeLayout = typeLayout;
break;
}
- case ScalarType::UInt32:
+ case slang::TypeReflection::Kind::Resource:
{
- auto ptr = (const uint32_t*)data;
- const size_t size = sizeInBytes / sizeof(ptr[0]);
- for (size_t i = 0; i < size; ++i)
- {
- uint32_t v = ptr[i];
- writer.print("%u\n", v);
- }
+ elementTypeLayout = typeLayout->getElementTypeLayout();
break;
}
- case ScalarType::Int32:
+ case slang::TypeReflection::Kind::TextureBuffer:
+ case slang::TypeReflection::Kind::ShaderStorageBuffer:
{
- auto ptr = (const int32_t*)data;
- const size_t size = sizeInBytes / sizeof(ptr[0]);
- for (size_t i = 0; i < size; ++i)
- {
- int32_t v = ptr[i];
- writer.print("%i\n", v);
- }
+ elementTypeLayout = typeLayout->getElementTypeLayout();
break;
}
- case ScalarType::Int64:
+ }
+ }
+
+ if (elementTypeLayout)
+ {
+ scalarType = elementTypeLayout->getScalarType();
+ }
+
+ if (scalarType != ScalarType::None && scalarType != ScalarType::Void)
+ {
+ UnownedStringSlice text = TypeTextUtil::getScalarTypeName(scalarType);
+ // Write out the type
+ writer.put("type: ");
+ writer.put(text);
+ writer.put("\n");
+ }
+
+ switch (scalarType)
+ {
+ // TODO(JS):
+ // Bool is here, because it's not clear across APIs how bool is laid out in memory
+ default:
+ case ScalarType::None:
+ case ScalarType::Void:
+ case ScalarType::Bool:
+ {
+ auto ptr = (const uint32_t*)data;
+ const size_t size = sizeInBytes / sizeof(ptr[0]);
+ for (size_t i = 0; i < size; ++i)
+ {
+ uint32_t v = ptr[i];
+ writer.print("%X\n", v);
+ }
+ break;
+ }
+ case ScalarType::Float16:
+ {
+ auto ptr = (const uint16_t*)data;
+ const size_t size = sizeInBytes / sizeof(ptr[0]);
+ for (size_t i = 0; i < size; ++i)
{
- auto ptr = (const int64_t*)data;
- const size_t size = sizeInBytes / sizeof(ptr[0]);
- for (size_t i = 0; i < size; ++i)
- {
- int64_t v = ptr[i];
- writer.print("%" PRId64 "\n", v);
- }
- break;
+ const float v = HalfToFloat(ptr[i]);
+ writer.print("%f\n", v);
}
- case ScalarType::UInt64:
+ break;
+ }
+ case ScalarType::UInt32:
+ {
+ auto ptr = (const uint32_t*)data;
+ const size_t size = sizeInBytes / sizeof(ptr[0]);
+ for (size_t i = 0; i < size; ++i)
{
- auto ptr = (const uint64_t*)data;
- const size_t size = sizeInBytes / sizeof(ptr[0]);
- for (size_t i = 0; i < size; ++i)
- {
- uint64_t v = ptr[i];
- writer.print("%" PRIu64 "\n", v);
- }
- break;
+ uint32_t v = ptr[i];
+ writer.print("%u\n", v);
}
- case ScalarType::Float32:
+ break;
+ }
+ case ScalarType::Int32:
+ {
+ auto ptr = (const int32_t*)data;
+ const size_t size = sizeInBytes / sizeof(ptr[0]);
+ for (size_t i = 0; i < size; ++i)
{
- auto ptr = (const float*)data;
- const size_t size = sizeInBytes / sizeof(ptr[0]);
- for (size_t i = 0; i < size; ++i)
- {
- const float v = ptr[i];
- writer.print("%f\n", v);
- }
- break;
+ int32_t v = ptr[i];
+ writer.print("%i\n", v);
}
- case ScalarType::Float64:
+ break;
+ }
+ case ScalarType::Int64:
+ {
+ auto ptr = (const int64_t*)data;
+ const size_t size = sizeInBytes / sizeof(ptr[0]);
+ for (size_t i = 0; i < size; ++i)
{
- auto ptr = (const double*)data;
- const size_t size = sizeInBytes / sizeof(ptr[0]);
- for (size_t i = 0; i < size; ++i)
- {
- const double v = ptr[i];
- writer.print("%f\n", v);
- }
- break;
+ int64_t v = ptr[i];
+ writer.print("%" PRId64 "\n", v);
}
+ break;
+ }
+ case ScalarType::UInt64:
+ {
+ auto ptr = (const uint64_t*)data;
+ const size_t size = sizeInBytes / sizeof(ptr[0]);
+ for (size_t i = 0; i < size; ++i)
+ {
+ uint64_t v = ptr[i];
+ writer.print("%" PRIu64 "\n", v);
+ }
+ break;
+ }
+ case ScalarType::Float32:
+ {
+ auto ptr = (const float*)data;
+ const size_t size = sizeInBytes / sizeof(ptr[0]);
+ for (size_t i = 0; i < size; ++i)
+ {
+ const float v = ptr[i];
+ writer.print("%f\n", v);
+ }
+ break;
+ }
+ case ScalarType::Float64:
+ {
+ auto ptr = (const double*)data;
+ const size_t size = sizeInBytes / sizeof(ptr[0]);
+ for (size_t i = 0; i < size; ++i)
+ {
+ const double v = ptr[i];
+ writer.print("%f\n", v);
+ }
+ break;
}
-
- return SLANG_OK;
}
- void loadDataIntoHalf(uint16_t& out, const uint8_t& in)
- {
- out = FloatToHalf((float(in) / 255.0f));
- }
- void loadDataIntoFloat(float& out, const uint8_t& in)
- {
- out = (float(in)/255.0f);
- }
- template<typename T>
- void loadDataIntoUint(T& out, const uint8_t& in)
- {
- out = T(in);
- }
- template<typename T>
- void loadDataIntoInt(T& out, const uint8_t& in)
- {
- out = T(in);
- }
+ return SLANG_OK;
+}
- // T for type to return, F for function pointer to operate on uint8->T
- template<typename T, typename F>
- void generateTextureDataWithTargetTStorage(TextureData& output, const InputTextureDesc& desc, const rhi::FormatInfo& formatInfo, F loadUint8ToT)
- {
- // the following function assumes input of 0 or 1 since our testing framework only tests with 0 or 1
- TextureData work;
- generateTextureDataRGB8(work, desc);
+void loadDataIntoHalf(uint16_t& out, const uint8_t& in)
+{
+ out = FloatToHalf((float(in) / 255.0f));
+}
+void loadDataIntoFloat(float& out, const uint8_t& in)
+{
+ out = (float(in) / 255.0f);
+}
+template<typename T>
+void loadDataIntoUint(T& out, const uint8_t& in)
+{
+ out = T(in);
+}
+template<typename T>
+void loadDataIntoInt(T& out, const uint8_t& in)
+{
+ out = T(in);
+}
- output.init(desc.format);
+// T for type to return, F for function pointer to operate on uint8->T
+template<typename T, typename F>
+void generateTextureDataWithTargetTStorage(
+ TextureData& output,
+ const InputTextureDesc& desc,
+ const rhi::FormatInfo& formatInfo,
+ F loadUint8ToT)
+{
+ // the following function assumes input of 0 or 1 since our testing framework only tests with 0
+ // or 1
+ TextureData work;
+ generateTextureDataRGB8(work, desc);
- output.m_textureSize = work.m_textureSize;
- output.m_mipLevels = work.m_mipLevels;
- output.m_arraySize = work.m_arraySize;
+ output.init(desc.format);
- List<TextureData::Slice>& dstSlices = output.m_slices;
+ output.m_textureSize = work.m_textureSize;
+ output.m_mipLevels = work.m_mipLevels;
+ output.m_arraySize = work.m_arraySize;
- Index numSlices = work.m_slices.getCount();
- dstSlices.setCount(numSlices);
+ List<TextureData::Slice>& dstSlices = output.m_slices;
- for (int i = 0; i < numSlices; ++i)
- {
- const TextureData::Slice& srcSlice = work.m_slices[i];
+ Index numSlices = work.m_slices.getCount();
+ dstSlices.setCount(numSlices);
- const Index pixelCount = srcSlice.valuesCount;
- const uint8_t* srcPixels = (const uint8_t*)srcSlice.values;
+ for (int i = 0; i < numSlices; ++i)
+ {
+ const TextureData::Slice& srcSlice = work.m_slices[i];
- T* dstPixels = (T*)output.setSliceCount(i, pixelCount);
- switch (formatInfo.channelCount)
- {
- case 1:
+ const Index pixelCount = srcSlice.valuesCount;
+ const uint8_t* srcPixels = (const uint8_t*)srcSlice.values;
+
+ T* dstPixels = (T*)output.setSliceCount(i, pixelCount);
+ switch (formatInfo.channelCount)
+ {
+ case 1:
{
for (Index j = 0; j < pixelCount; ++j, srcPixels += 4, dstPixels += 1)
{
@@ -1198,7 +1251,7 @@ namespace renderer_test
}
break;
}
- case 2:
+ case 2:
{
for (Index j = 0; j < pixelCount; ++j, srcPixels += 4, dstPixels += 2)
{
@@ -1208,7 +1261,7 @@ namespace renderer_test
}
break;
}
- case 3:
+ case 3:
{
for (Index j = 0; j < pixelCount; ++j, srcPixels += 4, dstPixels += 3)
{
@@ -1219,7 +1272,7 @@ namespace renderer_test
}
break;
}
- case 4:
+ case 4:
{
for (Index j = 0; j < pixelCount; ++j, srcPixels += 4, dstPixels += 4)
{
@@ -1231,245 +1284,286 @@ namespace renderer_test
}
break;
}
- }
}
}
- void generateTextureData(TextureData& output, const InputTextureDesc& desc)
- {
- const FormatInfo& formatInfo = getFormatInfo(desc.format);
+}
+void generateTextureData(TextureData& output, const InputTextureDesc& desc)
+{
+ const FormatInfo& formatInfo = getFormatInfo(desc.format);
- switch (desc.format)
+ switch (desc.format)
+ {
+ case Format::R8G8B8A8_UNORM:
{
- case Format::R8G8B8A8_UNORM:
- {
- generateTextureDataRGB8(output, desc);
- break;
- }
- case Format::R16_FLOAT:
- case Format::R16G16_FLOAT:
- case Format::R16G16B16A16_FLOAT:
- {
- generateTextureDataWithTargetTStorage<uint16_t>(output, desc, formatInfo, loadDataIntoHalf);
- break;
- }
- case Format::R64_UINT:
- {
- generateTextureDataWithTargetTStorage<uint64_t>(output, desc, formatInfo, loadDataIntoUint<uint64_t>);
- break;
- }
- case Format::R32_FLOAT:
- case Format::R32G32_FLOAT:
- case Format::R32G32B32_FLOAT:
- case Format::R32G32B32A32_FLOAT:
- case Format::D32_FLOAT:
- {
- generateTextureDataWithTargetTStorage<float>(output, desc, formatInfo, loadDataIntoFloat);
- break;
- }
- case Format::R32_UINT:
- case Format::R32G32_UINT:
- case Format::R32G32B32_UINT:
- case Format::R32G32B32A32_UINT:
- {
- generateTextureDataWithTargetTStorage<uint32_t>(output, desc, formatInfo, loadDataIntoUint<uint32_t>);
- break;
- }
- case Format::R16_UINT:
- case Format::R16G16_UINT:
- case Format::R16G16B16A16_UINT:
- {
- generateTextureDataWithTargetTStorage<uint16_t>(output, desc, formatInfo, loadDataIntoUint<uint16_t>);
- break;
- }
- case Format::R8_UINT:
- case Format::R8G8_UINT:
- case Format::R8G8B8A8_UINT:
- {
- generateTextureDataWithTargetTStorage<uint8_t>(output, desc, formatInfo, loadDataIntoUint<uint8_t>);
- break;
- }
- case Format::R64_SINT:
- {
- generateTextureDataWithTargetTStorage<int64_t>(output, desc, formatInfo, loadDataIntoInt<int64_t>);
- break;
- }
- case Format::R32_SINT:
- case Format::R32G32_SINT:
- case Format::R32G32B32_SINT:
- case Format::R32G32B32A32_SINT:
- {
- generateTextureDataWithTargetTStorage<int32_t>(output, desc, formatInfo, loadDataIntoInt<int32_t>);
- break;
- }
- case Format::R16_SINT:
- case Format::R16G16_SINT:
- case Format::R16G16B16A16_SINT:
- {
- generateTextureDataWithTargetTStorage<int16_t>(output, desc, formatInfo, loadDataIntoInt<int16_t>);
- break;
- }
- case Format::R8_SINT:
- case Format::R8G8_SINT:
- case Format::R8G8B8A8_SINT:
- {
- generateTextureDataWithTargetTStorage<int8_t>(output, desc, formatInfo, loadDataIntoInt<int8_t>);
- break;
- }
- default:
- {
- SLANG_ASSERT(!"Unhandled format");
- break;
- }
+ generateTextureDataRGB8(output, desc);
+ break;
}
- }
-
- template <typename F>
- void _iteratePixels(int dimension, int size, unsigned int * buffer, F f)
- {
- if (dimension == 1)
- for (int i = 0; i < size; i++)
- buffer[i] = f(i, 0, 0);
- else if (dimension == 2)
- for (int i = 0; i < size; i++)
- for (int j = 0; j < size; j++)
- buffer[i*size + j] = f(j, i, 0);
- else if (dimension == 3)
- for (int i = 0; i < size; i++)
- for (int j = 0; j < size; j++)
- for (int k = 0; k < size; k++)
- buffer[i*size*size + j * size + k] = f(k, j, i);
- };
-
- void generateTextureDataRGB8(TextureData& output, const InputTextureDesc& inputDesc)
- {
- int arrLen = inputDesc.arrayLength;
- if (arrLen == 0)
- arrLen = 1;
-
- output.init(Format::R8G8B8A8_UNORM);
-
- enum class SimpleScalarType {
- kUint,
- kInt,
- kFloat,
- };
- SimpleScalarType type;
- const rhi::FormatInfo& formatInfo = getFormatInfo(inputDesc.format);
- switch (formatInfo.channelType)
- {
- case SLANG_SCALAR_TYPE_UINT64:
- case SLANG_SCALAR_TYPE_UINT32:
- case SLANG_SCALAR_TYPE_UINT16:
- case SLANG_SCALAR_TYPE_UINT8:
- type = SimpleScalarType::kUint;
+ case Format::R16_FLOAT:
+ case Format::R16G16_FLOAT:
+ case Format::R16G16B16A16_FLOAT:
+ {
+ generateTextureDataWithTargetTStorage<uint16_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoHalf);
break;
- case SLANG_SCALAR_TYPE_INT64:
- case SLANG_SCALAR_TYPE_INT32:
- case SLANG_SCALAR_TYPE_INT16:
- case SLANG_SCALAR_TYPE_INT8:
- type = SimpleScalarType::kInt;
+ }
+ case Format::R64_UINT:
+ {
+ generateTextureDataWithTargetTStorage<uint64_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoUint<uint64_t>);
break;
- case SLANG_SCALAR_TYPE_FLOAT64:
- case SLANG_SCALAR_TYPE_FLOAT32:
- case SLANG_SCALAR_TYPE_FLOAT16:
- type = SimpleScalarType::kFloat;
+ }
+ case Format::R32_FLOAT:
+ case Format::R32G32_FLOAT:
+ case Format::R32G32B32_FLOAT:
+ case Format::R32G32B32A32_FLOAT:
+ case Format::D32_FLOAT:
+ {
+ generateTextureDataWithTargetTStorage<float>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoFloat);
break;
- default:
- type = SimpleScalarType::kUint;
+ }
+ case Format::R32_UINT:
+ case Format::R32G32_UINT:
+ case Format::R32G32B32_UINT:
+ case Format::R32G32B32A32_UINT:
+ {
+ generateTextureDataWithTargetTStorage<uint32_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoUint<uint32_t>);
+ break;
+ }
+ case Format::R16_UINT:
+ case Format::R16G16_UINT:
+ case Format::R16G16B16A16_UINT:
+ {
+ generateTextureDataWithTargetTStorage<uint16_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoUint<uint16_t>);
+ break;
+ }
+ case Format::R8_UINT:
+ case Format::R8G8_UINT:
+ case Format::R8G8B8A8_UINT:
+ {
+ generateTextureDataWithTargetTStorage<uint8_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoUint<uint8_t>);
+ break;
+ }
+ case Format::R64_SINT:
+ {
+ generateTextureDataWithTargetTStorage<int64_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoInt<int64_t>);
break;
}
- //List<List<unsigned int>>& dataBuffer = output.dataBuffer;
- int arraySize = arrLen;
- if (inputDesc.isCube)
- arraySize *= 6;
- output.m_arraySize = arraySize;
- output.m_textureSize = inputDesc.size;
+ case Format::R32_SINT:
+ case Format::R32G32_SINT:
+ case Format::R32G32B32_SINT:
+ case Format::R32G32B32A32_SINT:
+ {
+ generateTextureDataWithTargetTStorage<int32_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoInt<int32_t>);
+ break;
+ }
+ case Format::R16_SINT:
+ case Format::R16G16_SINT:
+ case Format::R16G16B16A16_SINT:
+ {
+ generateTextureDataWithTargetTStorage<int16_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoInt<int16_t>);
+ break;
+ }
+ case Format::R8_SINT:
+ case Format::R8G8_SINT:
+ case Format::R8G8B8A8_SINT:
+ {
+ generateTextureDataWithTargetTStorage<int8_t>(
+ output,
+ desc,
+ formatInfo,
+ loadDataIntoInt<int8_t>);
+ break;
+ }
+ default:
+ {
+ SLANG_ASSERT(!"Unhandled format");
+ break;
+ }
+ }
+}
- const Index maxMipLevels = Math::Log2Floor(output.m_textureSize) + 1;
- Index mipLevels = (inputDesc.mipMapCount <= 0) ? maxMipLevels : inputDesc.mipMapCount;
- mipLevels = (mipLevels > maxMipLevels) ? maxMipLevels : mipLevels;
+template<typename F>
+void _iteratePixels(int dimension, int size, unsigned int* buffer, F f)
+{
+ if (dimension == 1)
+ for (int i = 0; i < size; i++)
+ buffer[i] = f(i, 0, 0);
+ else if (dimension == 2)
+ for (int i = 0; i < size; i++)
+ for (int j = 0; j < size; j++)
+ buffer[i * size + j] = f(j, i, 0);
+ else if (dimension == 3)
+ for (int i = 0; i < size; i++)
+ for (int j = 0; j < size; j++)
+ for (int k = 0; k < size; k++)
+ buffer[i * size * size + j * size + k] = f(k, j, i);
+};
+
+void generateTextureDataRGB8(TextureData& output, const InputTextureDesc& inputDesc)
+{
+ int arrLen = inputDesc.arrayLength;
+ if (arrLen == 0)
+ arrLen = 1;
- output.m_mipLevels = int(mipLevels);
- output.m_slices.setCount(output.m_mipLevels * output.m_arraySize);
+ output.init(Format::R8G8B8A8_UNORM);
- int slice = 0;
- for (int i = 0; i < arraySize; i++)
+ enum class SimpleScalarType
+ {
+ kUint,
+ kInt,
+ kFloat,
+ };
+ SimpleScalarType type;
+ const rhi::FormatInfo& formatInfo = getFormatInfo(inputDesc.format);
+ switch (formatInfo.channelType)
+ {
+ case SLANG_SCALAR_TYPE_UINT64:
+ case SLANG_SCALAR_TYPE_UINT32:
+ case SLANG_SCALAR_TYPE_UINT16:
+ case SLANG_SCALAR_TYPE_UINT8: type = SimpleScalarType::kUint; break;
+ case SLANG_SCALAR_TYPE_INT64:
+ case SLANG_SCALAR_TYPE_INT32:
+ case SLANG_SCALAR_TYPE_INT16:
+ case SLANG_SCALAR_TYPE_INT8: type = SimpleScalarType::kInt; break;
+ case SLANG_SCALAR_TYPE_FLOAT64:
+ case SLANG_SCALAR_TYPE_FLOAT32:
+ case SLANG_SCALAR_TYPE_FLOAT16: type = SimpleScalarType::kFloat; break;
+ default: type = SimpleScalarType::kUint; break;
+ }
+ // List<List<unsigned int>>& dataBuffer = output.dataBuffer;
+ int arraySize = arrLen;
+ if (inputDesc.isCube)
+ arraySize *= 6;
+ output.m_arraySize = arraySize;
+ output.m_textureSize = inputDesc.size;
+
+ const Index maxMipLevels = Math::Log2Floor(output.m_textureSize) + 1;
+ Index mipLevels = (inputDesc.mipMapCount <= 0) ? maxMipLevels : inputDesc.mipMapCount;
+ mipLevels = (mipLevels > maxMipLevels) ? maxMipLevels : mipLevels;
+
+ output.m_mipLevels = int(mipLevels);
+ output.m_slices.setCount(output.m_mipLevels * output.m_arraySize);
+
+ int slice = 0;
+ for (int i = 0; i < arraySize; i++)
+ {
+ for (int j = 0; j < output.m_mipLevels; j++)
{
- for (int j = 0; j < output.m_mipLevels; j++)
- {
- int size = output.m_textureSize >> j;
- int bufferLen = size;
- if (inputDesc.dimension == 2)
- bufferLen *= size;
- else if (inputDesc.dimension == 3)
- bufferLen *= size*size;
-
- uint32_t* dst = (uint32_t*)output.setSliceCount(slice, bufferLen);
-
- if (type == SimpleScalarType::kFloat)
- _iteratePixels(inputDesc.dimension, size, dst, [&](int x, int y, int z) -> unsigned int
+ int size = output.m_textureSize >> j;
+ int bufferLen = size;
+ if (inputDesc.dimension == 2)
+ bufferLen *= size;
+ else if (inputDesc.dimension == 3)
+ bufferLen *= size * size;
+
+ uint32_t* dst = (uint32_t*)output.setSliceCount(slice, bufferLen);
+
+ if (type == SimpleScalarType::kFloat)
+ _iteratePixels(
+ inputDesc.dimension,
+ size,
+ dst,
+ [&](int x, int y, int z) -> unsigned int
+ {
+ if (inputDesc.content == InputTextureContent::Zero)
{
- if (inputDesc.content == InputTextureContent::Zero)
- {
- return 0x0;
- }
- else if (inputDesc.content == InputTextureContent::One)
- {
+ return 0x0;
+ }
+ else if (inputDesc.content == InputTextureContent::One)
+ {
+ return 0xFFFFFFFF;
+ }
+ else if (inputDesc.content == InputTextureContent::Gradient)
+ {
+ unsigned char r = (unsigned char)(x / (float)(size - 1) * 255.0f);
+ unsigned char g = (unsigned char)(y / (float)(size - 1) * 255.0f);
+ unsigned char b = (unsigned char)(z / (float)(size - 1) * 255.0f);
+ return 0xFF000000 + r + (g << 8) + (b << 16);
+ }
+ else if (inputDesc.content == InputTextureContent::ChessBoard)
+ {
+ unsigned int xSig = x < (size >> 1) ? 1 : 0;
+ unsigned int ySig = y < (size >> 1) ? 1 : 0;
+ unsigned int zSig = z < (size >> 1) ? 1 : 0;
+ auto sig = xSig ^ ySig ^ zSig;
+ if (sig)
return 0xFFFFFFFF;
- }
- else if (inputDesc.content == InputTextureContent::Gradient)
- {
- unsigned char r = (unsigned char)(x / (float)(size - 1) * 255.0f);
- unsigned char g = (unsigned char)(y / (float)(size - 1) * 255.0f);
- unsigned char b = (unsigned char)(z / (float)(size - 1) * 255.0f);
- return 0xFF000000 + r + (g << 8) + (b << 16);
- }
- else if (inputDesc.content == InputTextureContent::ChessBoard)
- {
- unsigned int xSig = x < (size >> 1) ? 1 : 0;
- unsigned int ySig = y < (size >> 1) ? 1 : 0;
- unsigned int zSig = z < (size >> 1) ? 1 : 0;
- auto sig = xSig ^ ySig ^ zSig;
- if (sig)
- return 0xFFFFFFFF;
- else
- return 0xFF808080;
- }
+ else
+ return 0xFF808080;
+ }
+ return 0x0;
+ });
+ else if (type == SimpleScalarType::kUint || type == SimpleScalarType::kInt)
+ _iteratePixels(
+ inputDesc.dimension,
+ size,
+ dst,
+ [&](int x, int y, int z) -> unsigned int
+ {
+ if (inputDesc.content == InputTextureContent::Zero)
+ {
return 0x0;
- });
- else if (type == SimpleScalarType::kUint || type == SimpleScalarType::kInt)
- _iteratePixels(inputDesc.dimension, size, dst, [&](int x, int y, int z) -> unsigned int
+ }
+ else if (inputDesc.content == InputTextureContent::One)
{
- if (inputDesc.content == InputTextureContent::Zero)
- {
- return 0x0;
- }
- else if (inputDesc.content == InputTextureContent::One)
- {
+ return 0x01010101;
+ }
+ else if (inputDesc.content == InputTextureContent::Gradient)
+ {
+ unsigned char r = (unsigned char)(x / (float)(size - 1));
+ unsigned char g = (unsigned char)(y / (float)(size - 1));
+ unsigned char b = (unsigned char)(z / (float)(size - 1));
+ return 0x01000000 + r + (g << 8) + (b << 16);
+ }
+ else if (inputDesc.content == InputTextureContent::ChessBoard)
+ {
+ unsigned int xSig = x < (size >> 1) ? 1 : 0;
+ unsigned int ySig = y < (size >> 1) ? 1 : 0;
+ unsigned int zSig = z < (size >> 1) ? 1 : 0;
+ auto sig = xSig ^ ySig ^ zSig;
+ if (sig)
return 0x01010101;
- }
- else if (inputDesc.content == InputTextureContent::Gradient)
- {
- unsigned char r = (unsigned char)(x / (float)(size - 1));
- unsigned char g = (unsigned char)(y / (float)(size - 1));
- unsigned char b = (unsigned char)(z / (float)(size - 1));
- return 0x01000000 + r + (g << 8) + (b << 16);
- }
- else if (inputDesc.content == InputTextureContent::ChessBoard)
- {
- unsigned int xSig = x < (size >> 1) ? 1 : 0;
- unsigned int ySig = y < (size >> 1) ? 1 : 0;
- unsigned int zSig = z < (size >> 1) ? 1 : 0;
- auto sig = xSig ^ ySig ^ zSig;
- if (sig)
- return 0x01010101;
- else
- return 0x0;
- }
- return 0x0;
- });
- slice++;
- }
+ else
+ return 0x0;
+ }
+ return 0x0;
+ });
+ slice++;
}
}
}
+} // namespace renderer_test
diff --git a/tools/render-test/shader-input-layout.h b/tools/render-test/shader-input-layout.h
index 9d4b139c8..032e6019d 100644
--- a/tools/render-test/shader-input-layout.h
+++ b/tools/render-test/shader-input-layout.h
@@ -3,12 +3,12 @@
#include "source/core/slang-basic.h"
#include "source/core/slang-random-generator.h"
-
#include "source/core/slang-writer.h"
#include <slang-rhi.h>
-namespace renderer_test {
+namespace renderer_test
+{
using namespace rhi;
@@ -28,7 +28,10 @@ enum class ShaderInputType
enum class InputTextureContent
{
- Zero, One, ChessBoard, Gradient
+ Zero,
+ One,
+ ChessBoard,
+ Gradient
};
enum InputTextureSampleCount
@@ -49,19 +52,19 @@ struct InputTextureDesc
bool isDepthTexture = false;
bool isRWTexture = false;
int size = 4;
- int mipMapCount = 0; ///< 0 means the maximum number of mips will be bound
+ int mipMapCount = 0; ///< 0 means the maximum number of mips will be bound
InputTextureSampleCount sampleCount = InputTextureSampleCount::One;
- Format format = Format::R8G8B8A8_UNORM;
+ Format format = Format::R8G8B8A8_UNORM;
InputTextureContent content = InputTextureContent::One;
};
enum class InputBufferType
{
-// ConstantBuffer,
+ // ConstantBuffer,
StorageBuffer,
-// RootConstantBuffer,
+ // RootConstantBuffer,
};
struct InputBufferDesc
@@ -93,7 +96,7 @@ struct TextureData
return slice;
}
- void* values = nullptr; ///< Values of the type format
+ void* values = nullptr; ///< Values of the type format
size_t valuesCount = 0;
};
@@ -111,7 +114,7 @@ struct TextureData
return dst;
}
- /// Set the size of the slice in count of format sized elements
+ /// Set the size of the slice in count of format sized elements
void* setSliceCount(Slang::Index sliceIndex, size_t count)
{
auto& slice = m_slices[sliceIndex];
@@ -163,7 +166,8 @@ public:
public:
Val(ShaderInputType kind)
: kind(kind)
- {}
+ {
+ }
ShaderInputType kind;
bool isOutput = false;
@@ -175,7 +179,8 @@ public:
public:
TextureVal()
: Val(ShaderInputType::Texture)
- {}
+ {
+ }
InputTextureDesc textureDesc;
};
@@ -185,7 +190,8 @@ public:
public:
DataValBase(ShaderInputType kind)
: Val(kind)
- {}
+ {
+ }
Slang::List<unsigned int> bufferData;
};
@@ -195,7 +201,8 @@ public:
public:
BufferVal()
: DataValBase(ShaderInputType::Buffer)
- {}
+ {
+ }
InputBufferDesc bufferDesc;
};
@@ -205,7 +212,8 @@ public:
public:
DataVal()
: DataValBase(ShaderInputType::UniformData)
- {}
+ {
+ }
};
class SamplerVal : public Val
@@ -213,7 +221,8 @@ public:
public:
SamplerVal()
: Val(ShaderInputType::Sampler)
- {}
+ {
+ }
InputSamplerDesc samplerDesc;
};
@@ -223,7 +232,8 @@ public:
public:
CombinedTextureSamplerVal()
: Val(ShaderInputType::CombinedTextureSampler)
- {}
+ {
+ }
Slang::RefPtr<TextureVal> textureVal;
Slang::RefPtr<SamplerVal> samplerVal;
@@ -234,13 +244,14 @@ public:
public:
AccelerationStructureVal()
: Val(ShaderInputType::AccelerationStructure)
- {}
+ {
+ }
};
struct Field
{
- Slang::String name;
- ValPtr val;
+ Slang::String name;
+ ValPtr val;
};
typedef Field Entry;
@@ -249,7 +260,8 @@ public:
public:
ParentVal(ShaderInputType kind)
: Val(kind)
- {}
+ {
+ }
virtual void addField(Field const& field) = 0;
};
@@ -259,7 +271,8 @@ public:
public:
AggVal(ShaderInputType kind = ShaderInputType::Aggregate)
: ParentVal(kind)
- {}
+ {
+ }
Slang::List<Field> fields;
@@ -271,7 +284,8 @@ public:
public:
ObjectVal()
: Val(ShaderInputType::Object)
- {}
+ {
+ }
Slang::String typeName;
ValPtr contentVal;
@@ -284,7 +298,8 @@ public:
Slang::List<Slang::String> typeArgs;
SpecializeVal()
: Val(ShaderInputType::Specialize)
- {}
+ {
+ }
};
class ArrayVal : public ParentVal
@@ -292,7 +307,8 @@ public:
public:
ArrayVal()
: ParentVal(ShaderInputType::Array)
- {}
+ {
+ }
Slang::List<ValPtr> vals;
@@ -318,14 +334,19 @@ public:
void parse(Slang::RandomGenerator* rand, const char* source);
- /// Writes a binding, if bindRoot is set, will try to honor the underlying type when outputting. If not will dump as uint32_t hex.
- static SlangResult writeBinding(slang::TypeLayoutReflection* typeLayout, const void* data, size_t sizeInBytes, Slang::WriterHelper writer);
+ /// Writes a binding, if bindRoot is set, will try to honor the underlying type when outputting.
+ /// If not will dump as uint32_t hex.
+ static SlangResult writeBinding(
+ slang::TypeLayoutReflection* typeLayout,
+ const void* data,
+ size_t sizeInBytes,
+ Slang::WriterHelper writer);
};
void generateTextureDataRGB8(TextureData& output, const InputTextureDesc& desc);
void generateTextureData(TextureData& output, const InputTextureDesc& desc);
-} // namespace render_test
+} // namespace renderer_test
#endif
diff --git a/tools/render-test/shader-renderer-util.cpp b/tools/render-test/shader-renderer-util.cpp
index 19bbbd2a5..37e5e9e2a 100644
--- a/tools/render-test/shader-renderer-util.cpp
+++ b/tools/render-test/shader-renderer-util.cpp
@@ -2,7 +2,8 @@
#include "shader-renderer-util.h"
-namespace renderer_test {
+namespace renderer_test
+{
using namespace Slang;
using Slang::Result;
@@ -27,17 +28,14 @@ inline int calcMaxDimension(Extents size, TextureType type)
{
switch (type)
{
- case TextureType::Texture1D:
- return size.width;
- case TextureType::Texture3D:
- return Math::Max(Math::Max(size.width, size.height), size.depth);
+ case TextureType::Texture1D: return size.width;
+ case TextureType::Texture3D: return Math::Max(Math::Max(size.width, size.height), size.depth);
case TextureType::TextureCube: // fallthru
case TextureType::Texture2D:
{
return Math::Max(size.width, size.height);
}
- default:
- return 0;
+ default: return 0;
}
}
@@ -69,7 +67,8 @@ inline int calcNumMipLevels(TextureType type, Extents size)
TextureDesc textureDesc = {};
// Default to R8G8B8A8_UNORM
- const Format format = (inputDesc.format == Format::Unknown) ? Format::R8G8B8A8_UNORM : inputDesc.format;
+ const Format format =
+ (inputDesc.format == Format::Unknown) ? Format::R8G8B8A8_UNORM : inputDesc.format;
textureDesc.sampleCount = inputDesc.sampleCount;
textureDesc.format = format;
@@ -78,21 +77,16 @@ inline int calcNumMipLevels(TextureType type, Extents size)
textureDesc.usage = TextureUsage::CopyDestination | TextureUsage::CopySource;
switch (defaultState)
{
- case ResourceState::ShaderResource:
- textureDesc.usage |= TextureUsage::ShaderResource;
- break;
- case ResourceState::UnorderedAccess:
- textureDesc.usage |= TextureUsage::UnorderedAccess;
- break;
- default:
- return SLANG_FAIL;
+ case ResourceState::ShaderResource: textureDesc.usage |= TextureUsage::ShaderResource; break;
+ case ResourceState::UnorderedAccess: textureDesc.usage |= TextureUsage::UnorderedAccess; break;
+ default: return SLANG_FAIL;
}
textureDesc.defaultState = defaultState;
// It's the same size in all dimensions
switch (inputDesc.dimension)
{
- case 1:
+ case 1:
{
textureDesc.type = TextureType::Texture1D;
textureDesc.size.width = inputDesc.size;
@@ -101,7 +95,7 @@ inline int calcNumMipLevels(TextureType type, Extents size)
break;
}
- case 2:
+ case 2:
{
textureDesc.type = inputDesc.isCube ? TextureType::TextureCube : TextureType::Texture2D;
textureDesc.size.width = inputDesc.size;
@@ -109,7 +103,7 @@ inline int calcNumMipLevels(TextureType type, Extents size)
textureDesc.size.depth = 1;
break;
}
- case 3:
+ case 3:
{
textureDesc.type = TextureType::Texture3D;
textureDesc.size.width = inputDesc.size;
@@ -125,11 +119,12 @@ inline int calcNumMipLevels(TextureType type, Extents size)
}
List<SubresourceData> initSubresources;
- int arrayLayerCount = textureDesc.arrayLength * (textureDesc.type == TextureType::TextureCube ? 6 : 1);
+ int arrayLayerCount =
+ textureDesc.arrayLength * (textureDesc.type == TextureType::TextureCube ? 6 : 1);
int subResourceCounter = 0;
- for( int a = 0; a < arrayLayerCount; ++a )
+ for (int a = 0; a < arrayLayerCount; ++a)
{
- for( int m = 0; m < textureDesc.mipLevelCount; ++m )
+ for (int m = 0; m < textureDesc.mipLevelCount; ++m)
{
int subResourceIndex = subResourceCounter++;
const int mipWidth = calcMipSize(textureDesc.size.width, m);
@@ -163,7 +158,8 @@ inline int calcNumMipLevels(TextureType type, Extents size)
bufferDesc.size = bufferSize;
bufferDesc.format = inputDesc.format;
bufferDesc.elementSize = inputDesc.stride;
- bufferDesc.usage = BufferUsage::CopyDestination | BufferUsage::CopySource | BufferUsage::ShaderResource | BufferUsage::UnorderedAccess;
+ bufferDesc.usage = BufferUsage::CopyDestination | BufferUsage::CopySource |
+ BufferUsage::ShaderResource | BufferUsage::UnorderedAccess;
bufferDesc.defaultState = ResourceState::UnorderedAccess;
ComPtr<IBuffer> bufferResource = device->createBuffer(bufferDesc, initData);
@@ -187,10 +183,9 @@ static SamplerDesc _calcSamplerDesc(const InputSamplerDesc& srcDesc)
return samplerDesc;
}
-ComPtr<ISampler> _createSampler(IDevice* device,
- const InputSamplerDesc& srcDesc)
+ComPtr<ISampler> _createSampler(IDevice* device, const InputSamplerDesc& srcDesc)
{
return device->createSampler(_calcSamplerDesc(srcDesc));
}
-} // renderer_test
+} // namespace renderer_test
diff --git a/tools/render-test/shader-renderer-util.h b/tools/render-test/shader-renderer-util.h
index 8d0075f3f..bf0569988 100644
--- a/tools/render-test/shader-renderer-util.h
+++ b/tools/render-test/shader-renderer-util.h
@@ -1,26 +1,30 @@
// shader-renderer-util.h
#pragma once
-#include <slang-rhi.h>
#include "shader-input-layout.h"
-namespace renderer_test {
+#include <slang-rhi.h>
+
+namespace renderer_test
+{
using namespace Slang;
ComPtr<ISampler> _createSampler(IDevice* device, const InputSamplerDesc& srcDesc);
-/// Utility class containing functions that construct items on the renderer using the ShaderInputLayout representation
+/// Utility class containing functions that construct items on the renderer using the
+/// ShaderInputLayout representation
struct ShaderRendererUtil
{
- /// Generate a texture using the InputTextureDesc and construct a Texture using the Renderer with the contents
+ /// Generate a texture using the InputTextureDesc and construct a Texture using the Renderer
+ /// with the contents
static Slang::Result generateTexture(
const InputTextureDesc& inputDesc,
ResourceState defaultState,
IDevice* device,
ComPtr<ITexture>& textureOut);
- /// Create texture resource using inputDesc, and texData to describe format, and contents
+ /// Create texture resource using inputDesc, and texData to describe format, and contents
static Slang::Result createTexture(
const InputTextureDesc& inputDesc,
const TextureData& texData,
@@ -28,7 +32,7 @@ struct ShaderRendererUtil
IDevice* device,
ComPtr<ITexture>& textureOut);
- /// Create the BufferResource using the renderer from the contents of inputDesc
+ /// Create the BufferResource using the renderer from the contents of inputDesc
static Slang::Result createBuffer(
const InputBufferDesc& inputDesc,
size_t bufferSize,
@@ -37,4 +41,4 @@ struct ShaderRendererUtil
ComPtr<IBuffer>& bufferOut);
};
-} // renderer_test
+} // namespace renderer_test
diff --git a/tools/render-test/slang-support.cpp b/tools/render-test/slang-support.cpp
index 97f163261..924a19104 100644
--- a/tools/render-test/slang-support.cpp
+++ b/tools/render-test/slang-support.cpp
@@ -4,15 +4,15 @@
#include "slang-support.h"
+#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-test-tool-util.h"
#include "options.h"
#include <assert.h>
#include <stdio.h>
-#include "../../source/core/slang-string-util.h"
-#include "../../source/core/slang-test-tool-util.h"
-
-namespace renderer_test {
+namespace renderer_test
+{
using namespace Slang;
// Entry point name to use for vertex/fragment shader
@@ -23,8 +23,7 @@ static const char rtEntryPointName[] = "raygenMain";
static const char taskEntryPointName[] = "taskMain";
static const char meshEntryPointName[] = "meshMain";
-void ShaderCompilerUtil::Output::set(
- slang::IComponentType* inSlangProgram)
+void ShaderCompilerUtil::Output::set(slang::IComponentType* inSlangProgram)
{
slangProgram = inSlangProgram;
desc.slangGlobalScope = inSlangProgram;
@@ -41,7 +40,12 @@ void ShaderCompilerUtil::Output::reset()
m_extraRequestForReflection = nullptr;
}
-/* static */ SlangResult ShaderCompilerUtil::_compileProgramImpl(slang::IGlobalSession* globalSession, const Options& options, const Input& input, const ShaderCompileRequest& request, Output& out)
+/* static */ SlangResult ShaderCompilerUtil::_compileProgramImpl(
+ slang::IGlobalSession* globalSession,
+ const Options& options,
+ const Input& input,
+ const ShaderCompileRequest& request,
+ Output& out)
{
out.reset();
@@ -72,7 +76,8 @@ void ShaderCompilerUtil::Output::reset()
// If there are additional args parse them
if (args.getCount())
{
- const auto res = slangRequest->processCommandLineArguments(args.getBuffer(), int(args.getCount()));
+ const auto res =
+ slangRequest->processCommandLineArguments(args.getBuffer(), int(args.getCount()));
// If there is a parse failure and diagnostic, output it
if (SLANG_FAILED(res))
{
@@ -89,8 +94,11 @@ void ShaderCompilerUtil::Output::reset()
if (!hasRepro)
{
spSetCodeGenTarget(slangRequest, input.target);
- if(input.profile.getLength()) // do not set profile unless requested
- spSetTargetProfile(slangRequest, 0, spFindProfile(out.session, input.profile.getBuffer()));
+ if (input.profile.getLength()) // do not set profile unless requested
+ spSetTargetProfile(
+ slangRequest,
+ 0,
+ spFindProfile(out.session, input.profile.getBuffer()));
if (options.generateSPIRVDirectly)
spSetTargetFlags(slangRequest, 0, SLANG_TARGET_FLAG_GENERATE_SPIRV_DIRECTLY);
else
@@ -113,9 +121,7 @@ void ShaderCompilerUtil::Output::reset()
case SLANG_SOURCE_LANGUAGE_HLSL:
spAddPreprocessorDefine(slangRequest, "__HLSL__", "1");
break;
- case SLANG_SOURCE_LANGUAGE_C:
- spAddPreprocessorDefine(slangRequest, "__C__", "1");
- break;
+ case SLANG_SOURCE_LANGUAGE_C: spAddPreprocessorDefine(slangRequest, "__C__", "1"); break;
case SLANG_SOURCE_LANGUAGE_CPP:
spAddPreprocessorDefine(slangRequest, "__CPP__", "1");
break;
@@ -126,9 +132,7 @@ void ShaderCompilerUtil::Output::reset()
spAddPreprocessorDefine(slangRequest, "__WGSL__", "1");
break;
- default:
- assert(!"unexpected");
- break;
+ default: assert(!"unexpected"); break;
}
if (input.passThrough != SLANG_PASS_THROUGH_NONE)
@@ -146,23 +150,35 @@ void ShaderCompilerUtil::Output::reset()
int translationUnitIndex = 0;
{
translationUnitIndex = spAddTranslationUnit(slangRequest, sourceLanguage, nullptr);
- spAddTranslationUnitSourceString(slangRequest, translationUnitIndex, request.source.path, request.source.dataBegin);
+ spAddTranslationUnitSourceString(
+ slangRequest,
+ translationUnitIndex,
+ request.source.path,
+ request.source.dataBegin);
}
const int globalSpecializationArgCount = int(request.globalSpecializationArgs.getCount());
for (int ii = 0; ii < globalSpecializationArgCount; ++ii)
{
- spSetTypeNameForGlobalExistentialTypeParam(slangRequest, ii, request.globalSpecializationArgs[ii].getBuffer());
+ spSetTypeNameForGlobalExistentialTypeParam(
+ slangRequest,
+ ii,
+ request.globalSpecializationArgs[ii].getBuffer());
}
- const int entryPointSpecializationArgCount = int(request.entryPointSpecializationArgs.getCount());
+ const int entryPointSpecializationArgCount =
+ int(request.entryPointSpecializationArgs.getCount());
auto setEntryPointSpecializationArgs = [&](int entryPoint)
+ {
+ for (int ii = 0; ii < entryPointSpecializationArgCount; ++ii)
{
- for (int ii = 0; ii < entryPointSpecializationArgCount; ++ii)
- {
- spSetTypeNameForEntryPointExistentialTypeParam(slangRequest, entryPoint, ii, request.entryPointSpecializationArgs[ii].getBuffer());
- }
- };
+ spSetTypeNameForEntryPointExistentialTypeParam(
+ slangRequest,
+ entryPoint,
+ ii,
+ request.entryPointSpecializationArgs[ii].getBuffer());
+ }
+ };
Index explicitEntryPointCount = request.entryPoints.getCount();
for (Index ee = 0; ee < explicitEntryPointCount; ++ee)
@@ -210,7 +226,7 @@ void ShaderCompilerUtil::Output::reset()
ComPtr<slang::IComponentType> linkedSlangProgram;
List<ShaderCompileRequest::EntryPoint> actualEntryPoints;
- if(input.passThrough == SLANG_PASS_THROUGH_NONE)
+ if (input.passThrough == SLANG_PASS_THROUGH_NONE)
{
// In the case where pass-through compilation is not being used,
// we can use the Slang reflection information to discover what
@@ -218,7 +234,9 @@ void ShaderCompilerUtil::Output::reset()
// loading of code.
//
auto reflection = slang::ProgramLayout::get(slangRequest);
- SLANG_RETURN_ON_FAIL(spCompileRequest_getProgramWithEntryPoints(slangRequest, linkedSlangProgram.writeRef()));
+ SLANG_RETURN_ON_FAIL(spCompileRequest_getProgramWithEntryPoints(
+ slangRequest,
+ linkedSlangProgram.writeRef()));
// Get the amount of entry points in reflection
Index entryPointCount = Index(reflection->getEntryPointCount());
@@ -226,7 +244,7 @@ void ShaderCompilerUtil::Output::reset()
// We must have at least one entry point (whether explicit or implicit)
SLANG_ASSERT(entryPointCount);
- for(Index ee = 0; ee < entryPointCount; ++ee)
+ for (Index ee = 0; ee < entryPointCount; ++ee)
{
auto entryPoint = reflection->getEntryPointByIndex(ee);
const char* entryPointName = entryPoint->getName();
@@ -281,9 +299,14 @@ void ShaderCompilerUtil::Output::reset()
return SLANG_OK;
}
-/* static */ SlangResult ShaderCompilerUtil::compileProgram(slang::IGlobalSession* globalSession, const Options& options, const Input& input, const ShaderCompileRequest& request, Output& out)
+/* static */ SlangResult ShaderCompilerUtil::compileProgram(
+ slang::IGlobalSession* globalSession,
+ const Options& options,
+ const Input& input,
+ const ShaderCompileRequest& request,
+ Output& out)
{
- if( input.passThrough == SLANG_PASS_THROUGH_NONE )
+ if (input.passThrough == SLANG_PASS_THROUGH_NONE)
{
return _compileProgramImpl(globalSession, options, input, request, out);
}
@@ -293,11 +316,8 @@ void ShaderCompilerUtil::Output::reset()
switch (input.passThrough)
{
case SLANG_PASS_THROUGH_DXC:
- case SLANG_PASS_THROUGH_FXC:
- canUseSlangForPrecompile = true;
- break;
- default:
- break;
+ case SLANG_PASS_THROUGH_FXC: canUseSlangForPrecompile = true; break;
+ default: break;
}
// If we are doing a HLSL pass-through compilation, then we can't rely
// on the downstream compiler for the reflection information that
@@ -315,7 +335,8 @@ void ShaderCompilerUtil::Output::reset()
// TODO: we want to pass along a flag to skip codegen...
- SLANG_RETURN_ON_FAIL(_compileProgramImpl(globalSession, options, slangInput, request, slangOutput));
+ SLANG_RETURN_ON_FAIL(
+ _compileProgramImpl(globalSession, options, slangInput, request, slangOutput));
}
// Now we have what we need to be able to do the downstream compile better.
@@ -334,7 +355,9 @@ void ShaderCompilerUtil::Output::reset()
}
}
-/* static */SlangResult ShaderCompilerUtil::readSource(const String& inSourcePath, List<char>& outSourceText)
+/* static */ SlangResult ShaderCompilerUtil::readSource(
+ const String& inSourcePath,
+ List<char>& outSourceText)
{
// Read in the source code
FILE* sourceFile = fopen(inSourcePath.getBuffer(), "rb");
@@ -348,7 +371,7 @@ void ShaderCompilerUtil::Output::reset()
fseek(sourceFile, 0, SEEK_SET);
outSourceText.setCount(sourceSize + 1);
- if(fread(outSourceText.getBuffer(), sourceSize, 1, sourceFile) != 1)
+ if (fread(outSourceText.getBuffer(), sourceSize, 1, sourceFile) != 1)
{
fprintf(stderr, "error: failed to read from '%s'\n", inSourcePath.getBuffer());
return SLANG_FAIL;
@@ -359,7 +382,7 @@ void ShaderCompilerUtil::Output::reset()
return SLANG_OK;
}
-/* static */SlangResult ShaderCompilerUtil::compileWithLayout(
+/* static */ SlangResult ShaderCompilerUtil::compileWithLayout(
slang::IGlobalSession* globalSession,
const Options& options,
const ShaderCompilerUtil::Input& input,
@@ -371,7 +394,8 @@ void ShaderCompilerUtil::Output::reset()
List<char> sourceText;
SLANG_RETURN_ON_FAIL(readSource(sourcePath, sourceText));
- if (input.sourceLanguage == SLANG_SOURCE_LANGUAGE_CPP || input.sourceLanguage == SLANG_SOURCE_LANGUAGE_C)
+ if (input.sourceLanguage == SLANG_SOURCE_LANGUAGE_CPP ||
+ input.sourceLanguage == SLANG_SOURCE_LANGUAGE_C)
{
// Add an include of the prelude
ComPtr<ISlangBlob> prelude;
@@ -379,7 +403,7 @@ void ShaderCompilerUtil::Output::reset()
String preludeString = StringUtil::getString(prelude);
- // Add the prelude
+ // Add the prelude
StringBuilder builder;
builder << preludeString << "\n";
builder << UnownedStringSlice(sourceText.getBuffer(), sourceText.getCount());
@@ -395,14 +419,10 @@ void ShaderCompilerUtil::Output::reset()
// Default the amount of renderTargets based on shader type
switch (shaderType)
{
- default:
- layout.numRenderTargets = 1;
- break;
+ default: layout.numRenderTargets = 1; break;
- case Options::ShaderProgramType::Compute:
- case Options::ShaderProgramType::RayTracing:
- layout.numRenderTargets = 0;
- break;
+ case Options::ShaderProgramType::Compute:
+ case Options::ShaderProgramType::RayTracing: layout.numRenderTargets = 0; break;
}
// Deterministic random generator
@@ -429,65 +449,65 @@ void ShaderCompilerUtil::Output::reset()
// mechanisms for discovering entry points (e.g., `[shader(...)]`
// attributes).
//
- if( !options.dontAddDefaultEntryPoints )
+ if (!options.dontAddDefaultEntryPoints)
{
- switch(shaderType)
+ switch (shaderType)
{
case Options::ShaderProgramType::Graphics:
case Options::ShaderProgramType::GraphicsCompute:
- {
- ShaderCompileRequest::EntryPoint vertexEntryPoint;
- vertexEntryPoint.name = vertexEntryPointName;
- vertexEntryPoint.slangStage = SLANG_STAGE_VERTEX;
- compileRequest.entryPoints.add(vertexEntryPoint);
-
- ShaderCompileRequest::EntryPoint fragmentEntryPoint;
- fragmentEntryPoint.name = fragmentEntryPointName;
- fragmentEntryPoint.slangStage = SLANG_STAGE_FRAGMENT;
- compileRequest.entryPoints.add(fragmentEntryPoint);
- }
- break;
+ {
+ ShaderCompileRequest::EntryPoint vertexEntryPoint;
+ vertexEntryPoint.name = vertexEntryPointName;
+ vertexEntryPoint.slangStage = SLANG_STAGE_VERTEX;
+ compileRequest.entryPoints.add(vertexEntryPoint);
+
+ ShaderCompileRequest::EntryPoint fragmentEntryPoint;
+ fragmentEntryPoint.name = fragmentEntryPointName;
+ fragmentEntryPoint.slangStage = SLANG_STAGE_FRAGMENT;
+ compileRequest.entryPoints.add(fragmentEntryPoint);
+ }
+ break;
case Options::ShaderProgramType::GraphicsTaskMeshCompute:
- {
- ShaderCompileRequest::EntryPoint taskEntryPoint;
- taskEntryPoint.name = taskEntryPointName;
- taskEntryPoint.slangStage = SLANG_STAGE_AMPLIFICATION;
- compileRequest.entryPoints.add(taskEntryPoint);
- }
- [[fallthrough]];
+ {
+ ShaderCompileRequest::EntryPoint taskEntryPoint;
+ taskEntryPoint.name = taskEntryPointName;
+ taskEntryPoint.slangStage = SLANG_STAGE_AMPLIFICATION;
+ compileRequest.entryPoints.add(taskEntryPoint);
+ }
+ [[fallthrough]];
case Options::ShaderProgramType::GraphicsMeshCompute:
- {
- ShaderCompileRequest::EntryPoint meshEntryPoint;
- meshEntryPoint.name = meshEntryPointName;
- meshEntryPoint.slangStage = SLANG_STAGE_MESH;
- compileRequest.entryPoints.add(meshEntryPoint);
-
- ShaderCompileRequest::EntryPoint fragmentEntryPoint;
- fragmentEntryPoint.name = fragmentEntryPointName;
- fragmentEntryPoint.slangStage = SLANG_STAGE_FRAGMENT;
- compileRequest.entryPoints.add(fragmentEntryPoint);
- }
- break;
+ {
+ ShaderCompileRequest::EntryPoint meshEntryPoint;
+ meshEntryPoint.name = meshEntryPointName;
+ meshEntryPoint.slangStage = SLANG_STAGE_MESH;
+ compileRequest.entryPoints.add(meshEntryPoint);
+
+ ShaderCompileRequest::EntryPoint fragmentEntryPoint;
+ fragmentEntryPoint.name = fragmentEntryPointName;
+ fragmentEntryPoint.slangStage = SLANG_STAGE_FRAGMENT;
+ compileRequest.entryPoints.add(fragmentEntryPoint);
+ }
+ break;
case Options::ShaderProgramType::RayTracing:
- {
- // Note: Current GPU ray tracing pipelines allow for an
- // almost arbitrary mix of entry points for different stages
- // to be used together (e.g., a single "program" might
- // have multiple any-hit shaders, multiple miss shaders, etc.)
- //
- // Rather than try to define a fixed set of entry point
- // names and stages that the testing will support, we will
- // instead rely on `[shader(...)]` annotations to tell us
- // what entry points are present in the input code.
- }
- break;
+ {
+ // Note: Current GPU ray tracing pipelines allow for an
+ // almost arbitrary mix of entry points for different stages
+ // to be used together (e.g., a single "program" might
+ // have multiple any-hit shaders, multiple miss shaders, etc.)
+ //
+ // Rather than try to define a fixed set of entry point
+ // names and stages that the testing will support, we will
+ // instead rely on `[shader(...)]` annotations to tell us
+ // what entry points are present in the input code.
+ }
+ break;
default:
- {
- ShaderCompileRequest::EntryPoint computeEntryPoint;
- computeEntryPoint.name = computeEntryPointName;
- computeEntryPoint.slangStage = SLANG_STAGE_COMPUTE;
- compileRequest.entryPoints.add(computeEntryPoint);
- }
+ {
+ ShaderCompileRequest::EntryPoint computeEntryPoint;
+ computeEntryPoint.name = computeEntryPointName;
+ computeEntryPoint.slangStage = SLANG_STAGE_COMPUTE;
+ compileRequest.entryPoints.add(computeEntryPoint);
+ }
}
}
compileRequest.globalSpecializationArgs = layout.globalSpecializationArgs;
@@ -500,7 +520,12 @@ void ShaderCompilerUtil::Output::reset()
c.idOverride = conformance.idOverride;
compileRequest.typeConformances.add(c);
}
- return ShaderCompilerUtil::compileProgram(globalSession, options, input, compileRequest, output.output);
+ return ShaderCompilerUtil::compileProgram(
+ globalSession,
+ options,
+ input,
+ compileRequest,
+ output.output);
}
-} // renderer_test
+} // namespace renderer_test
diff --git a/tools/render-test/slang-support.h b/tools/render-test/slang-support.h
index c93008999..d52e94b47 100644
--- a/tools/render-test/slang-support.h
+++ b/tools/render-test/slang-support.h
@@ -1,14 +1,14 @@
// slang-support.h
#pragma once
-#include <slang-rhi.h>
-
+#include "options.h"
+#include "shader-input-layout.h"
#include "slang.h"
-#include "shader-input-layout.h"
-#include "options.h"
+#include <slang-rhi.h>
-namespace renderer_test {
+namespace renderer_test
+{
struct ShaderCompileRequest
{
@@ -52,36 +52,34 @@ struct ShaderCompilerUtil
{
struct Input
{
- SlangCompileTarget target;
- SlangSourceLanguage sourceLanguage;
- SlangPassThrough passThrough;
- Slang::String profile;
+ SlangCompileTarget target;
+ SlangSourceLanguage sourceLanguage;
+ SlangPassThrough passThrough;
+ Slang::String profile;
};
struct Output
{
- void set(
- slang::IComponentType* slangProgram);
+ void set(slang::IComponentType* slangProgram);
void reset();
- ~Output()
- {
- reset();
- }
+ ~Output() { reset(); }
ComPtr<slang::IComponentType> slangProgram;
ShaderProgramDesc desc = {};
- /// Compile request that owns the lifetime of compiled kernel code.
+ /// Compile request that owns the lifetime of compiled kernel code.
ComPtr<SlangCompileRequest> m_requestForKernels = nullptr;
- /// Compile request that owns the lifetime of reflection information.
+ /// Compile request that owns the lifetime of reflection information.
ComPtr<SlangCompileRequest> m_extraRequestForReflection = nullptr;
SlangCompileRequest* getRequestForKernels() const { return m_requestForKernels; }
- SlangCompileRequest* getRequestForReflection() const { return m_extraRequestForReflection ? m_extraRequestForReflection : m_requestForKernels; }
+ SlangCompileRequest* getRequestForReflection() const
+ {
+ return m_extraRequestForReflection ? m_extraRequestForReflection : m_requestForKernels;
+ }
SlangSession* session = nullptr;
-
};
struct OutputAndLayout
@@ -91,13 +89,29 @@ struct ShaderCompilerUtil
Slang::String sourcePath;
};
- static SlangResult compileWithLayout(slang::IGlobalSession* globalSession, const Options& options, const ShaderCompilerUtil::Input& input, OutputAndLayout& output);
-
- static SlangResult readSource(const Slang::String& inSourcePath, Slang::List<char>& outSourceText);
-
- static SlangResult _compileProgramImpl(slang::IGlobalSession* globalSession, const Options& options, const Input& input, const ShaderCompileRequest& request, Output& out);
- static SlangResult compileProgram(slang::IGlobalSession* globalSession, const Options& options, const Input& input, const ShaderCompileRequest& request, Output& out);
+ static SlangResult compileWithLayout(
+ slang::IGlobalSession* globalSession,
+ const Options& options,
+ const ShaderCompilerUtil::Input& input,
+ OutputAndLayout& output);
+
+ static SlangResult readSource(
+ const Slang::String& inSourcePath,
+ Slang::List<char>& outSourceText);
+
+ static SlangResult _compileProgramImpl(
+ slang::IGlobalSession* globalSession,
+ const Options& options,
+ const Input& input,
+ const ShaderCompileRequest& request,
+ Output& out);
+ static SlangResult compileProgram(
+ slang::IGlobalSession* globalSession,
+ const Options& options,
+ const Input& input,
+ const ShaderCompileRequest& request,
+ Output& out);
};
-} // renderer_test
+} // namespace renderer_test
diff --git a/tools/slang-capability-generator/capability-generator-main.cpp b/tools/slang-capability-generator/capability-generator-main.cpp
index 0b2540599..40fe8310c 100644
--- a/tools/slang-capability-generator/capability-generator-main.cpp
+++ b/tools/slang-capability-generator/capability-generator-main.cpp
@@ -1,22 +1,24 @@
// capabilities-generator-main.cpp
-#include <stdio.h>
#include "../../source/compiler-core/slang-lexer.h"
#include "../../source/compiler-core/slang-perfect-hash-codegen.h"
+#include "../../source/core/slang-file-system.h"
#include "../../source/core/slang-io.h"
#include "../../source/core/slang-secure-crt.h"
#include "../../source/core/slang-string-util.h"
-#include "../../source/core/slang-file-system.h"
#include "../../source/core/slang-uint-set.h"
+#include <stdio.h>
+
using namespace Slang;
namespace Diagnostics
{
-#define DIAGNOSTIC(id, severity, name, messageFormat) const DiagnosticInfo name = { id, Severity::severity, #name, messageFormat };
+#define DIAGNOSTIC(id, severity, name, messageFormat) \
+ const DiagnosticInfo name = {id, Severity::severity, #name, messageFormat};
#include "slang-capability-diagnostic-defs.h"
#undef DIAGNOSTIC
-}
+} // namespace Diagnostics
enum class CapabilityFlavor
{
@@ -30,7 +32,7 @@ struct CapabilityDef;
struct CapabilityConjunctionExpr
{
List<CapabilityDef*> atoms;
- SourceLoc sourceLoc;
+ SourceLoc sourceLoc;
};
struct CapabilityDisjunctionExpr
@@ -50,7 +52,10 @@ struct CapabilitySharedContext
CapabilityDef* ptrOfStage = nullptr;
};
-static void _removeFromOtherAtomsNotInThis(HashSet<const CapabilityDef*> thisSet, HashSet<const CapabilityDef*> otherSet, List<const CapabilityDef*> atomsToRemove)
+static void _removeFromOtherAtomsNotInThis(
+ HashSet<const CapabilityDef*> thisSet,
+ HashSet<const CapabilityDef*> otherSet,
+ List<const CapabilityDef*> atomsToRemove)
{
atomsToRemove.clear();
atomsToRemove.reserve(otherSet.getCount());
@@ -81,21 +86,13 @@ UnownedStringSlice getHeaderNameFromAutoDocHeaderGroup(UInt headerGroup)
{
switch (headerGroup)
{
- case (UInt)AutoDocHeaderGroup::Targets:
- return UnownedStringSlice("Targets");
- case (UInt)AutoDocHeaderGroup::Stages:
- return UnownedStringSlice("Stages");
- case (UInt)AutoDocHeaderGroup::Extensions:
- return UnownedStringSlice("Extensions");
- case (UInt)AutoDocHeaderGroup::Versions:
- return UnownedStringSlice("Versions");
- case (UInt)AutoDocHeaderGroup::Compound:
- return UnownedStringSlice("Compound Capabilities");
- case (UInt)AutoDocHeaderGroup::Other:
- return UnownedStringSlice("Other");
- default:
- SLANG_ASSERT("Unknown `AutoDocHeaderGroup`");
- return UnownedStringSlice("");
+ case (UInt)AutoDocHeaderGroup::Targets: return UnownedStringSlice("Targets");
+ case (UInt)AutoDocHeaderGroup::Stages: return UnownedStringSlice("Stages");
+ case (UInt)AutoDocHeaderGroup::Extensions: return UnownedStringSlice("Extensions");
+ case (UInt)AutoDocHeaderGroup::Versions: return UnownedStringSlice("Versions");
+ case (UInt)AutoDocHeaderGroup::Compound: return UnownedStringSlice("Compound Capabilities");
+ case (UInt)AutoDocHeaderGroup::Other: return UnownedStringSlice("Other");
+ default: SLANG_ASSERT("Unknown `AutoDocHeaderGroup`"); return UnownedStringSlice("");
}
}
@@ -104,24 +101,29 @@ UnownedStringSlice getHeaderDescriptionFromAutoDocHeaderGroup(UInt headerGroup)
switch (headerGroup)
{
case (UInt)AutoDocHeaderGroup::Targets:
- return UnownedStringSlice("Capabilities to specify code generation targets (`glsl`, `spirv`...)");
+ return UnownedStringSlice(
+ "Capabilities to specify code generation targets (`glsl`, `spirv`...)");
case (UInt)AutoDocHeaderGroup::Stages:
- return UnownedStringSlice("Capabilities to specify code generation stages (`vertex`, `fragment`...)");
+ return UnownedStringSlice(
+ "Capabilities to specify code generation stages (`vertex`, `fragment`...)");
case (UInt)AutoDocHeaderGroup::Extensions:
return UnownedStringSlice("Capabilities to specify extensions (`GL_EXT`, `SPV_EXT`...)");
case (UInt)AutoDocHeaderGroup::Versions:
- return UnownedStringSlice("Capabilities to specify versions of a code generation target (`sm_5_0`, `GLSL_400`...)");
+ return UnownedStringSlice("Capabilities to specify versions of a code generation "
+ "target (`sm_5_0`, `GLSL_400`...)");
case (UInt)AutoDocHeaderGroup::Compound:
- return UnownedStringSlice("Capabilities to specify capabilities created by other capabilities (`raytracing`, `meshshading`...)");
+ return UnownedStringSlice("Capabilities to specify capabilities created by other "
+ "capabilities (`raytracing`, `meshshading`...)");
case (UInt)AutoDocHeaderGroup::Other:
return UnownedStringSlice("Capabilities which may be deprecated");
- default:
- SLANG_ASSERT("Unknown `AutoDocHeaderGroup`");
- return UnownedStringSlice("");
+ default: SLANG_ASSERT("Unknown `AutoDocHeaderGroup`"); return UnownedStringSlice("");
}
}
-AutoDocHeaderGroup getAutoDocHeaderGroupFromTag(DiagnosticSink* sink, UnownedStringSlice headerGroupName, SourceLoc loc)
+AutoDocHeaderGroup getAutoDocHeaderGroupFromTag(
+ DiagnosticSink* sink,
+ UnownedStringSlice headerGroupName,
+ SourceLoc loc)
{
if (headerGroupName.caseInsensitiveEquals(UnownedStringSlice("Other")))
return AutoDocHeaderGroup::Other;
@@ -182,8 +184,9 @@ public:
SerializedArrayView serializedCanonicalRepresentation;
SourceLoc sourceLoc;
AutoDocInfo docComment;
- /// Stores key atoms a CapabilityDef refers to.
- /// Shared key atoms: key atoms shared between every individual set in a canonicalRepresentation, added together.
+ /// Stores key atoms a CapabilityDef refers to.
+ /// Shared key atoms: key atoms shared between every individual set in a
+ /// canonicalRepresentation, added together.
HashSet<const CapabilityDef*> keyAtomsPresent;
CapabilitySharedContext* sharedContext;
@@ -233,27 +236,33 @@ public:
else if (base == sharedContext->ptrOfStage)
{
foundStage = true;
- if(!alreadySetTarget)
+ if (!alreadySetTarget)
sharedKeyAtomsInCanonicalSet_stage.add(otherkeyAtomsPresent);
}
// all key atoms associated with atom
keyAtomsFound.add(otherkeyAtomsPresent);
}
- // remove all not shared key atoms
+ // remove all not shared key atoms
if (foundTarget)
{
alreadySetTarget = true;
- _removeFromOtherAtomsNotInThis(keyAtomsFound, sharedKeyAtomsInCanonicalSet_target, atomsToRemove);
+ _removeFromOtherAtomsNotInThis(
+ keyAtomsFound,
+ sharedKeyAtomsInCanonicalSet_target,
+ atomsToRemove);
}
if (foundStage)
{
alreadySetStage = true;
- _removeFromOtherAtomsNotInThis(keyAtomsFound, sharedKeyAtomsInCanonicalSet_stage, atomsToRemove);
+ _removeFromOtherAtomsNotInThis(
+ keyAtomsFound,
+ sharedKeyAtomsInCanonicalSet_stage,
+ atomsToRemove);
}
keyAtomsFound.clear();
}
-
+
// add all shared key atoms
for (auto keyAtom : sharedKeyAtomsInCanonicalSet_target)
this->keyAtomsPresent.add(keyAtom);
@@ -285,16 +294,11 @@ static bool isInternalDef(RefPtr<CapabilityDef> def)
struct CapabilityDefParser
{
- CapabilityDefParser(
- Lexer* lexer,
- DiagnosticSink* sink,
- CapabilitySharedContext& sharedContext)
- : m_lexer(lexer)
- , m_sink(sink)
- , m_sharedContext(sharedContext)
+ CapabilityDefParser(Lexer* lexer, DiagnosticSink* sink, CapabilitySharedContext& sharedContext)
+ : m_lexer(lexer), m_sink(sink), m_sharedContext(sharedContext)
{
}
-
+
Lexer* m_lexer;
DiagnosticSink* m_sink;
@@ -330,12 +334,17 @@ struct CapabilityDefParser
nextToken = m_tokenReader.advanceToken();
if constexpr (ContainsOption<advanceOptions, AdvanceOptions::SkipComments>())
{
- while (nextToken.type == TokenType::BlockComment || nextToken.type == TokenType::LineComment)
+ while (nextToken.type == TokenType::BlockComment ||
+ nextToken.type == TokenType::LineComment)
nextToken = m_tokenReader.advanceToken();
}
if (nextToken.type != type)
{
- m_sink->diagnose(nextToken.loc, Diagnostics::unexpectedTokenExpectedTokenType, nextToken, type);
+ m_sink->diagnose(
+ nextToken.loc,
+ Diagnostics::unexpectedTokenExpectedTokenType,
+ nextToken,
+ type);
return SLANG_FAIL;
}
return SLANG_OK;
@@ -353,7 +362,8 @@ struct CapabilityDefParser
for (;;)
{
Token nameToken;
- SLANG_RETURN_ON_FAIL(readToken<AdvanceOptions::SkipComments>(TokenType::Identifier, nameToken));
+ SLANG_RETURN_ON_FAIL(
+ readToken<AdvanceOptions::SkipComments>(TokenType::Identifier, nameToken));
CapabilityDef* def = nullptr;
if (m_mapNameToCapability.tryGetValue(nameToken.getContent(), def))
{
@@ -386,15 +396,15 @@ struct CapabilityDefParser
void validateInternalAtomExternalAtomPair()
{
- // All `_Internal` atoms must have an `External` atom.
+ // All `_Internal` atoms must have an `External` atom.
// `External` atoms do not require to have an `_Internal` atom.
- // The following behavior ensures that if we error with 'atom' instead of
+ // The following behavior ensures that if we error with 'atom' instead of
// '_atom' a user may add the 'atom' capability to solve their error. This is
// important because '_Internal' will only be for 1 target, 'External' will alias
// to more than 1 target. We need to ensure users avoid 'Internal' when possible.
Dictionary<String, List<RefPtr<CapabilityDef>>> nameToInternalAndExternalAtom;
- for(auto i : m_defs)
+ for (auto i : m_defs)
{
// 'abstract' atoms are not reported to a user and are ignored
if (i->flavor == CapabilityFlavor::Abstract)
@@ -402,18 +412,22 @@ struct CapabilityDefParser
// Try to pack `_atom` and `atom` into the same per key List
String name = i->name;
- if(i->name.startsWith("_"))
+ if (i->name.startsWith("_"))
name = name.subString(1, name.getLength() - 1);
nameToInternalAndExternalAtom[name].add(i);
}
- for(auto i : nameToInternalAndExternalAtom)
+ for (auto i : nameToInternalAndExternalAtom)
{
SLANG_ASSERT(i.second.getCount() <= 2);
- if(i.second.getCount() != 2)
+ if (i.second.getCount() != 2)
{
- // If we only have a '_Internal' atom inside our name list there is a missing 'External' atom
- if(i.second[0]->name.startsWith("_"))
- m_sink->diagnose(i.second[0]->sourceLoc, Diagnostics::missingExternalInternalAtomPair, i.second[0]->name);
+ // If we only have a '_Internal' atom inside our name list there is a missing
+ // 'External' atom
+ if (i.second[0]->name.startsWith("_"))
+ m_sink->diagnose(
+ i.second[0]->sourceLoc,
+ Diagnostics::missingExternalInternalAtomPair,
+ i.second[0]->name);
}
}
}
@@ -434,7 +448,9 @@ struct CapabilityDefParser
{
auto nextToken = m_tokenReader.advanceToken();
- if (!isLineSuccessive(successiveCommentLine, m_lexer->m_sourceView->getHumaneLoc(nextToken.getLoc())))
+ if (!isLineSuccessive(
+ successiveCommentLine,
+ m_lexer->m_sourceView->getHumaneLoc(nextToken.getLoc())))
successiveComments = AutoDocInfo();
RefPtr<CapabilityDef> def = new CapabilityDef();
@@ -462,31 +478,37 @@ struct CapabilityDefParser
// Auto-document if the preceeding token to an identifier is '///'
// complete rules described in `source\slang\slang-capabilities.capdef`
auto commentContent = nextToken.getContent();
-
+
// remove "//"
commentContent = commentContent.subString(2, commentContent.getLength() - 2);
if (commentContent.startsWith("/"))
{
- auto commentLine = m_lexer->m_sourceView->getHumaneLoc(nextToken.getLoc());
+ auto commentLine = m_lexer->m_sourceView->getHumaneLoc(nextToken.getLoc());
// Reset the `successiveCommentLine` to our newest commentLine
successiveCommentLine = commentLine;
// remove "/" from "///"
- commentContent = commentContent.subString(1, commentContent.getLength() - 1).trim();
-
+ commentContent =
+ commentContent.subString(1, commentContent.getLength() - 1).trim();
+
// Check if we have a `[header]`
if (commentContent.startsWith("["))
{
// Make a substring of `header]`
- auto consumedLeftBracketOfHeader = commentContent.subString(1, commentContent.getLength() - 1);
+ auto consumedLeftBracketOfHeader =
+ commentContent.subString(1, commentContent.getLength() - 1);
// Find a `]` of `header]` if it exists
auto indexOfHeaderEnd = consumedLeftBracketOfHeader.indexOf(']');
if (indexOfHeaderEnd != -1)
{
// We found our `header`
- auto headerName = consumedLeftBracketOfHeader.subString(0, indexOfHeaderEnd);
- successiveComments.headerGroup = getAutoDocHeaderGroupFromTag(m_sink, headerName, nextToken.getLoc());
+ auto headerName =
+ consumedLeftBracketOfHeader.subString(0, indexOfHeaderEnd);
+ successiveComments.headerGroup = getAutoDocHeaderGroupFromTag(
+ m_sink,
+ headerName,
+ nextToken.getLoc());
continue;
}
// If we did not find a header this is a regular comment
@@ -508,7 +530,8 @@ struct CapabilityDefParser
}
Token nameToken;
- SLANG_RETURN_ON_FAIL(readToken<AdvanceOptions::SkipComments>(TokenType::Identifier, nameToken));
+ SLANG_RETURN_ON_FAIL(
+ readToken<AdvanceOptions::SkipComments>(TokenType::Identifier, nameToken));
def->name = nameToken.getContent();
if (def->flavor == CapabilityFlavor::Normal)
@@ -520,11 +543,13 @@ struct CapabilityDefParser
if (advanceIf<AdvanceOptions::SkipComments>(TokenType::OpAssign))
{
Token rankToken;
- SLANG_RETURN_ON_FAIL(readToken<AdvanceOptions::SkipComments>(TokenType::IntegerLiteral, rankToken));
+ SLANG_RETURN_ON_FAIL(readToken<AdvanceOptions::SkipComments>(
+ TokenType::IntegerLiteral,
+ rankToken));
def->rank = stringToInt(rankToken.getContent());
}
def->docComment = successiveComments;
- if(def->docComment.comment.getLength() == 0 && !isInternalDef(def))
+ if (def->docComment.comment.getLength() == 0 && !isInternalDef(def))
m_sink->diagnose(nextToken.loc, Diagnostics::requiresDocComment, def->name);
}
else if (def->flavor == CapabilityFlavor::Alias)
@@ -550,12 +575,10 @@ struct CapabilityDefParser
return SLANG_FAIL;
}
- //set abstract atom identifiers
- if (!m_sharedContext.ptrOfTarget
- && def->name.equals("target"))
+ // set abstract atom identifiers
+ if (!m_sharedContext.ptrOfTarget && def->name.equals("target"))
m_sharedContext.ptrOfTarget = m_defs.getLast();
- else if (!m_sharedContext.ptrOfStage
- && def->name.equals("stage"))
+ else if (!m_sharedContext.ptrOfStage && def->name.equals("stage"))
m_sharedContext.ptrOfStage = m_defs.getLast();
def->sourceLoc = nameToken.loc;
@@ -611,11 +634,13 @@ struct CapabilityConjunction
return nullptr;
}
- bool shareTargetAndStageAtom(const CapabilityConjunction& other, CapabilitySharedContext& context)
+ bool shareTargetAndStageAtom(
+ const CapabilityConjunction& other,
+ CapabilitySharedContext& context)
{
// shared target means thisTarget==otherTarget
// shared stage means either `nostage + ...` or `stage == stage`
-
+
const CapabilityDef* thisTarget = this->getAbstractAtom(context.ptrOfTarget);
const CapabilityDef* otherTarget = other.getAbstractAtom(context.ptrOfTarget);
@@ -633,7 +658,8 @@ struct CapabilityConjunction
bool isImpossible() const
{
- // Keep a map from an abstract base to the concrete atom defined in this conjunction that implements the base.
+ // Keep a map from an abstract base to the concrete atom defined in this conjunction that
+ // implements the base.
Dictionary<CapabilityDef*, CapabilityDef*> abstractKV;
for (auto& atom : atoms)
@@ -642,8 +668,8 @@ struct CapabilityConjunction
if (!abstractBase)
continue;
- // Have we already seen another concrete atom that implements the same abstract base of the current atom?
- // If so, we have a conflict and the conjunction is impossible.
+ // Have we already seen another concrete atom that implements the same abstract base of
+ // the current atom? If so, we have a conflict and the conjunction is impossible.
//
CapabilityDef* value = nullptr;
if (abstractKV.tryGetValue(abstractBase, value))
@@ -664,7 +690,11 @@ struct CapabilityDisjunction
{
List<CapabilityConjunction> conjunctions;
- void addConjunction(DiagnosticSink* sink, SourceLoc sourceLoc, CapabilitySharedContext& context, CapabilityConjunction& c)
+ void addConjunction(
+ DiagnosticSink* sink,
+ SourceLoc sourceLoc,
+ CapabilitySharedContext& context,
+ CapabilityConjunction& c)
{
if (c.isImpossible())
return;
@@ -700,7 +730,11 @@ struct CapabilityDisjunction
{
if (sink)
{
- sink->diagnose(sourceLoc, Diagnostics::unionWithSameKeyAtomButNotSubset, conjunctions[i].toString(), c.toString());
+ sink->diagnose(
+ sourceLoc,
+ Diagnostics::unionWithSameKeyAtomButNotSubset,
+ conjunctions[i].toString(),
+ c.toString());
sink = nullptr;
}
}
@@ -721,9 +755,9 @@ struct CapabilityDisjunction
if (!conjunctions[i].implies(conjunctions[ii]))
continue;
- if(i < ii)
+ if (i < ii)
{
- conjunctions.fastRemoveAt(ii);
+ conjunctions.fastRemoveAt(ii);
}
else
{
@@ -735,7 +769,10 @@ struct CapabilityDisjunction
}
}
- void inclusiveJoinConjunction(CapabilitySharedContext& context, CapabilityConjunction& c, List<CapabilityConjunction>& toAddAfter)
+ void inclusiveJoinConjunction(
+ CapabilitySharedContext& context,
+ CapabilityConjunction& c,
+ List<CapabilityConjunction>& toAddAfter)
{
if (c.isImpossible())
return;
@@ -764,7 +801,11 @@ struct CapabilityDisjunction
conjunctions.add(_Move(c));
}
- CapabilityDisjunction joinWith(DiagnosticSink* sink, SourceLoc sourceLoc, CapabilitySharedContext& context, const CapabilityDisjunction& other)
+ CapabilityDisjunction joinWith(
+ DiagnosticSink* sink,
+ SourceLoc sourceLoc,
+ CapabilitySharedContext& context,
+ const CapabilityDisjunction& other)
{
if (conjunctions.getCount() == 0)
{
@@ -774,7 +815,7 @@ struct CapabilityDisjunction
{
return *this;
}
-
+
CapabilityDisjunction result;
for (auto& thisC : conjunctions)
@@ -805,10 +846,12 @@ struct CapabilityDisjunction
List<CapabilityDef*> atoms;
for (auto& atom : c.atoms)
atoms.add(atom);
- atoms.sort([](CapabilityDef* c1, CapabilityDef* c2) {return c1->enumValue < c2->enumValue; });
+ atoms.sort([](CapabilityDef* c1, CapabilityDef* c2)
+ { return c1->enumValue < c2->enumValue; });
result.add(_Move(atoms));
}
- result.sort([](const List<CapabilityDef*>& c1, const List<CapabilityDef*>& c2)
+ result.sort(
+ [](const List<CapabilityDef*>& c1, const List<CapabilityDef*>& c2)
{
for (Index i = 0; i < Math::Min(c1.getCount(), c2.getCount()); i++)
{
@@ -836,7 +879,11 @@ CapabilityDisjunction getCanonicalRepresentation(CapabilityDef* def)
return result;
}
-CapabilityDisjunction evaluateConjunction(DiagnosticSink* sink, SourceLoc sourceLoc, CapabilitySharedContext& context, const List<CapabilityDef*>& atoms)
+CapabilityDisjunction evaluateConjunction(
+ DiagnosticSink* sink,
+ SourceLoc sourceLoc,
+ CapabilitySharedContext& context,
+ const List<CapabilityDef*>& atoms)
{
CapabilityDisjunction result;
for (auto* def : atoms)
@@ -847,7 +894,10 @@ CapabilityDisjunction evaluateConjunction(DiagnosticSink* sink, SourceLoc source
return result;
}
-void calcCanonicalRepresentation(DiagnosticSink* sink, CapabilityDef* def, const List<CapabilityDef*>& mapEnumValueToDef)
+void calcCanonicalRepresentation(
+ DiagnosticSink* sink,
+ CapabilityDef* def,
+ const List<CapabilityDef*>& mapEnumValueToDef)
{
CapabilityDisjunction disjunction;
if (def->flavor == CapabilityFlavor::Normal)
@@ -859,7 +909,8 @@ void calcCanonicalRepresentation(DiagnosticSink* sink, CapabilityDef* def, const
CapabilityDisjunction exprVal;
for (auto& c : def->expr.conjunctions)
{
- CapabilityDisjunction evalD = evaluateConjunction(sink, c.sourceLoc, *def->sharedContext, c.atoms);
+ CapabilityDisjunction evalD =
+ evaluateConjunction(sink, c.sourceLoc, *def->sharedContext, c.atoms);
List<CapabilityConjunction> toAddAfter;
for (auto& cc : evalD.conjunctions)
{
@@ -875,25 +926,36 @@ void calcCanonicalRepresentation(DiagnosticSink* sink, CapabilityDef* def, const
def->fillKeyAtomsPresentInCannonicalRepresentation();
}
-void calcCanonicalRepresentations(DiagnosticSink* sink, List<RefPtr<CapabilityDef>>& defs, const List<CapabilityDef*>& mapEnumValueToDef)
+void calcCanonicalRepresentations(
+ DiagnosticSink* sink,
+ List<RefPtr<CapabilityDef>>& defs,
+ const List<CapabilityDef*>& mapEnumValueToDef)
{
for (auto def : defs)
calcCanonicalRepresentation(sink, def, mapEnumValueToDef);
}
// Create a local UIntSet with data
-void outputLocalUIntSetBuffer(const String& nameOfBuffer, StringBuilder& resultBuilder, UIntSet& set)
+void outputLocalUIntSetBuffer(
+ const String& nameOfBuffer,
+ StringBuilder& resultBuilder,
+ UIntSet& set)
{
resultBuilder << " CapabilityAtomSet " << nameOfBuffer << ";\n";
- resultBuilder << " " << nameOfBuffer << ".resizeBackingBufferDirectly(" << set.getBuffer().getCount() << ");\n";
+ resultBuilder << " " << nameOfBuffer << ".resizeBackingBufferDirectly("
+ << set.getBuffer().getCount() << ");\n";
for (Index i = 0; i < set.getBuffer().getCount(); i++)
{
- resultBuilder << " " << nameOfBuffer << ".addRawElement(UIntSet::Element(" << set.getBuffer()[i] << "UL), " << i << "); \n";
+ resultBuilder << " " << nameOfBuffer << ".addRawElement(UIntSet::Element("
+ << set.getBuffer()[i] << "UL), " << i << "); \n";
}
}
// Create function to generate a UIntSet with initial data
-void outputUIntSetGenerator(const String& nameOfGenerator, StringBuilder & resultBuilder, UIntSet & set)
+void outputUIntSetGenerator(
+ const String& nameOfGenerator,
+ StringBuilder& resultBuilder,
+ UIntSet& set)
{
resultBuilder << "inline static CapabilityAtomSet " << nameOfGenerator << "()\n";
resultBuilder << "{\n";
@@ -908,20 +970,23 @@ UIntSet atomSetToUIntSet(const List<CapabilityDef*>& atomSet)
{
UIntSet set{};
// Last element is generally a larger number. Start from there to minimize reallocations.
- for (Index i = atomSet.getCount()-1; i >= 0; i--)
+ for (Index i = atomSet.getCount() - 1; i >= 0; i--)
set.add(atomSet[i]->enumValue);
return set;
}
-void printDocForCapabilityDef(StringBuilder& sbDoc, RefPtr<CapabilityDef> def, List<StringBuilder>& sbDocSections)
+void printDocForCapabilityDef(
+ StringBuilder& sbDoc,
+ RefPtr<CapabilityDef> def,
+ List<StringBuilder>& sbDocSections)
{
- if (isInternalDef(def)
- || def->flavor == CapabilityFlavor::Abstract
- || def->docComment.headerGroup == AutoDocHeaderGroup::Invalid)
+ if (isInternalDef(def) || def->flavor == CapabilityFlavor::Abstract ||
+ def->docComment.headerGroup == AutoDocHeaderGroup::Invalid)
return;
auto& sbDocSection = sbDocSections[(UInt)def->docComment.headerGroup];
- sbDocSection << "\n" << "`" << def->name << "`\n";
+ sbDocSection << "\n"
+ << "`" << def->name << "`\n";
sbDocSection << def->docComment.comment;
}
@@ -931,7 +996,8 @@ List<StringBuilder> setupDocCommentHeaderStringBuilders()
sbDocSections.setCount((UInt)AutoDocHeaderGroup::Count);
for (UInt i = 0; i < (UInt)AutoDocHeaderGroup::Count; i++)
{
- sbDocSections[i] << "\n" << getHeaderNameFromAutoDocHeaderGroup(i) << "\n----------------------\n";
+ sbDocSections[i] << "\n"
+ << getHeaderNameFromAutoDocHeaderGroup(i) << "\n----------------------\n";
sbDocSections[i] << "*" << getHeaderDescriptionFromAutoDocHeaderGroup(i) << "*\n";
}
return sbDocSections;
@@ -972,13 +1038,17 @@ Capability Atoms
for (UInt i = 0; i < (UInt)AutoDocHeaderGroup::Count; i++)
{
auto headerName = getHeaderNameFromAutoDocHeaderGroup(i);
- sbDoc << i + 1 << ". "; // "i. "
+ sbDoc << i + 1 << ". "; // "i. "
addHyperLink(sbDoc, headerName);
sbDoc << "\n";
}
}
-SlangResult generateDocumentation(DiagnosticSink* sink, List<RefPtr<CapabilityDef>>& defs, StringBuilder& sbDoc, const String& outPath)
+SlangResult generateDocumentation(
+ DiagnosticSink* sink,
+ List<RefPtr<CapabilityDef>>& defs,
+ StringBuilder& sbDoc,
+ const String& outPath)
{
setupDocumentationHeader(sbDoc, outPath);
@@ -991,9 +1061,13 @@ SlangResult generateDocumentation(DiagnosticSink* sink, List<RefPtr<CapabilityDe
sbDoc << stringBuilder.toString();
return 1;
}
-SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>>& defs, StringBuilder& sbHeader, StringBuilder& sbCpp)
+SlangResult generateDefinitions(
+ DiagnosticSink* sink,
+ List<RefPtr<CapabilityDef>>& defs,
+ StringBuilder& sbHeader,
+ StringBuilder& sbCpp)
{
-
+
sbHeader << "enum class CapabilityAtom\n{\n";
sbHeader << " Invalid,\n";
for (auto def : defs)
@@ -1005,7 +1079,7 @@ SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>
}
sbHeader << " Count\n";
sbHeader << "};\n";
-
+
CapabilityDef* firstAbstractDef = nullptr;
CapabilityDef* firstAliasDef = nullptr;
sbHeader << "enum class CapabilityName\n{\n";
@@ -1071,12 +1145,20 @@ SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>
anyStageAtomSet.add(def->enumValue);
}
}
- outputUIntSetGenerator("generatorOf_kAnyTargetUIntSetBuffer", anyTargetUIntSetHash, anyTargetAtomSet);
- anyTargetUIntSetHash << "static CapabilityAtomSet kAnyTargetUIntSetBuffer = generatorOf_kAnyTargetUIntSetBuffer();\n";
+ outputUIntSetGenerator(
+ "generatorOf_kAnyTargetUIntSetBuffer",
+ anyTargetUIntSetHash,
+ anyTargetAtomSet);
+ anyTargetUIntSetHash << "static CapabilityAtomSet kAnyTargetUIntSetBuffer = "
+ "generatorOf_kAnyTargetUIntSetBuffer();\n";
sbCpp << anyTargetUIntSetHash;
- outputUIntSetGenerator("generatorOf_kAnyStageUIntSetBuffer", anyStageUIntSetHash, anyStageAtomSet);
- anyStageUIntSetHash << "static CapabilityAtomSet kAnyStageUIntSetBuffer = generatorOf_kAnyStageUIntSetBuffer();\n";
+ outputUIntSetGenerator(
+ "generatorOf_kAnyStageUIntSetBuffer",
+ anyStageUIntSetHash,
+ anyStageAtomSet);
+ anyStageUIntSetHash << "static CapabilityAtomSet kAnyStageUIntSetBuffer = "
+ "generatorOf_kAnyStageUIntSetBuffer();\n";
sbCpp << anyStageUIntSetHash;
sbHeader << "\nenum {\n";
@@ -1088,11 +1170,9 @@ SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>
struct SerializedConjunction
{
- SerializedConjunction()
- {
- }
- SerializedConjunction(const String& initFunctionName, UIntSet& data) :
- m_initFunctionName(initFunctionName), m_data(data)
+ SerializedConjunction() {}
+ SerializedConjunction(const String& initFunctionName, UIntSet& data)
+ : m_initFunctionName(initFunctionName), m_data(data)
{
}
String m_initFunctionName;
@@ -1101,36 +1181,41 @@ SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>
List<SerializedConjunction> serializedCapabilitesCache;
List<Index> serializedAtomDisjunctions;
- auto serializeConjunction = [&](const List<CapabilityDef*>& capabilities, CapabilityDef* parentDef, Index conjunctionNumber) -> Index
+ auto serializeConjunction = [&](const List<CapabilityDef*>& capabilities,
+ CapabilityDef* parentDef,
+ Index conjunctionNumber) -> Index
+ {
+ auto capabilitiesAsUIntSet = atomSetToUIntSet(capabilities);
+ // Do we already have a serialized capability array that is the same the one we are trying
+ // to serialize?
+ for (Index i = 0; i < serializedCapabilitesCache.getCount(); i++)
{
- auto capabilitiesAsUIntSet = atomSetToUIntSet(capabilities);
- // Do we already have a serialized capability array that is the same the one we are trying to serialize?
- for (Index i = 0; i < serializedCapabilitesCache.getCount(); i++)
+ auto& existingSet = serializedCapabilitesCache[i].m_data;
+ if (existingSet == capabilitiesAsUIntSet)
{
- auto& existingSet = serializedCapabilitesCache[i].m_data;
- if (existingSet == capabilitiesAsUIntSet)
- {
- return i;
- }
+ return i;
}
- auto initName = "generatorOf_" + parentDef->name + "_conjunction"+String(conjunctionNumber);
- outputUIntSetGenerator(initName, sbCpp, capabilitiesAsUIntSet);
+ }
+ auto initName =
+ "generatorOf_" + parentDef->name + "_conjunction" + String(conjunctionNumber);
+ outputUIntSetGenerator(initName, sbCpp, capabilitiesAsUIntSet);
- auto result = serializedCapabilitesCache.getCount();
- serializedCapabilitesCache.add(SerializedConjunction(initName + "()", capabilitiesAsUIntSet));
- return result;
- };
+ auto result = serializedCapabilitesCache.getCount();
+ serializedCapabilitesCache.add(
+ SerializedConjunction(initName + "()", capabilitiesAsUIntSet));
+ return result;
+ };
auto serializeDisjunction = [&](const List<Index>& conjunctions) -> SerializedArrayView
+ {
+ SerializedArrayView result;
+ result.first = serializedAtomDisjunctions.getCount();
+ for (auto c : conjunctions)
{
- SerializedArrayView result;
- result.first = serializedAtomDisjunctions.getCount();
- for (auto c : conjunctions)
- {
- serializedAtomDisjunctions.add(c);
- }
- result.count = conjunctions.getCount();
- return result;
- };
+ serializedAtomDisjunctions.add(c);
+ }
+ result.count = conjunctions.getCount();
+ return result;
+ };
for (auto def : defs)
{
List<Index> conjunctions;
@@ -1138,7 +1223,7 @@ SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>
conjunctions.add(serializeConjunction(c, def, conjunctions.getCount()));
def->serializedCanonicalRepresentation = serializeDisjunction(conjunctions);
}
-
+
sbCpp << "static CapabilityAtomSet kCapabilityArray[] = {\n";
Index arrayIndex = 0;
for (Index i = 0; i < serializedCapabilitesCache.getCount(); ++i)
@@ -1153,12 +1238,15 @@ SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>
}
sbCpp << "};\n";
- sbCpp << "static const CapabilityAtomInfo kCapabilityNameInfos[int(CapabilityName::Count)] = {\n";
+ sbCpp
+ << "static const CapabilityAtomInfo kCapabilityNameInfos[int(CapabilityName::Count)] = {\n";
for (auto* def : mapEnumValueToDef)
{
if (!def)
{
- sbCpp << R"( { UnownedStringSlice::fromLiteral("Invalid"), CapabilityNameFlavor::Concrete, CapabilityName::Invalid, 0, {nullptr, 0} },)" << "\n";
+ sbCpp
+ << R"( { UnownedStringSlice::fromLiteral("Invalid"), CapabilityNameFlavor::Concrete, CapabilityName::Invalid, 0, {nullptr, 0} },)"
+ << "\n";
continue;
}
@@ -1168,15 +1256,9 @@ SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>
// flavor.
switch (def->flavor)
{
- case CapabilityFlavor::Normal:
- sbCpp << "CapabilityNameFlavor::Concrete";
- break;
- case CapabilityFlavor::Abstract:
- sbCpp << "CapabilityNameFlavor::Abstract";
- break;
- case CapabilityFlavor::Alias:
- sbCpp << "CapabilityNameFlavor::Alias";
- break;
+ case CapabilityFlavor::Normal: sbCpp << "CapabilityNameFlavor::Concrete"; break;
+ case CapabilityFlavor::Abstract: sbCpp << "CapabilityNameFlavor::Abstract"; break;
+ case CapabilityFlavor::Alias: sbCpp << "CapabilityNameFlavor::Alias"; break;
}
sbCpp << ", ";
@@ -1197,32 +1279,36 @@ SlangResult generateDefinitions(DiagnosticSink* sink, List<RefPtr<CapabilityDef>
sbCpp << ", ";
// canonnical representation.
- sbCpp << "{ kCapabilityConjunctions + " << def->serializedCanonicalRepresentation.first << ", " << def->serializedCanonicalRepresentation.count << "} },\n";
+ sbCpp << "{ kCapabilityConjunctions + " << def->serializedCanonicalRepresentation.first
+ << ", " << def->serializedCanonicalRepresentation.count << "} },\n";
}
-
+
sbCpp << "};\n";
-sbCpp
-<< "void freeCapabilityDefs()\n"
-<< "{\n"
-<< " for (auto& cap : kCapabilityArray) { cap = CapabilityAtomSet(); }\n"
-<< " kAnyTargetUIntSetBuffer = CapabilityAtomSet();\n"
-<< " kAnyStageUIntSetBuffer = CapabilityAtomSet();\n"
-<< "}\n";
-return SLANG_OK;
+ sbCpp << "void freeCapabilityDefs()\n"
+ << "{\n"
+ << " for (auto& cap : kCapabilityArray) { cap = CapabilityAtomSet(); }\n"
+ << " kAnyTargetUIntSetBuffer = CapabilityAtomSet();\n"
+ << " kAnyStageUIntSetBuffer = CapabilityAtomSet();\n"
+ << "}\n";
+ return SLANG_OK;
}
-SlangResult parseDefFile(DiagnosticSink* sink, String inputPath, List<RefPtr<CapabilityDef>>& outDefs, CapabilitySharedContext& capabilitySharedContext)
+SlangResult parseDefFile(
+ DiagnosticSink* sink,
+ String inputPath,
+ List<RefPtr<CapabilityDef>>& outDefs,
+ CapabilitySharedContext& capabilitySharedContext)
{
auto sourceManager = sink->getSourceManager();
String contents;
SLANG_RETURN_ON_FAIL(File::readAllText(inputPath, contents));
- PathInfo pathInfo = PathInfo::makeFromString(inputPath);
+ PathInfo pathInfo = PathInfo::makeFromString(inputPath);
SourceFile* sourceFile = sourceManager->createSourceFileWithString(pathInfo, contents);
SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc());
- Lexer lexer;
+ Lexer lexer;
NamePool namePool;
RootNamePool rootPool;
namePool.setRootNamePool(&rootPool);
@@ -1261,10 +1347,7 @@ int main(int argc, const char* const* argv)
{
if (argc < 2)
{
- fprintf(
- stderr,
- "Usage: %s\n",
- argc >= 1 ? argv[0] : "slang-capabilities-generator");
+ fprintf(stderr, "Usage: %s\n", argc >= 1 ? argv[0] : "slang-capabilities-generator");
return 1;
}
String targetDir, outDocPath;
@@ -1303,7 +1386,10 @@ int main(int argc, const char* const* argv)
if (!File::exists(outDocPath))
{
- sink.diagnose(SourceLoc(), Diagnostics::couldNotFindValidDocumentationOutputPath, outDocPath);
+ sink.diagnose(
+ SourceLoc(),
+ Diagnostics::couldNotFindValidDocumentationOutputPath,
+ outDocPath);
}
StringBuilder sbDoc;
@@ -1323,7 +1409,13 @@ int main(int argc, const char* const* argv)
opnames.add(def->name);
}
- if (SLANG_FAILED(writePerfectHashLookupCppFile(outLookupPath, opnames, "CapabilityName", "CapabilityName::", "slang-capability.h", &sink)))
+ if (SLANG_FAILED(writePerfectHashLookupCppFile(
+ outLookupPath,
+ opnames,
+ "CapabilityName",
+ "CapabilityName::",
+ "slang-capability.h",
+ &sink)))
{
printDiagnostics(&sink);
return 1;
diff --git a/tools/slang-capability-generator/slang-capability-diagnostic-defs.h b/tools/slang-capability-generator/slang-capability-diagnostic-defs.h
index 7f80bda6a..53f99bbb4 100644
--- a/tools/slang-capability-generator/slang-capability-diagnostic-defs.h
+++ b/tools/slang-capability-generator/slang-capability-diagnostic-defs.h
@@ -28,12 +28,20 @@ DIAGNOSTIC(-1, Note, seeDefinitionOf, "see definition of '$0'")
// 0xxxx - Command line and interaction with host platform APIs.
//
-DIAGNOSTIC( 1, Error, cannotOpenFile, "cannot open file '$0'.")
-DIAGNOSTIC( 2, Error, cannotFindFile, "cannot find file '$0'.")
-DIAGNOSTIC( 4, Error, cannotWriteOutputFile, "cannot write output file '$0'.")
-DIAGNOSTIC( 5, Error, failedToLoadDynamicLibrary, "failed to load dynamic library '$0'")
-DIAGNOSTIC( 6, Error, tooManyOutputPathsSpecified, "$0 output paths specified, but only $1 entry points given")
-DIAGNOSTIC( 7, Warning, couldNotFindValidDocumentationOutputPath, "could not find valid documentation output path at $0")
+DIAGNOSTIC(1, Error, cannotOpenFile, "cannot open file '$0'.")
+DIAGNOSTIC(2, Error, cannotFindFile, "cannot find file '$0'.")
+DIAGNOSTIC(4, Error, cannotWriteOutputFile, "cannot write output file '$0'.")
+DIAGNOSTIC(5, Error, failedToLoadDynamicLibrary, "failed to load dynamic library '$0'")
+DIAGNOSTIC(
+ 6,
+ Error,
+ tooManyOutputPathsSpecified,
+ "$0 output paths specified, but only $1 entry points given")
+DIAGNOSTIC(
+ 7,
+ Warning,
+ couldNotFindValidDocumentationOutputPath,
+ "could not find valid documentation output path at $0")
//
// 2xxxx - Parsing
@@ -43,7 +51,12 @@ DIAGNOSTIC(20003, Error, unexpectedToken, "unexpected $0")
DIAGNOSTIC(20001, Error, unexpectedTokenExpectedTokenType, "unexpected $0, expected $1")
DIAGNOSTIC(20001, Error, unexpectedTokenExpectedTokenName, "unexpected $0, expected '$1'")
DIAGNOSTIC(20004, Warning, requiresDocComment, "'$0' requires a documentation comment \"///\"")
-DIAGNOSTIC(20004, Warning, invalidDocCommentHeader, "got documentation comment '[$0]', expected one of: [Target] [Stage] [EXT] [Version] [Compound] [Other]")
+DIAGNOSTIC(
+ 20004,
+ Warning,
+ invalidDocCommentHeader,
+ "got documentation comment '[$0]', expected one of: [Target] [Stage] [EXT] [Version] "
+ "[Compound] [Other]")
DIAGNOSTIC(0, Error, tokenNameExpectedButEOF, "\"$0\" expected but end of file encountered.")
DIAGNOSTIC(0, Error, tokenTypeExpectedButEOF, "$0 expected but end of file encountered.")
@@ -57,7 +70,21 @@ DIAGNOSTIC(20001, Error, unexpectedEOF, " Unexpected end of file.")
DIAGNOSTIC(20002, Error, syntaxError, "syntax error.")
DIAGNOSTIC(20003, Error, undefinedIdentifier, "undefined identifier \"$0\".")
DIAGNOSTIC(20004, Error, redefinition, "capability redefinition: '$0'.")
-DIAGNOSTIC(20005, Error, unionWithSameKeyAtomButNotSubset, "unioning ('|') capability sets which have incompatible atoms but compatible 'key atoms', this: '$0', other: '$1'")
-DIAGNOSTIC(20006, Error, invalidJoinInGenerator, "joining ('+') capability sets which have incompatible 'key atoms'")
-DIAGNOSTIC(20007, Error, missingExternalInternalAtomPair, "All internal '_atom' require a corresponding external 'atom' atom meant for user's use. Offending atom: $0")
+DIAGNOSTIC(
+ 20005,
+ Error,
+ unionWithSameKeyAtomButNotSubset,
+ "unioning ('|') capability sets which have incompatible atoms but compatible 'key atoms', "
+ "this: '$0', other: '$1'")
+DIAGNOSTIC(
+ 20006,
+ Error,
+ invalidJoinInGenerator,
+ "joining ('+') capability sets which have incompatible 'key atoms'")
+DIAGNOSTIC(
+ 20007,
+ Error,
+ missingExternalInternalAtomPair,
+ "All internal '_atom' require a corresponding external 'atom' atom meant for user's use. "
+ "Offending atom: $0")
#undef DIAGNOSTIC
diff --git a/tools/slang-cpp-extractor/cpp-extractor-main.cpp b/tools/slang-cpp-extractor/cpp-extractor-main.cpp
index e3bb041be..78ae336fa 100644
--- a/tools/slang-cpp-extractor/cpp-extractor-main.cpp
+++ b/tools/slang-cpp-extractor/cpp-extractor-main.cpp
@@ -1,39 +1,38 @@
// main.cpp
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "../../source/core/slang-secure-crt.h"
-
-#include "slang-com-helper.h"
-
-#include "../../source/core/slang-list.h"
-#include "../../source/core/slang-string.h"
-#include "../../source/core/slang-string-util.h"
+#include "../../source/compiler-core/slang-diagnostic-sink.h"
+#include "../../source/compiler-core/slang-doc-extractor.h"
+#include "../../source/compiler-core/slang-lexer.h"
+#include "../../source/compiler-core/slang-name-convention-util.h"
+#include "../../source/compiler-core/slang-name.h"
+#include "../../source/compiler-core/slang-source-loc.h"
+#include "../../source/core/slang-file-system.h"
#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-list.h"
+#include "../../source/core/slang-secure-crt.h"
#include "../../source/core/slang-string-slice-pool.h"
+#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-string.h"
#include "../../source/core/slang-writer.h"
-#include "../../source/core/slang-file-system.h"
-
-#include "../../source/compiler-core/slang-source-loc.h"
-#include "../../source/compiler-core/slang-lexer.h"
-#include "../../source/compiler-core/slang-diagnostic-sink.h"
-#include "../../source/compiler-core/slang-name.h"
-#include "../../source/compiler-core/slang-name-convention-util.h"
-#include "../../source/compiler-core/slang-doc-extractor.h"
-
-#include "node.h"
#include "diagnostics.h"
+#include "file-util.h"
+#include "macro-writer.h"
+#include "node.h"
#include "options.h"
#include "parser.h"
-#include "macro-writer.h"
-#include "file-util.h"
+#include "slang-com-helper.h"
#include "unit-test.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
/*
Some command lines:
--d source/slang slang-ast-support-types.h slang-ast-base.h slang-ast-decl.h slang-ast-expr.h slang-ast-modifier.h slang-ast-stmt.h slang-ast-type.h slang-ast-val.h -strip-prefix slang- -o slang-generated -output-fields -mark-suffix _CLASS
+-d source/slang slang-ast-support-types.h slang-ast-base.h slang-ast-decl.h slang-ast-expr.h
+slang-ast-modifier.h slang-ast-stmt.h slang-ast-type.h slang-ast-val.h -strip-prefix slang- -o
+slang-generated -output-fields -mark-suffix _CLASS
*/
namespace CppExtract
@@ -46,24 +45,20 @@ using namespace Slang;
class App
{
public:
-
SlangResult execute(const Options& options);
- /// Execute
- SlangResult executeWithArgs(int argc, const char*const* argv);
+ /// Execute
+ SlangResult executeWithArgs(int argc, const char* const* argv);
const Options& getOptions() const { return m_options; }
- App(DiagnosticSink* sink, SourceManager* sourceManager, RootNamePool* rootNamePool):
- m_sink(sink),
- m_sourceManager(sourceManager),
- m_slicePool(StringSlicePool::Style::Default)
+ App(DiagnosticSink* sink, SourceManager* sourceManager, RootNamePool* rootNamePool)
+ : m_sink(sink), m_sourceManager(sourceManager), m_slicePool(StringSlicePool::Style::Default)
{
m_namePool.setRootNamePool(rootNamePool);
}
protected:
-
SlangResult _extractDoc(NodeTree* nodeTree);
NamePool m_namePool;
@@ -71,7 +66,7 @@ protected:
Options m_options;
DiagnosticSink* m_sink;
SourceManager* m_sourceManager;
-
+
StringSlicePool m_slicePool;
};
@@ -79,7 +74,8 @@ protected:
// Work out an appropriate search type for a node type.
//
// TODO(JS):
-// NOTE! Currently extractor doesn't extract callable types and so doesn't extract callable types parameters
+// NOTE! Currently extractor doesn't extract callable types and so doesn't extract callable types
+// parameters
static DocMarkupExtractor::SearchStyle _getSearchStyle(Node* node)
{
typedef DocMarkupExtractor::SearchStyle SearchStyle;
@@ -91,27 +87,27 @@ static DocMarkupExtractor::SearchStyle _getSearchStyle(Node* node)
switch (node->m_kind)
{
- case Node::Kind::Invalid:
+ case Node::Kind::Invalid:
{
return SearchStyle::None;
}
- case Node::Kind::Field:
+ case Node::Kind::Field:
{
return SearchStyle::Variable;
}
- case Node::Kind::EnumCase:
+ case Node::Kind::EnumCase:
{
return SearchStyle::EnumCase;
}
- case Node::Kind::TypeDef:
+ case Node::Kind::TypeDef:
{
return SearchStyle::Variable;
}
- case Node::Kind::Callable:
+ case Node::Kind::Callable:
{
return SearchStyle::Before;
}
- default: break;
+ default: break;
}
// Default is to only allow before.
@@ -162,7 +158,13 @@ SlangResult App::_extractDoc(NodeTree* nodeTree)
DocMarkupExtractor extractor;
- SLANG_RETURN_ON_FAIL(extractor.extract(inputItems.getBuffer(), inputItems.getCount(), m_sourceManager, m_sink, views, outputItems));
+ SLANG_RETURN_ON_FAIL(extractor.extract(
+ inputItems.getBuffer(),
+ inputItems.getCount(),
+ m_sourceManager,
+ m_sink,
+ views,
+ outputItems));
// Put what was extracted into the nodes
{
@@ -177,7 +179,8 @@ SlangResult App::_extractDoc(NodeTree* nodeTree)
const auto inputIndex = outputItem.inputIndex;
const auto& inputItem = inputItems[inputIndex];
- if (inputItem.searchStyle != DocMarkupExtractor::SearchStyle::None && outputItem.text.getLength())
+ if (inputItem.searchStyle != DocMarkupExtractor::SearchStyle::None &&
+ outputItem.text.getLength())
{
Node* node = nodes[inputIndex];
@@ -238,15 +241,20 @@ SlangResult App::execute(const Options& options)
{
for (TypeSet* typeSet : tree.getTypeSets())
{
- // The macro name is in upper snake, so split it
+ // The macro name is in upper snake, so split it
List<UnownedStringSlice> slices;
NameConventionUtil::split(typeSet->m_macroName, slices);
if (typeSet->m_fileMark.getLength() == 0)
{
StringBuilder buf;
- // Let's guess a 'fileMark' (it becomes part of the filename) based on the macro name. Use lower kabab.
- NameConventionUtil::join(slices.getBuffer(), slices.getCount(), NameConvention::LowerKabab, buf);
+ // Let's guess a 'fileMark' (it becomes part of the filename) based on the macro
+ // name. Use lower kabab.
+ NameConventionUtil::join(
+ slices.getBuffer(),
+ slices.getCount(),
+ NameConvention::LowerKabab,
+ buf);
typeSet->m_fileMark = buf.produceString();
}
@@ -254,7 +262,11 @@ SlangResult App::execute(const Options& options)
{
// Let's guess a typename if not set -> go with upper camel
StringBuilder buf;
- NameConventionUtil::join(slices.getBuffer(), slices.getCount(), NameConvention::UpperCamel, buf);
+ NameConventionUtil::join(
+ slices.getBuffer(),
+ slices.getCount(),
+ NameConvention::UpperCamel,
+ buf);
typeSet->m_typeName = buf.produceString();
}
}
@@ -303,7 +315,7 @@ SlangResult App::execute(const Options& options)
}
/// Execute
-SlangResult App::executeWithArgs(int argc, const char*const* argv)
+SlangResult App::executeWithArgs(int argc, const char* const* argv)
{
Options options;
OptionsParser optionsParser;
@@ -316,10 +328,13 @@ SlangResult App::executeWithArgs(int argc, const char*const* argv)
/*
-The typical command line for producing generated slang files. Can be determined by setting `dumpCommandLine` belong and compiling.
+The typical command line for producing generated slang files. Can be determined by setting
+`dumpCommandLine` belong and compiling.
```
--d E:\git\slang-jsmall-nvidia\source\slang\ slang-ast-support-types.h slang-ast-base.h slang-ast-decl.h slang-ast-expr.h slang-ast-modifier.h slang-ast-stmt.h slang-ast-type.h slang-ast-val.h -strip-prefix slang- -o slang-generated -output-fields -mark-suffix _CLASS
+-d E:\git\slang-jsmall-nvidia\source\slang\ slang-ast-support-types.h slang-ast-base.h
+slang-ast-decl.h slang-ast-expr.h slang-ast-modifier.h slang-ast-stmt.h slang-ast-type.h
+slang-ast-val.h -strip-prefix slang- -o slang-generated -output-fields -mark-suffix _CLASS
```
A command line to try and parse the slang.h
@@ -329,7 +344,7 @@ A command line to try and parse the slang.h
```
*/
-int main(int argc, const char*const* argv)
+int main(int argc, const char* const* argv)
{
using namespace CppExtract;
using namespace Slang;
@@ -345,8 +360,8 @@ int main(int argc, const char*const* argv)
DiagnosticSink sink(&sourceManager, Lexer::sourceLocationLexer);
sink.writer = writer;
- // Set to true to see command line that initiated C++ extractor. Helpful when finding issues from solution building failing, and then so
- // being able to repeat the issue
+ // Set to true to see command line that initiated C++ extractor. Helpful when finding issues
+ // from solution building failing, and then so being able to repeat the issue
bool dumpCommandLine = false;
if (dumpCommandLine)
@@ -384,4 +399,3 @@ int main(int argc, const char*const* argv)
}
return 0;
}
-
diff --git a/tools/slang-cpp-extractor/diagnostic-defs.h b/tools/slang-cpp-extractor/diagnostic-defs.h
index 85e88d64d..290036a23 100644
--- a/tools/slang-cpp-extractor/diagnostic-defs.h
+++ b/tools/slang-cpp-extractor/diagnostic-defs.h
@@ -41,19 +41,39 @@ DIAGNOSTIC(100007, Error, superTypeNotFound, "Super type not found for $0")
DIAGNOSTIC(100008, Error, superTypeNotAType, "Named super type is not a type $0")
DIAGNOSTIC(100009, Error, unexpectedUnbalancedToken, "Unexpected unbalanced token")
DIAGNOSTIC(100010, Error, unexpectedEndOfFile, "Unexpected end of file")
-DIAGNOSTIC(100011, Error, expectingTypeKeyword, "Expecting type keyword - struct or class, found $0")
+DIAGNOSTIC(
+ 100011,
+ Error,
+ expectingTypeKeyword,
+ "Expecting type keyword - struct or class, found $0")
-DIAGNOSTIC(100012, Error, typeInDifferentTypeSet, "Type $0 in different type set $1 from super class $2")
+DIAGNOSTIC(
+ 100012,
+ Error,
+ typeInDifferentTypeSet,
+ "Type $0 in different type set $1 from super class $2")
DIAGNOSTIC(100013, Error, expectingIdentifier, "Expecting an identifier, found $0")
DIAGNOSTIC(100014, Error, cannotDeclareTypeInScope, "Cannot declare types in this scope")
DIAGNOSTIC(100015, Error, identifierAlreadyDefined, "Identifier already defined '$0'")
DIAGNOSTIC(100016, Error, expectingType, "Expecting a type")
DIAGNOSTIC(100017, Error, cannotParseExpression, "Cannot parse expression")
DIAGNOSTIC(100018, Error, cannotOverload, "Cannot overload this declaration");
-DIAGNOSTIC(100019, Error, classMarkerOutsideOfClass, "A class/struct marker is found outside of class or struct");
-DIAGNOSTIC(100020, Error, classMarkerAlreadyFound, "A class/struct marker already found in type '$0'");
+DIAGNOSTIC(
+ 100019,
+ Error,
+ classMarkerOutsideOfClass,
+ "A class/struct marker is found outside of class or struct");
+DIAGNOSTIC(
+ 100020,
+ Error,
+ classMarkerAlreadyFound,
+ "A class/struct marker already found in type '$0'");
DIAGNOSTIC(100021, Error, cannotParseType, "Cannot parse type");
-DIAGNOSTIC(100022, Error, destructorNameDoesntMatch, "Destructor name doesn't match class name '$0'");
+DIAGNOSTIC(
+ 100022,
+ Error,
+ destructorNameDoesntMatch,
+ "Destructor name doesn't match class name '$0'");
DIAGNOSTIC(100023, Error, cannotParseCallable, "Cannot parse callable");
// Command line errors 100100
diff --git a/tools/slang-cpp-extractor/diagnostics.cpp b/tools/slang-cpp-extractor/diagnostics.cpp
index 3abbe1b38..782e5e9da 100644
--- a/tools/slang-cpp-extractor/diagnostics.cpp
+++ b/tools/slang-cpp-extractor/diagnostics.cpp
@@ -1,13 +1,15 @@
#include "diagnostics.h"
-namespace CppExtract {
+namespace CppExtract
+{
namespace CPPDiagnostics
{
using namespace Slang;
-#define DIAGNOSTIC(id, severity, name, messageFormat) const DiagnosticInfo name = { id, Severity::severity, #name, messageFormat };
+#define DIAGNOSTIC(id, severity, name, messageFormat) \
+ const DiagnosticInfo name = {id, Severity::severity, #name, messageFormat};
#include "diagnostic-defs.h"
-}
+} // namespace CPPDiagnostics
} // namespace CppExtract
diff --git a/tools/slang-cpp-extractor/diagnostics.h b/tools/slang-cpp-extractor/diagnostics.h
index 3a98beee3..cb3bd342b 100644
--- a/tools/slang-cpp-extractor/diagnostics.h
+++ b/tools/slang-cpp-extractor/diagnostics.h
@@ -3,15 +3,17 @@
#include "../../source/slang/slang-diagnostics.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
-namespace CPPDiagnostics {
+namespace CPPDiagnostics
+{
#define DIAGNOSTIC(id, severity, name, messageFormat) extern const DiagnosticInfo name;
#include "diagnostic-defs.h"
-} // CPPDiagnostics
-} // CppExtract
+} // namespace CPPDiagnostics
+} // namespace CppExtract
#endif
diff --git a/tools/slang-cpp-extractor/file-util.cpp b/tools/slang-cpp-extractor/file-util.cpp
index e73ba7f55..2980a22ce 100644
--- a/tools/slang-cpp-extractor/file-util.cpp
+++ b/tools/slang-cpp-extractor/file-util.cpp
@@ -2,10 +2,12 @@
#include "../../source/core/slang-io.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
-namespace { // anonymous
+namespace
+{ // anonymous
struct DiagnosticReporter
{
SlangResult report(SlangResult res)
@@ -27,9 +29,8 @@ struct DiagnosticReporter
return res;
}
- DiagnosticReporter(const String& filename, DiagnosticSink* sink) :
- m_filename(filename),
- m_sink(sink)
+ DiagnosticReporter(const String& filename, DiagnosticSink* sink)
+ : m_filename(filename), m_sink(sink)
{
}
@@ -37,14 +38,18 @@ struct DiagnosticReporter
String m_filename;
};
-} // anonymous
+} // namespace
-/* static */SlangResult FileUtil::readAllText(const Slang::String& fileName, DiagnosticSink* sink, String& outRead)
+/* static */ SlangResult FileUtil::readAllText(
+ const Slang::String& fileName,
+ DiagnosticSink* sink,
+ String& outRead)
{
DiagnosticReporter reporter(fileName, sink);
-
+
RefPtr<FileStream> stream = new FileStream;
- SLANG_RETURN_ON_FAIL(reporter.report(stream->init(fileName, FileMode::Open, FileAccess::Read, FileShare::ReadWrite)));
+ SLANG_RETURN_ON_FAIL(reporter.report(
+ stream->init(fileName, FileMode::Open, FileAccess::Read, FileShare::ReadWrite)));
StreamReader reader;
SLANG_RETURN_ON_FAIL(reporter.report(reader.init(stream)));
@@ -53,12 +58,16 @@ struct DiagnosticReporter
return SLANG_OK;
}
-/* static */SlangResult FileUtil::writeAllText(const Slang::String& fileName, DiagnosticSink* sink, const UnownedStringSlice& text)
+/* static */ SlangResult FileUtil::writeAllText(
+ const Slang::String& fileName,
+ DiagnosticSink* sink,
+ const UnownedStringSlice& text)
{
// TODO(JS):
- // There is an optimization/behavior here,that checks if the contents has changed. It only writes if it hasn't
- // That might not be what you want (both because of extra work of read, the file modified stamp or other reasons, file is write only etc)
- // NOTE! That this also does the work of the comparison after it is decoded, but the *bytes* might actually be different.
+ // There is an optimization/behavior here,that checks if the contents has changed. It only
+ // writes if it hasn't That might not be what you want (both because of extra work of read, the
+ // file modified stamp or other reasons, file is write only etc) NOTE! That this also does the
+ // work of the comparison after it is decoded, but the *bytes* might actually be different.
if (File::exists(fileName))
{
@@ -78,7 +87,7 @@ struct DiagnosticReporter
StreamWriter writer;
SLANG_RETURN_ON_FAIL(reporter.report(writer.init(stream)));
SLANG_RETURN_ON_FAIL(reporter.report(writer.write(text)))
- return SLANG_OK;
+ return SLANG_OK;
}
/* static */ void FileUtil::indent(Index indentCount, StringBuilder& out)
diff --git a/tools/slang-cpp-extractor/file-util.h b/tools/slang-cpp-extractor/file-util.h
index 01aafeedf..201825973 100644
--- a/tools/slang-cpp-extractor/file-util.h
+++ b/tools/slang-cpp-extractor/file-util.h
@@ -3,7 +3,8 @@
#include "diagnostics.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
// A macro to define a single indent as a string
@@ -11,15 +12,23 @@ using namespace Slang;
struct FileUtil
{
- /// Read text into outRead. Any failures written to sink (can be passed as nullptr, for no output)
- static SlangResult readAllText(const Slang::String& fileName, DiagnosticSink* sink, String& outRead);
- /// Write text to filename. Any failures written to sink. (can be passed as nullptr, for no output)
- static SlangResult writeAllText(const Slang::String& fileName, DiagnosticSink* sink, const UnownedStringSlice& text);
+ /// Read text into outRead. Any failures written to sink (can be passed as nullptr, for no
+ /// output)
+ static SlangResult readAllText(
+ const Slang::String& fileName,
+ DiagnosticSink* sink,
+ String& outRead);
+ /// Write text to filename. Any failures written to sink. (can be passed as nullptr, for no
+ /// output)
+ static SlangResult writeAllText(
+ const Slang::String& fileName,
+ DiagnosticSink* sink,
+ const UnownedStringSlice& text);
- /// Appends CPP_EXTRACT_INDENT_STRING indentCount number of times to out
+ /// Appends CPP_EXTRACT_INDENT_STRING indentCount number of times to out
static void indent(Index indentCount, StringBuilder& out);
};
-} // CppExtract
+} // namespace CppExtract
#endif
diff --git a/tools/slang-cpp-extractor/identifier-lookup.cpp b/tools/slang-cpp-extractor/identifier-lookup.cpp
index 6b60f573c..c7255aa1f 100644
--- a/tools/slang-cpp-extractor/identifier-lookup.cpp
+++ b/tools/slang-cpp-extractor/identifier-lookup.cpp
@@ -1,41 +1,42 @@
#include "identifier-lookup.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
-/* static */const IdentifierFlags IdentifierLookup::kIdentifierFlags[Index(IdentifierStyle::CountOf)] =
-{
- 0, /// None
- 0, /// Identifier
- 0, /// Declare type
- 0, /// Type set
- IdentifierFlag::Keyword, /// TypeModifier
- IdentifierFlag::Keyword, /// Keyword
+/* static */ const IdentifierFlags
+ IdentifierLookup::kIdentifierFlags[Index(IdentifierStyle::CountOf)] = {
+ 0, /// None
+ 0, /// Identifier
+ 0, /// Declare type
+ 0, /// Type set
+ IdentifierFlag::Keyword, /// TypeModifier
+ IdentifierFlag::Keyword, /// Keyword
- IdentifierFlag::Keyword | IdentifierFlag::StartScope | IdentifierFlag::ClassLike, /// Class
- IdentifierFlag::Keyword | IdentifierFlag::StartScope | IdentifierFlag::ClassLike, /// Struct
- IdentifierFlag::Keyword | IdentifierFlag::StartScope, /// Namespace
- IdentifierFlag::Keyword | IdentifierFlag::StartScope, /// Enum
+ IdentifierFlag::Keyword | IdentifierFlag::StartScope | IdentifierFlag::ClassLike, /// Class
+ IdentifierFlag::Keyword | IdentifierFlag::StartScope | IdentifierFlag::ClassLike, /// Struct
+ IdentifierFlag::Keyword | IdentifierFlag::StartScope, /// Namespace
+ IdentifierFlag::Keyword | IdentifierFlag::StartScope, /// Enum
- IdentifierFlag::Keyword, /// Typedef
+ IdentifierFlag::Keyword, /// Typedef
- IdentifierFlag::Keyword, /// Access
- IdentifierFlag::Reflection, /// Reflected
- IdentifierFlag::Reflection, /// Unreflected
+ IdentifierFlag::Keyword, /// Access
+ IdentifierFlag::Reflection, /// Reflected
+ IdentifierFlag::Reflection, /// Unreflected
- IdentifierFlag::Keyword, /// virtual
- 0, /// Calling convention
- IdentifierFlag::Keyword, /// template
- IdentifierFlag::Keyword, /// static
+ IdentifierFlag::Keyword, /// virtual
+ 0, /// Calling convention
+ IdentifierFlag::Keyword, /// template
+ IdentifierFlag::Keyword, /// static
- IdentifierFlag::Keyword, /// unsigned/signed
+ IdentifierFlag::Keyword, /// unsigned/signed
- IdentifierFlag::Keyword, /// extern
+ IdentifierFlag::Keyword, /// extern
- 0, /// Callable misc
- 0, /// IntegerType int, short, char, long
+ 0, /// Callable misc
+ 0, /// IntegerType int, short, char, long
- IdentifierFlag::Keyword, /// default
+ IdentifierFlag::Keyword, /// default
};
void IdentifierLookup::set(const UnownedStringSlice& name, IdentifierStyle style)
@@ -54,7 +55,7 @@ void IdentifierLookup::set(const UnownedStringSlice& name, IdentifierStyle style
}
}
-void IdentifierLookup::set(const char*const* names, size_t namesCount, IdentifierStyle style)
+void IdentifierLookup::set(const char* const* names, size_t namesCount, IdentifierStyle style)
{
for (size_t i = 0; i < namesCount; ++i)
{
@@ -77,20 +78,42 @@ void IdentifierLookup::initDefault(const UnownedStringSlice& markPrefix)
// Some keywords
{
- const char* names[] = { "continue", "if", "case", "break", "catch", "delete", "do", "else", "for", "new", "goto", "return", "switch", "throw", "using", "while", "operator", "explicit"};
+ const char* names[] = {
+ "continue",
+ "if",
+ "case",
+ "break",
+ "catch",
+ "delete",
+ "do",
+ "else",
+ "for",
+ "new",
+ "goto",
+ "return",
+ "switch",
+ "throw",
+ "using",
+ "while",
+ "operator",
+ "explicit"};
set(names, SLANG_COUNT_OF(names), IdentifierStyle::Keyword);
}
// Type modifier keywords
{
- const char* names[] = { "const", "volatile" };
+ const char* names[] = {"const", "volatile"};
set(names, SLANG_COUNT_OF(names), IdentifierStyle::TypeModifier);
}
// Special markers
{
- const char* names[] = { "PRE_DECLARE", "TYPE_SET", "REFLECTED", "UNREFLECTED" };
- const IdentifierStyle styles[] = { IdentifierStyle::PreDeclare, IdentifierStyle::TypeSet, IdentifierStyle::Reflected, IdentifierStyle::Unreflected };
+ const char* names[] = {"PRE_DECLARE", "TYPE_SET", "REFLECTED", "UNREFLECTED"};
+ const IdentifierStyle styles[] = {
+ IdentifierStyle::PreDeclare,
+ IdentifierStyle::TypeSet,
+ IdentifierStyle::Reflected,
+ IdentifierStyle::Unreflected};
SLANG_COMPILE_TIME_ASSERT(SLANG_COUNT_OF(names) == SLANG_COUNT_OF(styles));
StringBuilder buf;
@@ -104,7 +127,7 @@ void IdentifierLookup::initDefault(const UnownedStringSlice& markPrefix)
{
set("virtual", IdentifierStyle::Virtual);
-
+
set("template", IdentifierStyle::Template);
set("static", IdentifierStyle::Static);
set("extern", IdentifierStyle::Extern);
@@ -112,29 +135,28 @@ void IdentifierLookup::initDefault(const UnownedStringSlice& markPrefix)
}
{
- const char* names[] = { "char", "short", "int", "long"};
+ const char* names[] = {"char", "short", "int", "long"};
set(names, SLANG_COUNT_OF(names), IdentifierStyle::IntegerType);
}
{
- const char* names[] = { "SLANG_MCALL" };
+ const char* names[] = {"SLANG_MCALL"};
set(names, SLANG_COUNT_OF(names), IdentifierStyle::CallingConvention);
}
{
- const char* names[] = { "SLANG_NO_THROW", "inline"};
+ const char* names[] = {"SLANG_NO_THROW", "inline"};
set(names, SLANG_COUNT_OF(names), IdentifierStyle::CallableMisc);
}
// Keywords which introduce types/scopes
{
- const Pair pairs[] =
- {
- { "struct", IdentifierStyle::Struct },
- { "class", IdentifierStyle::Class },
- { "namespace", IdentifierStyle::Namespace },
- { "enum", IdentifierStyle::Enum },
- { "typedef", IdentifierStyle::TypeDef },
+ const Pair pairs[] = {
+ {"struct", IdentifierStyle::Struct},
+ {"class", IdentifierStyle::Class},
+ {"namespace", IdentifierStyle::Namespace},
+ {"enum", IdentifierStyle::Enum},
+ {"typedef", IdentifierStyle::TypeDef},
};
set(pairs, SLANG_COUNT_OF(pairs));
@@ -142,11 +164,11 @@ void IdentifierLookup::initDefault(const UnownedStringSlice& markPrefix)
// Keywords that control access
{
- const char* names[] = { "private", "protected", "public" };
+ const char* names[] = {"private", "protected", "public"};
set(names, SLANG_COUNT_OF(names), IdentifierStyle::Access);
}
{
- const char* names[] = { "signed", "unsigned"};
+ const char* names[] = {"signed", "unsigned"};
set(names, SLANG_COUNT_OF(names), IdentifierStyle::IntegerModifier);
}
diff --git a/tools/slang-cpp-extractor/identifier-lookup.h b/tools/slang-cpp-extractor/identifier-lookup.h
index 0d55ba65c..f26220f1f 100644
--- a/tools/slang-cpp-extractor/identifier-lookup.h
+++ b/tools/slang-cpp-extractor/identifier-lookup.h
@@ -3,49 +3,50 @@
#include "diagnostics.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
enum class IdentifierStyle
{
- None, ///< It's not an identifier
+ None, ///< It's not an identifier
- Identifier, ///< Just an identifier
+ Identifier, ///< Just an identifier
- PreDeclare, ///< Declare a type (not visible in C++ code)
- TypeSet, ///< TypeSet
+ PreDeclare, ///< Declare a type (not visible in C++ code)
+ TypeSet, ///< TypeSet
- TypeModifier, ///< const, volatile etc
- Keyword, ///< A keyword C/C++ keyword that is not another type
+ TypeModifier, ///< const, volatile etc
+ Keyword, ///< A keyword C/C++ keyword that is not another type
- Class, ///< class
- Struct, ///< struct
- Namespace, ///< namespace
- Enum, ///< enum
+ Class, ///< class
+ Struct, ///< struct
+ Namespace, ///< namespace
+ Enum, ///< enum
- TypeDef, ///< typedef
+ TypeDef, ///< typedef
- Access, ///< public, protected, private
+ Access, ///< public, protected, private
Reflected,
Unreflected,
- CallingConvention, ///< Used on a method
- Virtual, ///<
+ CallingConvention, ///< Used on a method
+ Virtual, ///<
Template,
- Static,
+ Static,
IntegerModifier,
Extern,
- CallableMisc, ///< For SLANG_NO_THROW etc
+ CallableMisc, ///< For SLANG_NO_THROW etc
- IntegerType, ///< Built in integer type
+ IntegerType, ///< Built in integer type
- Default, /// default
+ Default, /// default
CountOf,
};
@@ -55,8 +56,8 @@ struct IdentifierFlag
{
enum Enum : IdentifierFlags
{
- StartScope = 0x1, ///< namespace, struct or class
- ClassLike = 0x2, ///< Struct or class
+ StartScope = 0x1, ///< namespace, struct or class
+ ClassLike = 0x2, ///< Struct or class
Keyword = 0x4,
Reflection = 0x8,
};
@@ -66,7 +67,6 @@ struct IdentifierFlag
class IdentifierLookup
{
public:
-
struct Pair
{
const char* name;
@@ -79,14 +79,11 @@ public:
return (index >= 0) ? m_styles[index] : IdentifierStyle::None;
}
- void set(const char* name, IdentifierStyle style)
- {
- set(UnownedStringSlice(name), style);
- }
+ void set(const char* name, IdentifierStyle style) { set(UnownedStringSlice(name), style); }
void set(const UnownedStringSlice& name, IdentifierStyle style);
- void set(const char*const* names, size_t namesCount, IdentifierStyle style);
+ void set(const char* const* names, size_t namesCount, IdentifierStyle style);
void set(const Pair* pairs, Index pairsCount);
@@ -98,8 +95,8 @@ public:
void initDefault(const UnownedStringSlice& markPrefix);
- IdentifierLookup() :
- m_pool(StringSlicePool::Style::Empty)
+ IdentifierLookup()
+ : m_pool(StringSlicePool::Style::Empty)
{
SLANG_ASSERT(m_pool.getSlicesCount() == 0);
}
@@ -122,6 +119,6 @@ SLANG_FORCE_INLINE bool hasFlag(IdentifierStyle style, IdentifierFlag::Enum flag
return (getFlags(style) & flag) != 0;
}
-} // CppExtract
+} // namespace CppExtract
#endif
diff --git a/tools/slang-cpp-extractor/macro-writer.cpp b/tools/slang-cpp-extractor/macro-writer.cpp
index 285a91851..3f0e0a5fa 100644
--- a/tools/slang-cpp-extractor/macro-writer.cpp
+++ b/tools/slang-cpp-extractor/macro-writer.cpp
@@ -1,27 +1,27 @@
#include "macro-writer.h"
-#include "slang-com-helper.h"
-
#include "../../source/core/slang-list.h"
#include "../../source/core/slang-string.h"
-//#include "../../source/core/slang-string-util.h"
+#include "slang-com-helper.h"
+// #include "../../source/core/slang-string-util.h"
+#include "../../source/compiler-core/slang-diagnostic-sink.h"
#include "../../source/core/slang-io.h"
-
#include "../../source/core/slang-writer.h"
-
-#include "../../source/compiler-core/slang-diagnostic-sink.h"
-//#include "../../source/compiler-core/slang-name.h"
+// #include "../../source/compiler-core/slang-name.h"
#include "diagnostics.h"
-#include "options.h"
-#include "node-tree.h"
#include "file-util.h"
+#include "node-tree.h"
+#include "options.h"
namespace CppExtract
{
using namespace Slang;
-SLANG_FORCE_INLINE static void _indent(Index indentCount, StringBuilder& out) { return FileUtil::indent(indentCount, out); }
+SLANG_FORCE_INLINE static void _indent(Index indentCount, StringBuilder& out)
+{
+ return FileUtil::indent(indentCount, out);
+}
SlangResult MacroWriter::calcDef(NodeTree* tree, SourceOrigin* origin, StringBuilder& out)
{
@@ -31,12 +31,14 @@ SlangResult MacroWriter::calcDef(NodeTree* tree, SourceOrigin* origin, StringBui
{
if (auto classLikeNode = as<ClassLikeNode>(node))
{
- if (classLikeNode->m_marker.getContent().indexOf(UnownedStringSlice::fromLiteral("ABSTRACT")) >= 0)
+ if (classLikeNode->m_marker.getContent().indexOf(
+ UnownedStringSlice::fromLiteral("ABSTRACT")) >= 0)
{
out << "ABSTRACT_";
}
- out << "SYNTAX_CLASS(" << node->m_name.getContent() << ", " << classLikeNode->m_super.getContent() << ")\n";
+ out << "SYNTAX_CLASS(" << node->m_name.getContent() << ", "
+ << classLikeNode->m_super.getContent() << ")\n";
out << "END_SYNTAX_CLASS()\n\n";
}
}
@@ -55,23 +57,24 @@ SlangResult MacroWriter::calcChildrenHeader(NodeTree* tree, TypeSet* typeSet, St
List<ClassLikeNode*> classNodes;
for (Index i = 0; i < baseTypes.getCount(); ++i)
{
- ClassLikeNode* baseType = baseTypes[i];
+ ClassLikeNode* baseType = baseTypes[i];
baseType->calcDerivedDepthFirst(classNodes);
}
- //Node::filter(Node::isClassLike, nodes);
+ // Node::filter(Node::isClassLike, nodes);
List<ClassLikeNode*> derivedTypes;
out << "\n\n /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!! CHILDREN !!!!!!!!!!!!!!!!!!!!!!!!!!!! */ \n\n";
- // Now the children
+ // Now the children
for (ClassLikeNode* classNode : classNodes)
{
classNode->getReflectedDerivedTypes(derivedTypes);
// Define the derived types
- out << "#define " << m_options->m_markPrefix << "CHILDREN_" << reflectTypeName << "_" << classNode->m_name.getContent() << "(x, param)";
+ out << "#define " << m_options->m_markPrefix << "CHILDREN_" << reflectTypeName << "_"
+ << classNode->m_name.getContent() << "(x, param)";
if (derivedTypes.getCount())
{
@@ -80,12 +83,13 @@ SlangResult MacroWriter::calcChildrenHeader(NodeTree* tree, TypeSet* typeSet, St
{
Node* derivedType = derivedTypes[j];
_indent(1, out);
- out << m_options->m_markPrefix << "ALL_" << reflectTypeName << "_" << derivedType->m_name.getContent() << "(x, param)";
+ out << m_options->m_markPrefix << "ALL_" << reflectTypeName << "_"
+ << derivedType->m_name.getContent() << "(x, param)";
if (j < derivedTypes.getCount() - 1)
{
out << "\\\n";
}
- }
+ }
}
out << "\n\n";
}
@@ -95,16 +99,19 @@ SlangResult MacroWriter::calcChildrenHeader(NodeTree* tree, TypeSet* typeSet, St
for (ClassLikeNode* classNode : classNodes)
{
// Define the derived types
- out << "#define " << m_options->m_markPrefix << "ALL_" << reflectTypeName << "_" << classNode->m_name.getContent() << "(x, param) \\\n";
+ out << "#define " << m_options->m_markPrefix << "ALL_" << reflectTypeName << "_"
+ << classNode->m_name.getContent() << "(x, param) \\\n";
_indent(1, out);
- out << m_options->m_markPrefix << reflectTypeName << "_" << classNode->m_name.getContent() << "(x, param)";
+ out << m_options->m_markPrefix << reflectTypeName << "_" << classNode->m_name.getContent()
+ << "(x, param)";
// If has derived types output them
if (classNode->hasReflectedDerivedType())
{
out << " \\\n";
_indent(1, out);
- out << m_options->m_markPrefix << "CHILDREN_" << reflectTypeName << "_" << classNode->m_name.getContent() << "(x, param)";
+ out << m_options->m_markPrefix << "CHILDREN_" << reflectTypeName << "_"
+ << classNode->m_name.getContent() << "(x, param)";
}
out << "\n\n";
}
@@ -116,7 +123,8 @@ SlangResult MacroWriter::calcChildrenHeader(NodeTree* tree, TypeSet* typeSet, St
for (ClassLikeNode* classNode : classNodes)
{
// Define the derived types
- out << "#define " << m_options->m_markPrefix << "FIELDS_" << reflectTypeName << "_" << classNode->m_name.getContent() << "(_x_, _param_)";
+ out << "#define " << m_options->m_markPrefix << "FIELDS_" << reflectTypeName << "_"
+ << classNode->m_name.getContent() << "(_x_, _param_)";
// Find all of the instance fields fields
List<FieldNode*> fields;
@@ -137,10 +145,10 @@ SlangResult MacroWriter::calcChildrenHeader(NodeTree* tree, TypeSet* typeSet, St
const Index fieldsCount = fields.getCount();
bool previousField = false;
- for (Index j = 0; j < fieldsCount; ++j)
+ for (Index j = 0; j < fieldsCount; ++j)
{
const FieldNode* field = fields[j];
-
+
if (field->isReflected())
{
if (previousField)
@@ -150,14 +158,15 @@ SlangResult MacroWriter::calcChildrenHeader(NodeTree* tree, TypeSet* typeSet, St
_indent(1, out);
- // NOTE! We put the type field in brackets, such that there is no issue with templates containing a comma.
- // If stringified
- out << "_x_(" << field->m_name.getContent() << ", (" << field->m_fieldType << "), _param_)";
+ // NOTE! We put the type field in brackets, such that there is no issue with
+ // templates containing a comma. If stringified
+ out << "_x_(" << field->m_name.getContent() << ", (" << field->m_fieldType
+ << "), _param_)";
previousField = true;
}
}
}
-
+
out << "\n\n";
}
}
@@ -172,8 +181,9 @@ SlangResult MacroWriter::calcOriginHeader(NodeTree* tree, StringBuilder& out)
out << "// Origin macros\n\n";
for (SourceOrigin* origin : tree->getSourceOrigins())
- {
- out << "#define " << m_options->m_markPrefix << "ORIGIN_" << origin->m_macroOrigin << "(x, param) \\\n";
+ {
+ out << "#define " << m_options->m_markPrefix << "ORIGIN_" << origin->m_macroOrigin
+ << "(x, param) \\\n";
for (Node* node : origin->m_nodes)
{
@@ -279,14 +289,17 @@ SlangResult MacroWriter::calcTypeHeader(NodeTree* tree, TypeSet* typeSet, String
out << "// SUPER - is the super class name (or NO_SUPER)\n";
out << "// ORIGIN - where the definition was found\n";
out << "// LAST - is the class name for the last in the range (or NO_LAST)\n";
- out << "// MARKER - is the text inbetween in the prefix/postix (like ABSTRACT). If no inbetween text is is 'NONE'\n";
- out << "// TYPE - Can be BASE, INNER or LEAF for the overall base class, an INNER class, or a LEAF class\n";
+ out << "// MARKER - is the text inbetween in the prefix/postix (like ABSTRACT). If no "
+ "inbetween text is is 'NONE'\n";
+ out << "// TYPE - Can be BASE, INNER or LEAF for the overall base class, an INNER class, "
+ "or a LEAF class\n";
out << "// param is a user defined parameter that can be parsed to the invoked x macro\n\n";
// Output all of the definitions for each type
for (ClassLikeNode* node : nodes)
{
- out << "#define " << m_options->m_markPrefix << reflectTypeName << "_" << node->m_name.getContent() << "(x, param) ";
+ out << "#define " << m_options->m_markPrefix << reflectTypeName << "_"
+ << node->m_name.getContent() << "(x, param) ";
// Output the X macro part
_indent(1, out);
@@ -319,9 +332,12 @@ SlangResult MacroWriter::calcTypeHeader(NodeTree* tree, TypeSet* typeSet, String
// Output any specifics of the markup
UnownedStringSlice marker = node->m_marker.getContent();
// Need to extract the name
- if (marker.getLength() > m_options->m_markPrefix.getLength() + m_options->m_markSuffix.getLength())
+ if (marker.getLength() >
+ m_options->m_markPrefix.getLength() + m_options->m_markSuffix.getLength())
{
- marker = UnownedStringSlice(marker.begin() + m_options->m_markPrefix.getLength(), marker.end() - m_options->m_markSuffix.getLength());
+ marker = UnownedStringSlice(
+ marker.begin() + m_options->m_markPrefix.getLength(),
+ marker.end() - m_options->m_markSuffix.getLength());
}
else
{
@@ -417,7 +433,8 @@ SlangResult MacroWriter::writeOutput(NodeTree* tree)
StringBuilder headerPath;
headerPath << path << "-" << typeSet->m_fileMark << "." << ext;
- SLANG_RETURN_ON_FAIL(FileUtil::writeAllText(headerPath, m_sink, header.getUnownedSlice()));
+ SLANG_RETURN_ON_FAIL(
+ FileUtil::writeAllText(headerPath, m_sink, header.getUnownedSlice()));
}
{
@@ -426,7 +443,8 @@ SlangResult MacroWriter::writeOutput(NodeTree* tree)
StringBuilder headerPath;
headerPath << path << "-" << typeSet->m_fileMark << "-macro." + ext;
- SLANG_RETURN_ON_FAIL(FileUtil::writeAllText(headerPath, m_sink, childrenHeader.getUnownedSlice()));
+ SLANG_RETURN_ON_FAIL(
+ FileUtil::writeAllText(headerPath, m_sink, childrenHeader.getUnownedSlice()));
}
}
@@ -434,4 +452,3 @@ SlangResult MacroWriter::writeOutput(NodeTree* tree)
}
} // namespace CppExtract
-
diff --git a/tools/slang-cpp-extractor/macro-writer.h b/tools/slang-cpp-extractor/macro-writer.h
index b1754741d..0cbf85fb3 100644
--- a/tools/slang-cpp-extractor/macro-writer.h
+++ b/tools/slang-cpp-extractor/macro-writer.h
@@ -1,47 +1,43 @@
#ifndef CPP_EXTRACT_MACRO_WRITER_H
#define CPP_EXTRACT_MACRO_WRITER_H
+#include "../../source/compiler-core/slang-diagnostic-sink.h"
#include "diagnostics.h"
-
-#include "options.h"
#include "node-tree.h"
+#include "options.h"
-#include "../../source/compiler-core/slang-diagnostic-sink.h"
-
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
/* A class that writes out macros that define type hierarchies, as well as fields of types */
class MacroWriter
{
public:
-
- /// Write output
+ /// Write output
SlangResult writeOutput(NodeTree* tree);
- /// Write def files
+ /// Write def files
SlangResult writeDefs(NodeTree* tree);
- /// Calculate the header
+ /// Calculate the header
SlangResult calcTypeHeader(NodeTree* tree, TypeSet* typeSet, StringBuilder& out);
SlangResult calcChildrenHeader(NodeTree* tree, TypeSet* typeSet, StringBuilder& out);
SlangResult calcOriginHeader(NodeTree* tree, StringBuilder& out);
SlangResult calcDef(NodeTree* tree, SourceOrigin* origin, StringBuilder& out);
- /// Ctor.
- MacroWriter(DiagnosticSink* sink, const Options* options):
- m_sink(sink),
- m_options(options)
+ /// Ctor.
+ MacroWriter(DiagnosticSink* sink, const Options* options)
+ : m_sink(sink), m_options(options)
{
}
protected:
-
const Options* m_options = nullptr;
DiagnosticSink* m_sink;
};
-} // CppExtract
+} // namespace CppExtract
#endif
diff --git a/tools/slang-cpp-extractor/node-tree.cpp b/tools/slang-cpp-extractor/node-tree.cpp
index 546a54c27..6b543ad31 100644
--- a/tools/slang-cpp-extractor/node-tree.cpp
+++ b/tools/slang-cpp-extractor/node-tree.cpp
@@ -1,22 +1,24 @@
#include "node-tree.h"
-#include "options.h"
-#include "identifier-lookup.h"
-
#include "../../source/compiler-core/slang-name-convention-util.h"
-
#include "../../source/core/slang-io.h"
+#include "identifier-lookup.h"
+#include "options.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!! NodeTree !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
-NodeTree::NodeTree(StringSlicePool* typePool, NamePool* namePool, IdentifierLookup* identifierLookup):
- m_typePool(typePool),
- m_namePool(namePool),
- m_identifierLookup(identifierLookup),
- m_typeSetPool(StringSlicePool::Style::Empty)
+NodeTree::NodeTree(
+ StringSlicePool* typePool,
+ NamePool* namePool,
+ IdentifierLookup* identifierLookup)
+ : m_typePool(typePool)
+ , m_namePool(namePool)
+ , m_identifierLookup(identifierLookup)
+ , m_typeSetPool(StringSlicePool::Style::Empty)
{
m_rootNode = new ScopeNode(Node::Kind::Namespace);
m_rootNode->m_reflectionType = ReflectionType::Reflected;
@@ -52,7 +54,7 @@ TypeSet* NodeTree::getOrAddTypeSet(const UnownedStringSlice& slice)
SourceOrigin* NodeTree::addSourceOrigin(SourceFile* sourceFile, const Options& options)
{
- // Calculate from the path, a 'macro origin' name.
+ // Calculate from the path, a 'macro origin' name.
const String macroOrigin = calcMacroOrigin(sourceFile->getPathInfo().foundPath, options);
SourceOrigin* origin = new SourceOrigin(sourceFile, macroOrigin);
@@ -60,7 +62,7 @@ SourceOrigin* NodeTree::addSourceOrigin(SourceFile* sourceFile, const Options& o
return origin;
}
-/* static */String NodeTree::calcMacroOrigin(const String& filePath, const Options& options)
+/* static */ String NodeTree::calcMacroOrigin(const String& filePath, const Options& options)
{
// Get the filename without extension
String fileName = Path::getFileNameWithoutExt(filePath);
@@ -69,7 +71,8 @@ SourceOrigin* NodeTree::addSourceOrigin(SourceFile* sourceFile, const Options& o
UnownedStringSlice slice = fileName.getUnownedSlice();
// Filename prefix
- if (options.m_stripFilePrefix.getLength() && slice.startsWith(options.m_stripFilePrefix.getUnownedSlice()))
+ if (options.m_stripFilePrefix.getLength() &&
+ slice.startsWith(options.m_stripFilePrefix.getUnownedSlice()))
{
const Index len = options.m_stripFilePrefix.getLength();
slice = UnownedStringSlice(slice.begin() + len, slice.end());
@@ -94,7 +97,9 @@ SlangResult NodeTree::_calcDerivedTypesRec(ScopeNode* inScopeNode, DiagnosticSin
ScopeNode* parentScope = classLikeNode->m_parentScope;
if (parentScope == nullptr)
{
- sink->diagnoseRaw(Severity::Error, UnownedStringSlice::fromLiteral("Can't lookup in scope if there is none!"));
+ sink->diagnoseRaw(
+ Severity::Error,
+ UnownedStringSlice::fromLiteral("Can't lookup in scope if there is none!"));
return SLANG_FAIL;
}
@@ -104,7 +109,10 @@ SlangResult NodeTree::_calcDerivedTypesRec(ScopeNode* inScopeNode, DiagnosticSin
{
if (classLikeNode->isReflected())
{
- sink->diagnose(classLikeNode->m_name, CPPDiagnostics::superTypeNotFound, classLikeNode->getAbsoluteName());
+ sink->diagnose(
+ classLikeNode->m_name,
+ CPPDiagnostics::superTypeNotFound,
+ classLikeNode->getAbsoluteName());
return SLANG_FAIL;
}
}
@@ -114,17 +122,26 @@ SlangResult NodeTree::_calcDerivedTypesRec(ScopeNode* inScopeNode, DiagnosticSin
if (!superType)
{
- sink->diagnose(classLikeNode->m_name, CPPDiagnostics::superTypeNotAType, classLikeNode->getAbsoluteName());
+ sink->diagnose(
+ classLikeNode->m_name,
+ CPPDiagnostics::superTypeNotAType,
+ classLikeNode->getAbsoluteName());
return SLANG_FAIL;
}
if (superType->m_typeSet != classLikeNode->m_typeSet)
{
- sink->diagnose(classLikeNode->m_name, CPPDiagnostics::typeInDifferentTypeSet, classLikeNode->m_name.getContent(), classLikeNode->m_typeSet->m_macroName, superType->m_typeSet->m_macroName);
+ sink->diagnose(
+ classLikeNode->m_name,
+ CPPDiagnostics::typeInDifferentTypeSet,
+ classLikeNode->m_name.getContent(),
+ classLikeNode->m_typeSet->m_macroName,
+ superType->m_typeSet->m_macroName);
return SLANG_FAIL;
}
- // The base class must be defined in same scope (as we didn't allow different scopes for base classes)
+ // The base class must be defined in same scope (as we didn't allow different scopes
+ // for base classes)
superType->addDerived(classLikeNode);
}
}
diff --git a/tools/slang-cpp-extractor/node-tree.h b/tools/slang-cpp-extractor/node-tree.h
index b54321b09..f1547dbc1 100644
--- a/tools/slang-cpp-extractor/node-tree.h
+++ b/tools/slang-cpp-extractor/node-tree.h
@@ -1,31 +1,31 @@
#ifndef CPP_EXTRACT_NODE_TREE_H
#define CPP_EXTRACT_NODE_TREE_H
+#include "../../source/compiler-core/slang-lexer.h"
#include "diagnostics.h"
-#include "node.h"
#include "identifier-lookup.h"
+#include "node.h"
-#include "../../source/compiler-core/slang-lexer.h"
-
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
class TypeSet : public RefObject
{
public:
/// This is the looked up name.
- UnownedStringSlice m_macroName; ///< The name extracted from the macro SLANG_ABSTRACT_AST_CLASS -> AST
+ UnownedStringSlice
+ m_macroName; ///< The name extracted from the macro SLANG_ABSTRACT_AST_CLASS -> AST
- String m_typeName; ///< The enum type name associated with this type for AST it is ASTNode
- String m_fileMark; ///< This 'mark' becomes of the output filename
+ String m_typeName; ///< The enum type name associated with this type for AST it is ASTNode
+ String m_fileMark; ///< This 'mark' becomes of the output filename
- List<ClassLikeNode*> m_baseTypes; ///< The base types for this type set
+ List<ClassLikeNode*> m_baseTypes; ///< The base types for this type set
};
class SourceOrigin : public RefObject
{
public:
-
void addNode(Node* node)
{
if (auto classLike = as<ClassLikeNode>(node))
@@ -37,17 +37,18 @@ public:
m_nodes.add(node);
}
- SourceOrigin(SourceFile* sourceFile, const String& macroOrigin) :
- m_sourceFile(sourceFile),
- m_macroOrigin(macroOrigin)
- {}
+ SourceOrigin(SourceFile* sourceFile, const String& macroOrigin)
+ : m_sourceFile(sourceFile), m_macroOrigin(macroOrigin)
+ {
+ }
- String m_macroOrigin; ///< The macro text is inserted into the macro to identify the origin. It is based on the filename
- SourceFile* m_sourceFile; ///< The source file - also holds the path information
+ String m_macroOrigin; ///< The macro text is inserted into the macro to identify the origin. It
+ ///< is based on the filename
+ SourceFile* m_sourceFile; ///< The source file - also holds the path information
/// All of the nodes defined in this file in the order they were defined
/// Note that the same namespace may be listed multiple times.
- List<RefPtr<Node> > m_nodes;
+ List<RefPtr<Node>> m_nodes;
};
struct Options;
@@ -59,22 +60,23 @@ class NodeTree
{
public:
friend class Parser;
- /// Get all of the parsed source origins
- const List<RefPtr<SourceOrigin> >& getSourceOrigins() const { return m_sourceOrigins; }
+ /// Get all of the parsed source origins
+ const List<RefPtr<SourceOrigin>>& getSourceOrigins() const { return m_sourceOrigins; }
TypeSet* getTypeSet(const UnownedStringSlice& slice);
TypeSet* getOrAddTypeSet(const UnownedStringSlice& slice);
SourceOrigin* addSourceOrigin(SourceFile* sourceFile, const Options& options);
- /// Get all of the type sets
+ /// Get all of the type sets
const List<RefPtr<TypeSet>>& getTypeSets() const { return m_typeSets; }
- /// Get the root node
+ /// Get the root node
Node* getRootNode() const { return m_rootNode; }
- /// When parsing we don't lookup all up super types/add derived types. This is because
- /// we allow files to be processed in any order, so we have to do the type lookup as a separate operation
+ /// When parsing we don't lookup all up super types/add derived types. This is because
+ /// we allow files to be processed in any order, so we have to do the type lookup as a separate
+ /// operation
SlangResult calcDerivedTypes(DiagnosticSink* sink);
NodeTree(StringSlicePool* typePool, NamePool* namePool, IdentifierLookup* identifierLookup);
@@ -84,19 +86,19 @@ public:
protected:
SlangResult _calcDerivedTypesRec(ScopeNode* node, DiagnosticSink* sink);
- StringSlicePool m_typeSetPool; ///< Pool for type set names
- List<RefPtr<TypeSet> > m_typeSets; ///< The type sets
+ StringSlicePool m_typeSetPool; ///< Pool for type set names
+ List<RefPtr<TypeSet>> m_typeSets; ///< The type sets
IdentifierLookup* m_identifierLookup;
- StringSlicePool* m_typePool; ///< Pool for just types
+ StringSlicePool* m_typePool; ///< Pool for just types
NamePool* m_namePool;
- RefPtr<ScopeNode> m_rootNode; ///< The root scope
+ RefPtr<ScopeNode> m_rootNode; ///< The root scope
List<RefPtr<SourceOrigin>> m_sourceOrigins;
};
-} // CppExtract
+} // namespace CppExtract
#endif
diff --git a/tools/slang-cpp-extractor/node.cpp b/tools/slang-cpp-extractor/node.cpp
index 1189e3815..4598e34c9 100644
--- a/tools/slang-cpp-extractor/node.cpp
+++ b/tools/slang-cpp-extractor/node.cpp
@@ -1,15 +1,19 @@
#include "node.h"
-#include "file-util.h"
-
-#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-string-escape-util.h"
+#include "../../source/core/slang-string-util.h"
+#include "file-util.h"
-namespace CppExtract {
+namespace CppExtract
+{
-// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Node Impl !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Node Impl
+// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-SLANG_FORCE_INLINE static void _indent(Index indentCount, StringBuilder& out) { FileUtil::indent(indentCount, out); }
+SLANG_FORCE_INLINE static void _indent(Index indentCount, StringBuilder& out)
+{
+ FileUtil::indent(indentCount, out);
+}
void Node::dumpMarkup(int indentCount, StringBuilder& out)
{
@@ -93,7 +97,7 @@ void Node::calcAbsoluteName(StringBuilder& outName) const
}
}
-/* static */void Node::calcScopePath(Node* node, List<Node*>& outPath)
+/* static */ void Node::calcScopePath(Node* node, List<Node*>& outPath)
{
outPath.clear();
@@ -107,11 +111,11 @@ void Node::calcAbsoluteName(StringBuilder& outName) const
outPath.reverse();
}
-/* static */void Node::filterImpl(Filter inFilter, List<Node*>& ioNodes)
+/* static */ void Node::filterImpl(Filter inFilter, List<Node*>& ioNodes)
{
// Filter out all the unreflected nodes
Index count = ioNodes.getCount();
- for (Index j = 0; j < count; )
+ for (Index j = 0; j < count;)
{
Node* node = ioNodes[j];
@@ -127,7 +131,7 @@ void Node::calcAbsoluteName(StringBuilder& outName) const
}
}
-/* static */Node* Node::lookupNameInScope(ScopeNode* scope, const UnownedStringSlice& name)
+/* static */ Node* Node::lookupNameInScope(ScopeNode* scope, const UnownedStringSlice& name)
{
// TODO(JS): Doesn't handle 'using namespace'.
@@ -167,7 +171,10 @@ void Node::calcAbsoluteName(StringBuilder& outName) const
return nullptr;
}
-/* static */Node* Node::lookupFromScope(ScopeNode* scope, const UnownedStringSlice* parts, Index partsCount)
+/* static */ Node* Node::lookupFromScope(
+ ScopeNode* scope,
+ const UnownedStringSlice* parts,
+ Index partsCount)
{
SLANG_ASSERT(partsCount > 0);
if (partsCount == 1)
@@ -202,7 +209,9 @@ void Node::calcAbsoluteName(StringBuilder& outName) const
return nullptr;
}
-/* static */void Node::splitPath(const UnownedStringSlice& inPath, List<UnownedStringSlice>& outParts)
+/* static */ void Node::splitPath(
+ const UnownedStringSlice& inPath,
+ List<UnownedStringSlice>& outParts)
{
if (inPath.indexOf(UnownedStringSlice::fromLiteral("::")) >= 0)
{
@@ -220,7 +229,7 @@ void Node::calcAbsoluteName(StringBuilder& outName) const
}
}
-/* static */Node* Node::lookupFromScope(ScopeNode* scope, const UnownedStringSlice& inPath)
+/* static */ Node* Node::lookupFromScope(ScopeNode* scope, const UnownedStringSlice& inPath)
{
if (inPath.indexOf(UnownedStringSlice::fromLiteral("::")) >= 0)
{
@@ -235,7 +244,7 @@ void Node::calcAbsoluteName(StringBuilder& outName) const
}
}
-/* static */Node* Node::lookup(ScopeNode* scope, const UnownedStringSlice& inPath)
+/* static */ Node* Node::lookup(ScopeNode* scope, const UnownedStringSlice& inPath)
{
if (inPath.indexOf(UnownedStringSlice::fromLiteral("::")) >= 0)
{
@@ -341,11 +350,11 @@ void ScopeNode::dump(int indentCount, StringBuilder& out)
switch (m_kind)
{
- case Kind::AnonymousNamespace:
+ case Kind::AnonymousNamespace:
{
out << "namespace {\n";
}
- case Kind::Namespace:
+ case Kind::Namespace:
{
if (m_name.hasContent())
{
@@ -379,7 +388,7 @@ static bool _needsSpace(const Token& prevTok, const Token& tok)
auto loc = tok.getLoc();
auto prevContent = prevTok.getContent();
-
+
if (prevLoc + prevContent.getLength() == loc)
{
return false;
@@ -477,7 +486,7 @@ void EnumNode::dump(int indent, StringBuilder& out)
}
if (m_backingTokens.getCount() > 0)
- {
+ {
out << " : ";
_dumpTokens(m_backingTokens, out);
}
diff --git a/tools/slang-cpp-extractor/node.h b/tools/slang-cpp-extractor/node.h
index 8455588ad..3590aa5ce 100644
--- a/tools/slang-cpp-extractor/node.h
+++ b/tools/slang-cpp-extractor/node.h
@@ -1,11 +1,11 @@
#ifndef CPP_EXTRACT_NODE_H
#define CPP_EXTRACT_NODE_H
-#include "diagnostics.h"
-
#include "../../source/compiler-core/slang-doc-extractor.h"
+#include "diagnostics.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
enum class ReflectionType : uint8_t
@@ -30,7 +30,7 @@ public:
StructType,
ClassType,
- Enum,
+ Enum,
EnumClass,
Namespace,
@@ -41,10 +41,10 @@ public:
TypeDef,
- Callable, ///< Functions/methods
+ Callable, ///< Functions/methods
- Other, ///< Used 'other' parsing like for TYPE
- Unknown, ///< Used for marking tokens consumed but usage is not known
+ Other, ///< Used 'other' parsing like for TYPE
+ Unknown, ///< Used for marking tokens consumed but usage is not known
CountOf,
};
@@ -67,35 +67,57 @@ public:
EnumEnd = int(Kind::EnumClass),
};
- /// Returns true if kind can cast to this type
- /// Used for implementing as<T> casting
- static bool isOfKind(Kind kind) { SLANG_UNUSED(kind); return true; }
+ /// Returns true if kind can cast to this type
+ /// Used for implementing as<T> casting
+ static bool isOfKind(Kind kind)
+ {
+ SLANG_UNUSED(kind);
+ return true;
+ }
- static bool isKindScope(Kind kind) { return int(kind) >= int(KindRange::ScopeStart) && int(kind) <= int(KindRange::ScopeEnd); }
- static bool isKindClassLike(Kind kind) { return int(kind) >= int(KindRange::ClassLikeStart) && int(kind) <= int(KindRange::ClassLikeEnd); }
- static bool isKindEnumLike(Kind kind) { return int(kind) >= int(KindRange::EnumStart) && int(kind) <= int(KindRange::EnumEnd); }
+ static bool isKindScope(Kind kind)
+ {
+ return int(kind) >= int(KindRange::ScopeStart) && int(kind) <= int(KindRange::ScopeEnd);
+ }
+ static bool isKindClassLike(Kind kind)
+ {
+ return int(kind) >= int(KindRange::ClassLikeStart) &&
+ int(kind) <= int(KindRange::ClassLikeEnd);
+ }
+ static bool isKindEnumLike(Kind kind)
+ {
+ return int(kind) >= int(KindRange::EnumStart) && int(kind) <= int(KindRange::EnumEnd);
+ }
- /// It a type, but doesn't have a scope
- static bool isKindOtherType(Kind kind) { return int(kind) >= int(KindRange::OtherTypeStart) && int(kind) <= int(KindRange::OtherTypeEnd); }
- /// Is a type and has a scope
- static bool isKindScopeType(Kind kind) { return int(kind) >= int(KindRange::ScopeTypeStart) && int(kind) <= int(KindRange::ScopeTypeEnd); }
+ /// It a type, but doesn't have a scope
+ static bool isKindOtherType(Kind kind)
+ {
+ return int(kind) >= int(KindRange::OtherTypeStart) &&
+ int(kind) <= int(KindRange::OtherTypeEnd);
+ }
+ /// Is a type and has a scope
+ static bool isKindScopeType(Kind kind)
+ {
+ return int(kind) >= int(KindRange::ScopeTypeStart) &&
+ int(kind) <= int(KindRange::ScopeTypeEnd);
+ }
- /// True if the kind is any type
+ /// True if the kind is any type
static bool isKindType(Kind kind) { return isKindOtherType(kind) || isKindScopeType(kind); }
- /// True if the kind can accept contained types
+ /// True if the kind can accept contained types
static bool canKindContainTypes(Kind type)
{
switch (type)
{
- case Kind::StructType:
- case Kind::ClassType:
- case Kind::Namespace:
- case Kind::AnonymousNamespace:
+ case Kind::StructType:
+ case Kind::ClassType:
+ case Kind::Namespace:
+ case Kind::AnonymousNamespace:
{
return true;
}
- default: break;
+ default: break;
}
return false;
}
@@ -105,73 +127,86 @@ public:
bool isScope() const { return isKindScope(m_kind); }
bool isEnumLike() const { return isKindEnumLike(m_kind); }
- /// These are useful for the filter
- static bool isClassLikeAndReflected(Node* node) { return node->isClassLike() && node->isReflected(); }
+ /// These are useful for the filter
+ static bool isClassLikeAndReflected(Node* node)
+ {
+ return node->isClassLike() && node->isReflected();
+ }
static bool isClassLike(Node* node) { return isKindClassLike(node->m_kind); }
virtual void dump(int indent, StringBuilder& out) = 0;
- /// Do depth first traversal of nodes in scopes
+ /// Do depth first traversal of nodes in scopes
virtual void calcScopeDepthFirst(List<Node*>& outNodes);
- /// Calculate the absolute name for this namespace/type
+ /// Calculate the absolute name for this namespace/type
void calcAbsoluteName(StringBuilder& outName) const;
- /// Get the absolute name
- String getAbsoluteName() const { StringBuilder buf; calcAbsoluteName(buf); return buf.produceString(); }
+ /// Get the absolute name
+ String getAbsoluteName() const
+ {
+ StringBuilder buf;
+ calcAbsoluteName(buf);
+ return buf.produceString();
+ }
- /// Calculate the scope path to this node, from the root
+ /// Calculate the scope path to this node, from the root
void calcScopePath(List<Node*>& outPath) { calcScopePath(this, outPath); }
- /// True if reflected
+ /// True if reflected
bool isReflected() const { return m_reflectionType == ReflectionType::Reflected; }
SourceLoc getSourceLoc() const { return m_name.getLoc(); }
ScopeNode* getRootScope();
- typedef bool(*Filter)(Node* node);
-
- template <typename T>
- static void filter(Filter filter, List<T*>& io) { const Node* _isNodeDerived = (T*)nullptr; SLANG_UNUSED(_isNodeDerived); filterImpl(filter, reinterpret_cast<List<Node*>&>(io)); }
+ typedef bool (*Filter)(Node* node);
+
+ template<typename T>
+ static void filter(Filter filter, List<T*>& io)
+ {
+ const Node* _isNodeDerived = (T*)nullptr;
+ SLANG_UNUSED(_isNodeDerived);
+ filterImpl(filter, reinterpret_cast<List<Node*>&>(io));
+ }
static void filterImpl(Filter filter, List<Node*>& io);
static void calcScopePath(Node* node, List<Node*>& outPath);
- /// Lookup a name in just the specified scope
- /// Handles anonymous namespaces, or name lookups that are in the parents space
+ /// Lookup a name in just the specified scope
+ /// Handles anonymous namespaces, or name lookups that are in the parents space
static Node* lookupNameInScope(ScopeNode* scope, const UnownedStringSlice& name);
- /// Lookup from a path
+ /// Lookup from a path
static Node* lookupFromScope(ScopeNode* scope, const UnownedStringSlice* path, Index pathCount);
- /// Looks up *just* from the specified scope.
+ /// Looks up *just* from the specified scope.
static Node* lookupFromScope(ScopeNode* scope, const UnownedStringSlice& slice);
- /// Look up name (which can contain ::)
+ /// Look up name (which can contain ::)
static Node* lookup(ScopeNode* scope, const UnownedStringSlice& name);
static void splitPath(const UnownedStringSlice& slice, List<UnownedStringSlice>& outSplitPath);
- /// If markup is specified dump it
+ /// If markup is specified dump it
void dumpMarkup(int indent, StringBuilder& out);
- Node(Kind type) :
- m_kind(type),
- m_parentScope(nullptr),
- m_reflectionType(ReflectionType::NotReflected)
+ Node(Kind type)
+ : m_kind(type), m_parentScope(nullptr), m_reflectionType(ReflectionType::NotReflected)
{
}
- Kind m_kind; ///< The kind of node this is
- ReflectionType m_reflectionType; ///< Classes can be traversed, but not reflected. To be reflected they have to contain the marker
-
- MarkupVisibility m_markupVisibility = MarkupVisibility::Public; ///< The visibility of the markup
- String m_markup; ///< Documentation associated with this node
+ Kind m_kind; ///< The kind of node this is
+ ReflectionType m_reflectionType; ///< Classes can be traversed, but not reflected. To be
+ ///< reflected they have to contain the marker
+
+ MarkupVisibility m_markupVisibility =
+ MarkupVisibility::Public; ///< The visibility of the markup
+ String m_markup; ///< Documentation associated with this node
- Token m_name; ///< The name of this scope/type
+ Token m_name; ///< The name of this scope/type
- ScopeNode* m_parentScope; ///< The scope this type/scope is defined in
+ ScopeNode* m_parentScope; ///< The scope this type/scope is defined in
};
struct ScopeNode : public Node
@@ -183,33 +218,37 @@ struct ScopeNode : public Node
virtual void dump(int indent, StringBuilder& out) SLANG_OVERRIDE;
virtual void calcScopeDepthFirst(List<Node*>& outNodes) SLANG_OVERRIDE;
- /// True if can contain callable entries
+ /// True if can contain callable entries
bool canContainCallable() const { return isClassLike() || isNamespace(); }
- /// True if can accept fields (class like types can)
+ /// True if can accept fields (class like types can)
bool canContainFields() const { return isClassLike(); }
- /// True if the scope can accept types
+ /// True if the scope can accept types
bool canContainTypes() const { return canKindContainTypes(m_kind); }
- /// Gets the reflection for any contained types
- ReflectionType getContainedReflectionType() const { return m_reflectionType == ReflectionType::NotReflected ? ReflectionType::NotReflected : m_reflectionOverride; }
+ /// Gets the reflection for any contained types
+ ReflectionType getContainedReflectionType() const
+ {
+ return m_reflectionType == ReflectionType::NotReflected ? ReflectionType::NotReflected
+ : m_reflectionOverride;
+ }
- /// Add a child node to this nodes scope
+ /// Add a child node to this nodes scope
void addChild(Node* child);
- /// Adds the child but does not add the name to the map
+ /// Adds the child but does not add the name to the map
void addChildIgnoringName(Node* child);
- /// Find a child node in this scope with the specified name. Return nullptr if not found
+ /// Find a child node in this scope with the specified name. Return nullptr if not found
Node* findChild(const UnownedStringSlice& name) const;
- /// Gets the anonymous namespace associated with this scope
+ /// Gets the anonymous namespace associated with this scope
ScopeNode* getAnonymousNamespace();
- ScopeNode(Kind kind) :
- Super(kind),
- m_reflectionOverride(ReflectionType::Reflected),
- m_anonymousNamespace(nullptr)
+ ScopeNode(Kind kind)
+ : Super(kind)
+ , m_reflectionOverride(ReflectionType::Reflected)
+ , m_anonymousNamespace(nullptr)
{
}
@@ -234,8 +273,8 @@ struct FieldNode : public Node
virtual void dump(int indent, StringBuilder& out) SLANG_OVERRIDE;
- FieldNode() :
- Super(Kind::Field)
+ FieldNode()
+ : Super(Kind::Field)
{
}
@@ -252,49 +291,48 @@ struct ClassLikeNode : public ScopeNode
static bool isOfKind(Kind kind) { return isKindClassLike(kind); }
- /// Add a node that is derived from this
+ /// Add a node that is derived from this
void addDerived(ClassLikeNode* derived);
- /// Dump all of the derived types
+ /// Dump all of the derived types
void dumpDerived(int indentCount, StringBuilder& out);
- /// Calculates the derived depth
+ /// Calculates the derived depth
Index calcDerivedDepth() const;
- /// Find the last (reflected) derived type
+ /// Find the last (reflected) derived type
ClassLikeNode* findLastDerived();
- /// Traverse the hierarchy of derived nodes, in depth first order
+ /// Traverse the hierarchy of derived nodes, in depth first order
void calcDerivedDepthFirst(List<ClassLikeNode*>& outNodes);
- /// True if has a derived type that is reflected
+ /// True if has a derived type that is reflected
bool hasReflectedDerivedType() const;
- /// Stores in out any reflected derived types
+ /// Stores in out any reflected derived types
void getReflectedDerivedTypes(List<ClassLikeNode*>& out) const;
// Node Impl
virtual void dump(int indent, StringBuilder& out) SLANG_OVERRIDE;
- ClassLikeNode(Kind kind) :
- Super(kind),
- m_origin(nullptr),
- m_typeSet(nullptr),
- m_superNode(nullptr)
+ ClassLikeNode(Kind kind)
+ : Super(kind), m_origin(nullptr), m_typeSet(nullptr), m_superNode(nullptr)
{
SLANG_ASSERT(kind == Kind::ClassType || kind == Kind::StructType);
}
- SourceOrigin* m_origin; ///< Defines where this was uniquely defined.
+ SourceOrigin* m_origin; ///< Defines where this was uniquely defined.
- Token m_marker; ///< The marker associated with this scope (typically the marker is SLANG_CLASS etc, that is used to identify reflectedType)
+ Token m_marker; ///< The marker associated with this scope (typically the marker is SLANG_CLASS
+ ///< etc, that is used to identify reflectedType)
- List<RefPtr<ClassLikeNode>> m_derivedTypes; ///< All of the types derived from this type
+ List<RefPtr<ClassLikeNode>> m_derivedTypes; ///< All of the types derived from this type
- TypeSet* m_typeSet; ///< The typeset this type belongs to.
+ TypeSet* m_typeSet; ///< The typeset this type belongs to.
- Token m_super; ///< Super class name
- ClassLikeNode* m_superNode; ///< If this is a class/struct, the type it is derived from (or nullptr if base)
+ Token m_super; ///< Super class name
+ ClassLikeNode* m_superNode; ///< If this is a class/struct, the type it is derived from (or
+ ///< nullptr if base)
};
struct CallableNode : public Node
@@ -305,7 +343,10 @@ struct CallableNode : public Node
virtual void dump(int indent, StringBuilder& out) SLANG_OVERRIDE;
- CallableNode() :Super(Kind::Callable) {}
+ CallableNode()
+ : Super(Kind::Callable)
+ {
+ }
struct Param
{
@@ -332,8 +373,8 @@ struct EnumCaseNode : public Node
virtual void dump(int indent, StringBuilder& out) SLANG_OVERRIDE;
- EnumCaseNode():
- Super(Kind::EnumCase)
+ EnumCaseNode()
+ : Super(Kind::EnumCase)
{
}
@@ -348,8 +389,8 @@ struct EnumNode : public ScopeNode
virtual void dump(int indent, StringBuilder& out) SLANG_OVERRIDE;
- EnumNode(Kind kind):
- Super(kind)
+ EnumNode(Kind kind)
+ : Super(kind)
{
SLANG_ASSERT(isKindEnumLike(kind));
}
@@ -364,17 +405,20 @@ struct TypeDefNode : public Node
virtual void dump(int indent, StringBuilder& out) SLANG_OVERRIDE;
- TypeDefNode():
- Super(Kind::TypeDef)
+ TypeDefNode()
+ : Super(Kind::TypeDef)
{
}
List<Token> m_targetTypeTokens;
};
-template <typename T>
-T* as(Node* node) { return (node && T::isOfKind(node->m_kind)) ? static_cast<T*>(node) : nullptr; }
+template<typename T>
+T* as(Node* node)
+{
+ return (node && T::isOfKind(node->m_kind)) ? static_cast<T*>(node) : nullptr;
+}
-} // CppExtract
+} // namespace CppExtract
#endif
diff --git a/tools/slang-cpp-extractor/options.cpp b/tools/slang-cpp-extractor/options.cpp
index 90639da38..17ff5eebc 100644
--- a/tools/slang-cpp-extractor/options.cpp
+++ b/tools/slang-cpp-extractor/options.cpp
@@ -2,7 +2,8 @@
#include "diagnostics.h"
-namespace CppExtract {
+namespace CppExtract
+{
SlangResult OptionsParser::_parseArgFlag(const char* option, bool& outFlag)
{
@@ -52,7 +53,11 @@ SlangResult OptionsParser::_parseArgReplaceValue(const char* option, String& ioV
return SLANG_OK;
}
-SlangResult OptionsParser::parse(int argc, const char*const* argv, DiagnosticSink* sink, Options& outOptions)
+SlangResult OptionsParser::parse(
+ int argc,
+ const char* const* argv,
+ DiagnosticSink* sink,
+ Options& outOptions)
{
outOptions.reset();
@@ -86,12 +91,14 @@ SlangResult OptionsParser::parse(int argc, const char*const* argv, DiagnosticSin
}
else if (arg == "-mark-prefix")
{
- SLANG_RETURN_ON_FAIL(_parseArgReplaceValue("-mark-prefix", outOptions.m_markPrefix));
+ SLANG_RETURN_ON_FAIL(
+ _parseArgReplaceValue("-mark-prefix", outOptions.m_markPrefix));
continue;
}
else if (arg == "-mark-suffix")
{
- SLANG_RETURN_ON_FAIL(_parseArgReplaceValue("-mark-suffix", outOptions.m_markSuffix));
+ SLANG_RETURN_ON_FAIL(
+ _parseArgReplaceValue("-mark-suffix", outOptions.m_markSuffix));
continue;
}
else if (arg == "-defs")
@@ -106,7 +113,8 @@ SlangResult OptionsParser::parse(int argc, const char*const* argv, DiagnosticSin
}
else if (arg == "-strip-prefix")
{
- SLANG_RETURN_ON_FAIL(_parseArgWithValue("-strip-prefix", outOptions.m_stripFilePrefix));
+ SLANG_RETURN_ON_FAIL(
+ _parseArgWithValue("-strip-prefix", outOptions.m_stripFilePrefix));
continue;
}
else if (arg == "-unit-test")
diff --git a/tools/slang-cpp-extractor/options.h b/tools/slang-cpp-extractor/options.h
index e660bc376..8231d5e3b 100644
--- a/tools/slang-cpp-extractor/options.h
+++ b/tools/slang-cpp-extractor/options.h
@@ -3,7 +3,8 @@
#include "../../source/slang/slang-diagnostics.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
@@ -11,10 +12,7 @@ using namespace Slang;
struct Options
{
- void reset()
- {
- *this = Options();
- }
+ void reset() { *this = Options(); }
Options()
{
@@ -22,28 +20,34 @@ struct Options
m_markSuffix = "_CLASS";
}
- bool m_defs = false; ///< If set will output a '-defs.h' file for each of the input files, that corresponds to previous defs files (although doesn't have fields/RAW)
- bool m_dump = false; ///< If true will dump to stderr the types/fields and hierarchy it extracted
- bool m_runUnitTests = false; ///< If true will run internal unit tests
- bool m_extractDoc = true; ///< If set will try to extract documentation associated with nodes
+ bool m_defs = false; ///< If set will output a '-defs.h' file for each of the input files, that
+ ///< corresponds to previous defs files (although doesn't have fields/RAW)
+ bool m_dump =
+ false; ///< If true will dump to stderr the types/fields and hierarchy it extracted
+ bool m_runUnitTests = false; ///< If true will run internal unit tests
+ bool m_extractDoc = true; ///< If set will try to extract documentation associated with nodes
- bool m_outputFields = false; ///< When dumping macros also dump field definitions
+ bool m_outputFields = false; ///< When dumping macros also dump field definitions
bool m_requireMark = true;
- List<String> m_inputPaths; ///< The input paths to the files to be processed
+ List<String> m_inputPaths; ///< The input paths to the files to be processed
- String m_outputPath; ///< The output path. Note that the extractor can generate multiple output files, and this will actually be the 'stem' of several files
+ String m_outputPath; ///< The output path. Note that the extractor can generate multiple output
+ ///< files, and this will actually be the 'stem' of several files
- String m_inputDirectory; ///< The input directory that is by default used for reading m_inputPaths from.
- String m_markPrefix; ///< The prefix of the 'marker' used to identify a reflected type
- String m_markSuffix; ///< The postfix of the 'marker' used to identify a reflected type
- String m_stripFilePrefix; ///< Used for the 'origin' information, this is stripped from the source filename, and the remainder of the filename (without extension) is 'macroized'
+ String m_inputDirectory; ///< The input directory that is by default used for reading
+ ///< m_inputPaths from.
+ String m_markPrefix; ///< The prefix of the 'marker' used to identify a reflected type
+ String m_markSuffix; ///< The postfix of the 'marker' used to identify a reflected type
+ String m_stripFilePrefix; ///< Used for the 'origin' information, this is stripped from the
+ ///< source filename, and the remainder of the filename (without
+ ///< extension) is 'macroized'
};
struct OptionsParser
{
/// Parse the parameters. NOTE! Must have the program path removed
- SlangResult parse(int argc, const char*const* argv, DiagnosticSink* sink, Options& outOptions);
+ SlangResult parse(int argc, const char* const* argv, DiagnosticSink* sink, Options& outOptions);
SlangResult _parseArgWithValue(const char* option, String& outValue);
SlangResult _parseArgReplaceValue(const char* option, String& outValue);
@@ -53,11 +57,11 @@ struct OptionsParser
Index m_index;
Int m_argCount;
- const char*const* m_args;
+ const char* const* m_args;
DiagnosticSink* m_sink;
};
-} // CppExtract
+} // namespace CppExtract
#endif
diff --git a/tools/slang-cpp-extractor/parser.cpp b/tools/slang-cpp-extractor/parser.cpp
index 7ceb91824..a76965508 100644
--- a/tools/slang-cpp-extractor/parser.cpp
+++ b/tools/slang-cpp-extractor/parser.cpp
@@ -1,14 +1,13 @@
#include "parser.h"
-#include "options.h"
-#include "identifier-lookup.h"
-
#include "../../source/compiler-core/slang-name-convention-util.h"
-
-#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-string-util.h"
+#include "identifier-lookup.h"
+#include "options.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
// If fails then we need more bits to identify types
@@ -16,14 +15,11 @@ SLANG_COMPILE_TIME_ASSERT(int(Node::Kind::CountOf) <= 8 * sizeof(uint32_t));
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Parser !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-Parser::Parser(NodeTree* nodeTree, DiagnosticSink* sink) :
- m_sink(sink),
- m_nodeTree(nodeTree),
- m_nodeTypeEnabled(0)
+Parser::Parser(NodeTree* nodeTree, DiagnosticSink* sink)
+ : m_sink(sink), m_nodeTree(nodeTree), m_nodeTypeEnabled(0)
{
// Enable types by default
- const Node::Kind defaultEnabled[] =
- {
+ const Node::Kind defaultEnabled[] = {
Node::Kind::ClassType,
Node::Kind::StructType,
Node::Kind::Namespace,
@@ -62,7 +58,8 @@ void Parser::setKindsEnabled(const Node::Kind* kinds, Index kindsCount, bool isE
bool Parser::_isMarker(const UnownedStringSlice& name)
{
- return name.startsWith(m_options->m_markPrefix.getUnownedSlice()) && name.endsWith(m_options->m_markSuffix.getUnownedSlice());
+ return name.startsWith(m_options->m_markPrefix.getUnownedSlice()) &&
+ name.endsWith(m_options->m_markSuffix.getUnownedSlice());
}
SlangResult Parser::expect(TokenType type, Token* outToken)
@@ -117,7 +114,8 @@ bool Parser::advanceIfStyle(IdentifierStyle style, Token* outToken)
{
if (m_reader.peekTokenType() == TokenType::Identifier)
{
- IdentifierStyle readStyle = m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
+ IdentifierStyle readStyle =
+ m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
if (readStyle == style)
{
Token token = m_reader.advanceToken();
@@ -152,7 +150,7 @@ SlangResult Parser::pushScope(ScopeNode* scopeNode)
// We can only have one 'special' scope.
SLANG_ASSERT(scopeNode || m_scopeStack.getLast());
- // We keep to track.
+ // We keep to track.
m_scopeStack.add(scopeNode);
// If we pass nullptr, we don't update the current scope.
@@ -168,15 +166,21 @@ SlangResult Parser::pushScope(ScopeNode* scopeNode)
if (scopeNode->m_name.hasContent())
{
- // For anonymous namespace, we should look if we already have one and just reopen that. Doing so will mean will
- // find anonymous namespace clashes
+ // For anonymous namespace, we should look if we already have one and just reopen that.
+ // Doing so will mean will find anonymous namespace clashes
if (Node* foundNode = m_currentScope->findChild(scopeNode->m_name.getContent()))
{
if (scopeNode->isClassLike())
{
- m_sink->diagnose(m_reader.peekToken(), CPPDiagnostics::typeAlreadyDeclared, scopeNode->m_name.getContent());
- m_sink->diagnose(foundNode->m_name, CPPDiagnostics::seeDeclarationOf, scopeNode->m_name.getContent());
+ m_sink->diagnose(
+ m_reader.peekToken(),
+ CPPDiagnostics::typeAlreadyDeclared,
+ scopeNode->m_name.getContent());
+ m_sink->diagnose(
+ foundNode->m_name,
+ CPPDiagnostics::seeDeclarationOf,
+ scopeNode->m_name.getContent());
return SLANG_FAIL;
}
@@ -185,15 +189,18 @@ SlangResult Parser::pushScope(ScopeNode* scopeNode)
if (foundNode->m_kind != scopeNode->m_kind)
{
// Different types can't work
- m_sink->diagnose(m_reader.peekToken(), CPPDiagnostics::typeAlreadyDeclared, scopeNode->m_name.getContent());
+ m_sink->diagnose(
+ m_reader.peekToken(),
+ CPPDiagnostics::typeAlreadyDeclared,
+ scopeNode->m_name.getContent());
return SLANG_FAIL;
}
ScopeNode* foundScopeNode = as<ScopeNode>(foundNode);
SLANG_ASSERT(foundScopeNode);
- // Make sure the node is empty, as we are *not* going to add it, we are just going to use
- // the pre-existing namespace
+ // Make sure the node is empty, as we are *not* going to add it, we are just going
+ // to use the pre-existing namespace
SLANG_ASSERT(scopeNode->m_children.getCount() == 0);
// We can just use the pre-existing namespace
@@ -224,7 +231,7 @@ SlangResult Parser::popScope()
{
return SLANG_OK;
}
-
+
m_currentScope = m_currentScope->m_parentScope;
return SLANG_OK;
}
@@ -242,7 +249,7 @@ SlangResult Parser::_maybeConsumeScope()
}
else if (type == TokenType::LBrace)
{
- //m_reader.advanceToken();
+ // m_reader.advanceToken();
return consumeToClosingBrace();
}
else if (type == TokenType::EndOfFile)
@@ -271,23 +278,23 @@ SlangResult Parser::consumeToClosingBrace(const Token* inOpenBraceToken)
{
switch (m_reader.peekTokenType())
{
- case TokenType::EndOfFile:
+ case TokenType::EndOfFile:
{
m_sink->diagnose(m_reader.peekLoc(), CPPDiagnostics::didntFindMatchingBrace);
m_sink->diagnose(openToken, CPPDiagnostics::seeOpen);
return SLANG_FAIL;
}
- case TokenType::LBrace:
+ case TokenType::LBrace:
{
SLANG_RETURN_ON_FAIL(consumeToClosingBrace());
break;
}
- case TokenType::RBrace:
+ case TokenType::RBrace:
{
m_reader.advanceToken();
return SLANG_OK;
}
- default:
+ default:
{
m_reader.advanceToken();
break;
@@ -331,7 +338,10 @@ SlangResult Parser::_parseEnum()
}
else
{
- m_sink->diagnose(nameToken.loc, CPPDiagnostics::expectingIdentifier, nameToken.getContent());
+ m_sink->diagnose(
+ nameToken.loc,
+ CPPDiagnostics::expectingIdentifier,
+ nameToken.getContent());
return SLANG_FAIL;
}
}
@@ -348,8 +358,7 @@ SlangResult Parser::_parseEnum()
while (true)
{
TokenType tokenType = m_reader.peekTokenType();
- if (tokenType == TokenType::Semicolon ||
- tokenType == TokenType::LBrace ||
+ if (tokenType == TokenType::Semicolon || tokenType == TokenType::LBrace ||
tokenType == TokenType::EndOfFile)
{
break;
@@ -358,9 +367,9 @@ SlangResult Parser::_parseEnum()
backingTokens.add(m_reader.advanceToken());
}
- // TODO - Look up the backing type. It can only be an integral. We can assume it must be defined before lookup
- // for our uses here.
- // If we can't find the type, we could assume it's size is undefined
+ // TODO - Look up the backing type. It can only be an integral. We can assume it must be
+ // defined before lookup for our uses here. If we can't find the type, we could assume it's
+ // size is undefined
if (backingTokens.getCount() > 0)
{
@@ -377,13 +386,17 @@ SlangResult Parser::_parseEnum()
Node* node = m_currentScope->findChild(nameToken.getContent());
if (node)
{
- // Strictly speaking we should check the backing type etc, match, but for now ignore and assume it's ok
+ // Strictly speaking we should check the backing type etc, match, but for now ignore
+ // and assume it's ok
if (node->m_kind == kind)
{
return SLANG_OK;
}
- m_sink->diagnose(nameToken.loc, CPPDiagnostics::typeAlreadyDeclared, nameToken.getContent());
+ m_sink->diagnose(
+ nameToken.loc,
+ CPPDiagnostics::typeAlreadyDeclared,
+ nameToken.getContent());
return SLANG_FAIL;
}
return popScope();
@@ -407,7 +420,10 @@ SlangResult Parser::_parseEnum()
if (node->findChild(caseNode->m_name.getContent()))
{
- m_sink->diagnose(caseNode->m_name.loc, CPPDiagnostics::identifierAlreadyDefined, caseNode->m_name.getContent());
+ m_sink->diagnose(
+ caseNode->m_name.loc,
+ CPPDiagnostics::identifierAlreadyDefined,
+ caseNode->m_name.getContent());
return SLANG_FAIL;
}
@@ -433,7 +449,7 @@ SlangResult Parser::_parseEnum()
m_reader.advanceToken();
continue;
}
-
+
break;
}
@@ -497,34 +513,34 @@ SlangResult Parser::_consumeTemplate()
}
}
- // Search for { or ; to consume remaining
+ // Search for { or ; to consume remaining
while (true)
{
auto tokenType = m_reader.peekTokenType();
switch (tokenType)
{
- case TokenType::EndOfFile:
+ case TokenType::EndOfFile:
{
m_sink->diagnose(m_reader.peekLoc(), CPPDiagnostics::unexpectedEndOfFile);
return SLANG_FAIL;
}
- case TokenType::Semicolon:
+ case TokenType::Semicolon:
{
// Ends with semicolon if it's a template pre-declaration
m_reader.advanceToken();
return SLANG_OK;
}
- case TokenType::LBrace:
+ case TokenType::LBrace:
{
- // If ends with {, means could be body of a struct/class or a body of a function/method.
- // Consume it
+ // If ends with {, means could be body of a struct/class or a body of a
+ // function/method. Consume it
SLANG_RETURN_ON_FAIL(consumeToClosingBrace());
// If we hit a ; just consume and ignore
advanceIfToken(TokenType::Semicolon);
return SLANG_OK;
}
- default:
+ default:
{
// Consume
m_reader.advanceToken();
@@ -537,7 +553,8 @@ SlangResult Parser::_consumeTemplate()
SlangResult Parser::_maybeParseNode(Node::Kind kind)
{
// We are looking for
- // struct/class identifier [: [public|private|protected] Identifier ] { [public|private|proctected:]* marker ( identifier );
+ // struct/class identifier [: [public|private|protected] Identifier ] {
+ // [public|private|proctected:]* marker ( identifier );
if (kind == Node::Kind::Namespace)
{
@@ -625,7 +642,10 @@ SlangResult Parser::_maybeParseNode(Node::Kind kind)
if (peekTokenType == TokenType::EndOfFile)
{
// Expecting brace
- m_sink->diagnose(m_reader.peekToken(), CPPDiagnostics::expectingToken, TokenType::LBrace);
+ m_sink->diagnose(
+ m_reader.peekToken(),
+ CPPDiagnostics::expectingToken,
+ TokenType::LBrace);
return SLANG_FAIL;
}
else if (peekTokenType == TokenType::LBrace)
@@ -643,7 +663,7 @@ SlangResult Parser::_maybeParseNode(Node::Kind kind)
// Push the class scope
return pushScope(node);
}
-
+
SlangResult Parser::_consumeToSync()
{
while (true)
@@ -652,15 +672,15 @@ SlangResult Parser::_consumeToSync()
switch (type)
{
- case TokenType::Semicolon:
+ case TokenType::Semicolon:
{
m_reader.advanceToken();
return SLANG_OK;
}
- case TokenType::Pound:
- case TokenType::EndOfFile:
- case TokenType::LBrace:
- case TokenType::RBrace:
+ case TokenType::Pound:
+ case TokenType::EndOfFile:
+ case TokenType::LBrace:
+ case TokenType::RBrace:
{
return SLANG_OK;
}
@@ -674,18 +694,18 @@ SlangResult Parser::_maybeParseTemplateArg(Index& ioTemplateDepth)
{
switch (m_reader.peekTokenType())
{
- case TokenType::Identifier:
+ case TokenType::Identifier:
{
TokenReader::ParsingCursor nameCursor;
SLANG_RETURN_ON_FAIL(_maybeParseType(ioTemplateDepth, nameCursor));
return SLANG_OK;
}
- case TokenType::IntegerLiteral:
+ case TokenType::IntegerLiteral:
{
m_reader.advanceToken();
return SLANG_OK;
}
- default: break;
+ default: break;
}
return SLANG_FAIL;
}
@@ -708,7 +728,7 @@ SlangResult Parser::_maybeParseTemplateArgs(Index& ioTemplateDepth)
switch (m_reader.peekTokenType())
{
- case TokenType::OpGreater:
+ case TokenType::OpGreater:
{
if (ioTemplateDepth <= 0)
{
@@ -719,7 +739,7 @@ SlangResult Parser::_maybeParseTemplateArgs(Index& ioTemplateDepth)
m_reader.advanceToken();
return SLANG_OK;
}
- case TokenType::OpRsh:
+ case TokenType::OpRsh:
{
if (ioTemplateDepth <= 1)
{
@@ -730,7 +750,7 @@ SlangResult Parser::_maybeParseTemplateArgs(Index& ioTemplateDepth)
m_reader.advanceToken();
return SLANG_OK;
}
- default:
+ default:
{
while (true)
{
@@ -752,48 +772,52 @@ SlangResult Parser::_maybeParseTemplateArgs(Index& ioTemplateDepth)
SlangResult Parser::_maybeConsume(IdentifierStyle style)
{
- while (advanceIfStyle(style));
+ while (advanceIfStyle(style))
+ ;
return SLANG_OK;
}
-// True if two of these token types of the same type placed immediately after one another
+// True if two of these token types of the same type placed immediately after one another
// produce a different token. Can be conservative, as if not strictly required
// it will just mean more spacing in the output
static bool _canRepeatTokenType(TokenType type)
{
switch (type)
{
- case TokenType::OpAdd:
- case TokenType::OpSub:
- case TokenType::OpAnd:
- case TokenType::OpOr:
- case TokenType::OpGreater:
- case TokenType::OpLess:
- case TokenType::Identifier:
- case TokenType::OpAssign:
- case TokenType::Colon:
+ case TokenType::OpAdd:
+ case TokenType::OpSub:
+ case TokenType::OpAnd:
+ case TokenType::OpOr:
+ case TokenType::OpGreater:
+ case TokenType::OpLess:
+ case TokenType::Identifier:
+ case TokenType::OpAssign:
+ case TokenType::Colon:
{
return false;
}
- default: break;
+ default: break;
}
return true;
}
// Returns true if there needs to be a space between the previous token type, and the current token
// type for correct output. It is assumed that the token stream is appropriate.
-// The implementation might need more sophistication, but this at least avoids Blah const * -> Blahconst*
+// The implementation might need more sophistication, but this at least avoids Blah const * ->
+// Blahconst*
static bool _tokenConcatNeedsSpace(TokenType prev, TokenType cur)
{
- if ((cur == TokenType::OpAssign) ||
- (prev == cur && !_canRepeatTokenType(cur)))
+ if ((cur == TokenType::OpAssign) || (prev == cur && !_canRepeatTokenType(cur)))
{
return true;
}
return false;
}
-void Parser::_getTypeTokens(TokenReader::ParsingCursor start, TokenReader::ParsingCursor nameCursor, List<Token>& outToks)
+void Parser::_getTypeTokens(
+ TokenReader::ParsingCursor start,
+ TokenReader::ParsingCursor nameCursor,
+ List<Token>& outToks)
{
auto endCursor = m_reader.getCursor();
m_reader.setCursor(start);
@@ -811,7 +835,9 @@ void Parser::_getTypeTokens(TokenReader::ParsingCursor start, TokenReader::Parsi
}
}
-UnownedStringSlice Parser::_concatType(TokenReader::ParsingCursor start, TokenReader::ParsingCursor nameCursor)
+UnownedStringSlice Parser::_concatType(
+ TokenReader::ParsingCursor start,
+ TokenReader::ParsingCursor nameCursor)
{
List<Token> toks;
_getTypeTokens(start, nameCursor, toks);
@@ -868,7 +894,9 @@ UnownedStringSlice Parser::_concatTokens(TokenReader::ParsingCursor start)
return typePool->getSlice(typePool->add(buf));
}
-SlangResult Parser::_maybeParseType(Index& ioTemplateDepth, TokenReader::ParsingCursor& outNameCursor)
+SlangResult Parser::_maybeParseType(
+ Index& ioTemplateDepth,
+ TokenReader::ParsingCursor& outNameCursor)
{
outNameCursor = TokenReader::ParsingCursor();
@@ -876,11 +904,11 @@ SlangResult Parser::_maybeParseType(Index& ioTemplateDepth, TokenReader::Parsing
{
if (m_reader.peekTokenType() == TokenType::Identifier)
{
- const IdentifierStyle style = m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
+ const IdentifierStyle style =
+ m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
if (style == IdentifierStyle::TypeModifier ||
- style == IdentifierStyle::IntegerModifier ||
- style == IdentifierStyle::Class ||
+ style == IdentifierStyle::IntegerModifier || style == IdentifierStyle::Class ||
style == IdentifierStyle::Struct)
{
// These are ok keywords in this context
@@ -899,7 +927,8 @@ SlangResult Parser::_maybeParseType(Index& ioTemplateDepth, TokenReader::Parsing
const Token peekToken = m_reader.peekToken();
if (peekToken.type == TokenType::Identifier)
{
- const IdentifierStyle style = m_nodeTree->m_identifierLookup->get(peekToken.getContent());
+ const IdentifierStyle style =
+ m_nodeTree->m_identifierLookup->get(peekToken.getContent());
if (style == IdentifierStyle::IntegerType)
{
m_reader.advanceToken();
@@ -907,16 +936,16 @@ SlangResult Parser::_maybeParseType(Index& ioTemplateDepth, TokenReader::Parsing
}
break;
}
-
+
advanceIfToken(TokenType::Scope);
while (true)
{
// if we have a struct/class prefix in front of a name just consume it.
if (m_reader.peekTokenType() == TokenType::Identifier)
{
- const IdentifierStyle style = m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
- if (style == IdentifierStyle::Class ||
- style == IdentifierStyle::Struct)
+ const IdentifierStyle style =
+ m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
+ if (style == IdentifierStyle::Class || style == IdentifierStyle::Struct)
{
m_reader.advanceToken();
}
@@ -928,7 +957,8 @@ SlangResult Parser::_maybeParseType(Index& ioTemplateDepth, TokenReader::Parsing
return SLANG_FAIL;
}
- const IdentifierStyle style = m_nodeTree->m_identifierLookup->get(identifierToken.getContent());
+ const IdentifierStyle style =
+ m_nodeTree->m_identifierLookup->get(identifierToken.getContent());
if (hasFlag(style, IdentifierFlag::Keyword))
{
return SLANG_FAIL;
@@ -986,11 +1016,14 @@ SlangResult Parser::_maybeParseType(Index& ioTemplateDepth, TokenReader::Parsing
SLANG_RETURN_ON_FAIL(expect(TokenType::Identifier));
SLANG_RETURN_ON_FAIL(expect(TokenType::RParent));
-
+
// We need to parse and add the params
if (m_reader.peekTokenType() != TokenType::LParent)
{
- m_sink->diagnose(m_reader.peekToken(), CPPDiagnostics::expectingToken, TokenType::LParent);
+ m_sink->diagnose(
+ m_reader.peekToken(),
+ CPPDiagnostics::expectingToken,
+ TokenType::LParent);
return SLANG_FAIL;
}
@@ -1108,15 +1141,18 @@ SlangResult Parser::_parseSpecialMacro()
SlangResult Parser::_parseMarker()
{
- SLANG_ASSERT(m_reader.peekTokenType() == TokenType::Identifier &&
- _isMarker(m_reader.peekToken().getContent()) &&
- m_currentScope->isClassLike());
+ SLANG_ASSERT(
+ m_reader.peekTokenType() == TokenType::Identifier &&
+ _isMarker(m_reader.peekToken().getContent()) && m_currentScope->isClassLike());
ClassLikeNode* node = as<ClassLikeNode>(m_currentScope);
if (node->m_marker.type != TokenType::Unknown)
{
- m_sink->diagnose(m_reader.peekToken(), CPPDiagnostics::classMarkerAlreadyFound, node->m_name.getContent());
+ m_sink->diagnose(
+ m_reader.peekToken(),
+ CPPDiagnostics::classMarkerAlreadyFound,
+ node->m_name.getContent());
m_sink->diagnose(node->m_marker, CPPDiagnostics::previousLocation);
return SLANG_FAIL;
}
@@ -1128,7 +1164,9 @@ SlangResult Parser::_parseMarker()
UnownedStringSlice slice(node->m_marker.getContent());
// Strip the prefix and suffix
- slice = UnownedStringSlice(slice.begin() + m_options->m_markPrefix.getLength(), slice.end() - m_options->m_markSuffix.getLength());
+ slice = UnownedStringSlice(
+ slice.begin() + m_options->m_markPrefix.getLength(),
+ slice.end() - m_options->m_markSuffix.getLength());
// Strip ABSTRACT_ if it's there
UnownedStringSlice abstractSlice("ABSTRACT_");
@@ -1140,7 +1178,7 @@ SlangResult Parser::_parseMarker()
// TODO: We could strip other stuff or have other heuristics there, but this is
// probably okay for now
- // Set the typeSet
+ // Set the typeSet
node->m_typeSet = m_nodeTree->getOrAddTypeSet(slice);
// Okay now looking for ( identifier)
@@ -1152,7 +1190,10 @@ SlangResult Parser::_parseMarker()
if (typeNameToken.getContent() != node->m_name.getContent())
{
- m_sink->diagnose(typeNameToken, CPPDiagnostics::typeNameDoesntMatch, node->m_name.getContent());
+ m_sink->diagnose(
+ typeNameToken,
+ CPPDiagnostics::typeNameDoesntMatch,
+ node->m_name.getContent());
return SLANG_FAIL;
}
@@ -1203,16 +1244,14 @@ SlangResult Parser::_maybeParseType(UnownedStringSlice& outType, Token& outName)
static bool _isBalancedOpen(TokenType tokenType)
{
- return tokenType == TokenType::LBrace ||
- tokenType == TokenType::LParent ||
- tokenType == TokenType::LBracket;
+ return tokenType == TokenType::LBrace || tokenType == TokenType::LParent ||
+ tokenType == TokenType::LBracket;
}
static bool _isBalancedClose(TokenType tokenType)
{
- return tokenType == TokenType::RBrace ||
- tokenType == TokenType::RParent ||
- tokenType == TokenType::RBracket;
+ return tokenType == TokenType::RBrace || tokenType == TokenType::RParent ||
+ tokenType == TokenType::RBracket;
}
static TokenType _getBalancedClose(TokenType tokenType)
@@ -1220,10 +1259,10 @@ static TokenType _getBalancedClose(TokenType tokenType)
SLANG_ASSERT(_isBalancedOpen(tokenType));
switch (tokenType)
{
- case TokenType::LBrace: return TokenType::RBrace;
- case TokenType::LParent: return TokenType::RParent;
- case TokenType::LBracket: return TokenType::RBracket;
- default: return TokenType::Unknown;
+ case TokenType::LBrace: return TokenType::RBrace;
+ case TokenType::LParent: return TokenType::RParent;
+ case TokenType::LBracket: return TokenType::RBracket;
+ default: return TokenType::Unknown;
}
}
@@ -1251,7 +1290,7 @@ SlangResult Parser::_parseBalanced(DiagnosticSink* sink)
return SLANG_OK;
}
- // If we hit a balanced open, recurse
+ // If we hit a balanced open, recurse
if (_isBalancedOpen(tokenType))
{
SLANG_RETURN_ON_FAIL(_parseBalanced(sink));
@@ -1300,12 +1339,12 @@ SlangResult Parser::_consumeBalancedParens()
switch (tokenType)
{
- case TokenType::LParent:
+ case TokenType::LParent:
{
parenCount++;
break;
}
- case TokenType::RParent:
+ case TokenType::RParent:
{
--parenCount;
// If no more parens then we are done
@@ -1316,12 +1355,12 @@ SlangResult Parser::_consumeBalancedParens()
}
break;
}
- case TokenType::EndOfFile:
+ case TokenType::EndOfFile:
{
// If we hit the end of the file, then not balanced
return SLANG_FAIL;
}
- default: break;
+ default: break;
}
m_reader.advanceToken();
@@ -1333,9 +1372,10 @@ SlangResult Parser::_parseExpression(List<Token>& outExprTokens)
Index parenCount = 0;
Index bracketCount = 0;
- // TODO(JS): NOTE! This doesn't handle an expression that contains a template params in Something<Arg1, 3>,
- // because without knowing what Something is, it's not known if < is a comparison or or a 'template' bracket
- //
+ // TODO(JS): NOTE! This doesn't handle an expression that contains a template params in
+ // Something<Arg1, 3>, because without knowing what Something is, it's not known if < is a
+ // comparison or or a 'template' bracket
+ //
// This can be worked around in the originating source by placing in parens
while (true)
@@ -1344,12 +1384,12 @@ SlangResult Parser::_parseExpression(List<Token>& outExprTokens)
switch (tokenType)
{
- case TokenType::LParent:
+ case TokenType::LParent:
{
parenCount++;
break;
}
- case TokenType::RParent:
+ case TokenType::RParent:
{
// If no parens, and nothing else is open then we are done
if (parenCount == 0)
@@ -1365,12 +1405,12 @@ SlangResult Parser::_parseExpression(List<Token>& outExprTokens)
--parenCount;
break;
}
- case TokenType::LBracket:
+ case TokenType::LBracket:
{
bracketCount++;
break;
}
- case TokenType::RBracket:
+ case TokenType::RBracket:
{
// If no brackets are open we are done
if (bracketCount == 0)
@@ -1385,7 +1425,7 @@ SlangResult Parser::_parseExpression(List<Token>& outExprTokens)
--bracketCount;
break;
}
- case TokenType::EndOfFile:
+ case TokenType::EndOfFile:
{
if ((bracketCount | parenCount) == 0)
{
@@ -1394,9 +1434,9 @@ SlangResult Parser::_parseExpression(List<Token>& outExprTokens)
m_sink->diagnose(m_reader.peekLoc(), CPPDiagnostics::cannotParseExpression);
return SLANG_FAIL;
}
- case TokenType::RBrace:
- case TokenType::Semicolon:
- case TokenType::Comma:
+ case TokenType::RBrace:
+ case TokenType::Semicolon:
+ case TokenType::Comma:
{
if ((bracketCount | parenCount) == 0)
{
@@ -1405,7 +1445,7 @@ SlangResult Parser::_parseExpression(List<Token>& outExprTokens)
break;
}
- default: break;
+ default: break;
}
outExprTokens.add(m_reader.advanceToken());
@@ -1436,7 +1476,10 @@ SlangResult Parser::_parseTypeDef()
if (Node::lookupNameInScope(m_currentScope, nameToken.getContent()))
{
- m_sink->diagnose(nameToken.loc, CPPDiagnostics::identifierAlreadyDefined, nameToken.getContent());
+ m_sink->diagnose(
+ nameToken.loc,
+ CPPDiagnostics::identifierAlreadyDefined,
+ nameToken.getContent());
return SLANG_FAIL;
}
@@ -1484,7 +1527,8 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
while (m_reader.peekTokenType() == TokenType::Identifier)
{
- const IdentifierStyle style = m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
+ const IdentifierStyle style =
+ m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
// Check for virtualness
if (style == IdentifierStyle::Virtual)
@@ -1494,13 +1538,13 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
continue;
}
- // Check if static
+ // Check if static
if (style == IdentifierStyle::Static)
{
isStatic = true;
m_reader.advanceToken();
continue;
- }
+ }
break;
}
@@ -1511,7 +1555,7 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
Token nameToken;
bool isConstructor = false;
-
+
if (m_currentScope->isClassLike())
{
// If it's a dtor
@@ -1524,7 +1568,10 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
if (tok.getContent() != m_currentScope->m_name.getContent())
{
- m_sink->diagnose(m_reader.peekLoc(), CPPDiagnostics::destructorNameDoesntMatch, m_currentScope->m_name.getContent());
+ m_sink->diagnose(
+ m_reader.peekLoc(),
+ CPPDiagnostics::destructorNameDoesntMatch,
+ m_currentScope->m_name.getContent());
return SLANG_FAIL;
}
}
@@ -1563,7 +1610,7 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
return SLANG_OK;
}
}
-
+
// Handles other scenarios, but here for catching operator overloading
if (nameToken.type == TokenType::Identifier)
{
@@ -1582,7 +1629,7 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
SLANG_RETURN_ON_FAIL(_consumeBalancedParens());
// Consume everything up to ; or {
SLANG_RETURN_ON_FAIL(_consumeToSync());
-
+
return SLANG_OK;
}
@@ -1639,7 +1686,7 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
continue;
}
}
-
+
m_sink->diagnose(m_reader.peekLoc(), CPPDiagnostics::expectingToken, ", or ) or =");
return SLANG_FAIL;
}
@@ -1662,8 +1709,7 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
while (true)
{
auto peekType = m_reader.peekTokenType();
- if (peekType == TokenType::Semicolon ||
- peekType == TokenType::LBrace ||
+ if (peekType == TokenType::Semicolon || peekType == TokenType::LBrace ||
peekType == TokenType::EndOfFile)
{
break;
@@ -1673,14 +1719,15 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
}
}
}
-
+
// = 0 ? or = default
if (advanceIfToken(TokenType::OpAssign))
{
if (m_reader.peekTokenType() == TokenType::IntegerLiteral)
{
Int value = -1;
- if (SLANG_SUCCEEDED(StringUtil::parseInt(m_reader.peekToken().getContent(), value)) &&
+ if (SLANG_SUCCEEDED(
+ StringUtil::parseInt(m_reader.peekToken().getContent(), value)) &&
value == 0)
{
isPure = true;
@@ -1693,7 +1740,7 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
}
}
else if (advanceIfStyle(IdentifierStyle::Default))
- {
+ {
}
else
{
@@ -1768,7 +1815,7 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
List<Token> exprTokens;
SLANG_RETURN_ON_FAIL(_parseExpression(exprTokens));
}
-
+
// Hit end of field/variable
if (m_reader.peekTokenType() == TokenType::Semicolon)
{
@@ -1785,21 +1832,21 @@ SlangResult Parser::_maybeParseContained(Node** outNode)
return SLANG_OK;
}
}
-
+
_consumeToSync();
return SLANG_OK;
}
-/* static */Node::Kind Parser::_toNodeKind(IdentifierStyle style)
+/* static */ Node::Kind Parser::_toNodeKind(IdentifierStyle style)
{
switch (style)
{
- case IdentifierStyle::Class: return Node::Kind::ClassType;
- case IdentifierStyle::Struct: return Node::Kind::StructType;
- case IdentifierStyle::Namespace: return Node::Kind::Namespace;
- case IdentifierStyle::Enum: return Node::Kind::Enum;
- case IdentifierStyle::TypeDef: return Node::Kind::TypeDef;
- default: return Node::Kind::Invalid;
+ case IdentifierStyle::Class: return Node::Kind::ClassType;
+ case IdentifierStyle::Struct: return Node::Kind::StructType;
+ case IdentifierStyle::Namespace: return Node::Kind::Namespace;
+ case IdentifierStyle::Enum: return Node::Kind::Enum;
+ case IdentifierStyle::TypeDef: return Node::Kind::TypeDef;
+ default: return Node::Kind::Invalid;
}
}
@@ -1839,7 +1886,10 @@ SlangResult Parser::_parsePreDeclare()
if (style != IdentifierStyle::Struct && style != IdentifierStyle::Class)
{
- m_sink->diagnose(typeToken, CPPDiagnostics::expectingTypeKeyword, typeToken.getContent());
+ m_sink->diagnose(
+ typeToken,
+ CPPDiagnostics::expectingTypeKeyword,
+ typeToken.getContent());
return SLANG_FAIL;
}
nodeKind = _toNodeKind(style);
@@ -1859,8 +1909,8 @@ SlangResult Parser::_parsePreDeclare()
switch (nodeKind)
{
- case Node::Kind::ClassType:
- case Node::Kind::StructType:
+ case Node::Kind::ClassType:
+ case Node::Kind::StructType:
{
RefPtr<ClassLikeNode> node(new ClassLikeNode(nodeKind));
@@ -1876,7 +1926,7 @@ SlangResult Parser::_parsePreDeclare()
popScope();
break;
}
- default:
+ default:
{
return SLANG_FAIL;
}
@@ -1930,7 +1980,7 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
// Set up the scope stack
m_scopeStack.clear();
-
+
m_currentScope = m_nodeTree->m_rootNode;
m_scopeStack.add(m_currentScope);
@@ -1953,7 +2003,7 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
{
switch (m_reader.peekTokenType())
{
- case TokenType::OpBitNot:
+ case TokenType::OpBitNot:
{
// Handle dtor
if (m_currentScope->isClassLike())
@@ -1968,13 +2018,14 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
}
break;
}
- case TokenType::Identifier:
+ case TokenType::Identifier:
{
- const IdentifierStyle style = m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
+ const IdentifierStyle style =
+ m_nodeTree->m_identifierLookup->get(m_reader.peekToken().getContent());
switch (style)
{
- case IdentifierStyle::Extern:
+ case IdentifierStyle::Extern:
{
m_reader.advanceToken();
@@ -1988,22 +2039,22 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
}
break;
}
- case IdentifierStyle::Template:
+ case IdentifierStyle::Template:
{
SLANG_RETURN_ON_FAIL(_consumeTemplate());
break;
}
- case IdentifierStyle::PreDeclare:
+ case IdentifierStyle::PreDeclare:
{
SLANG_RETURN_ON_FAIL(_parsePreDeclare());
break;
}
- case IdentifierStyle::TypeSet:
+ case IdentifierStyle::TypeSet:
{
SLANG_RETURN_ON_FAIL(_parseTypeSet());
break;
}
- case IdentifierStyle::Reflected:
+ case IdentifierStyle::Reflected:
{
m_reader.advanceToken();
if (m_currentScope)
@@ -2012,7 +2063,7 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
}
break;
}
- case IdentifierStyle::Unreflected:
+ case IdentifierStyle::Unreflected:
{
m_reader.advanceToken();
if (m_currentScope)
@@ -2021,13 +2072,13 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
}
break;
}
- case IdentifierStyle::Access:
+ case IdentifierStyle::Access:
{
m_reader.advanceToken();
SLANG_RETURN_ON_FAIL(expect(TokenType::Colon));
break;
}
- case IdentifierStyle::TypeDef:
+ case IdentifierStyle::TypeDef:
{
if (isTypeEnabled(Node::Kind::TypeDef))
{
@@ -2040,7 +2091,7 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
}
break;
}
- default:
+ default:
{
IdentifierFlags flags = getFlags(style);
@@ -2067,7 +2118,9 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
{
if (!m_currentScope->isClassLike())
{
- m_sink->diagnose(m_reader.peekLoc(), CPPDiagnostics::classMarkerOutsideOfClass);
+ m_sink->diagnose(
+ m_reader.peekLoc(),
+ CPPDiagnostics::classMarkerOutsideOfClass);
return SLANG_FAIL;
}
@@ -2075,16 +2128,18 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
break;
}
- if (m_options->m_markPrefix.getLength() > 0 && content.startsWith(m_options->m_markPrefix.getUnownedSlice()))
+ if (m_options->m_markPrefix.getLength() > 0 &&
+ content.startsWith(m_options->m_markPrefix.getUnownedSlice()))
{
SLANG_RETURN_ON_FAIL(_parseSpecialMacro());
break;
}
- // Special case the node that's the root of the hierarchy (as far as reflection is concerned)
- // This could be a field
- if (m_currentScope->canContainFields() || m_currentScope->canContainCallable())
+ // Special case the node that's the root of the hierarchy (as far as
+ // reflection is concerned) This could be a field
+ if (m_currentScope->canContainFields() ||
+ m_currentScope->canContainCallable())
{
Node* containedNode = nullptr;
SLANG_RETURN_ON_FAIL(_maybeParseContained(&containedNode));
@@ -2099,18 +2154,18 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
}
break;
}
- case TokenType::LBrace:
+ case TokenType::LBrace:
{
SLANG_RETURN_ON_FAIL(consumeToClosingBrace());
break;
}
- case TokenType::RBrace:
+ case TokenType::RBrace:
{
SLANG_RETURN_ON_FAIL(popScope());
m_reader.advanceToken();
break;
}
- case TokenType::EndOfFile:
+ case TokenType::EndOfFile:
{
// Okay we need to confirm that we are in the root node, and with no open braces
if (m_currentScope != m_nodeTree->getRootNode())
@@ -2121,7 +2176,7 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
return SLANG_OK;
}
- case TokenType::Pound:
+ case TokenType::Pound:
{
Token token = m_reader.peekToken();
if (token.flags & TokenFlag::AtStartOfLine)
@@ -2143,7 +2198,7 @@ SlangResult Parser::parse(SourceOrigin* sourceOrigin, const Options* options)
m_reader.advanceToken();
break;
}
- default:
+ default:
{
// Skip it then
m_reader.advanceToken();
diff --git a/tools/slang-cpp-extractor/parser.h b/tools/slang-cpp-extractor/parser.h
index cf0147e8b..605a0d8be 100644
--- a/tools/slang-cpp-extractor/parser.h
+++ b/tools/slang-cpp-extractor/parser.h
@@ -1,20 +1,19 @@
#ifndef CPP_EXTRACT_PARSER_H
#define CPP_EXTRACT_PARSER_H
+#include "../../source/compiler-core/slang-lexer.h"
#include "diagnostics.h"
-#include "node.h"
#include "identifier-lookup.h"
#include "node-tree.h"
+#include "node.h"
-#include "../../source/compiler-core/slang-lexer.h"
-
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
class Parser
{
public:
-
typedef uint32_t NodeTypeBitType;
SlangResult expect(TokenType type, Token* outToken = nullptr);
@@ -28,11 +27,14 @@ public:
SlangResult consumeToClosingBrace(const Token* openBraceToken = nullptr);
SlangResult popScope();
- /// Parse the contents of the source file
+ /// Parse the contents of the source file
SlangResult parse(SourceOrigin* sourceOrigin, const Options* options);
void setKindEnabled(Node::Kind kind, bool isEnabled = true);
- bool isTypeEnabled(Node::Kind kind) { return (m_nodeTypeEnabled & (NodeTypeBitType(1) << int(kind))) != 0; }
+ bool isTypeEnabled(Node::Kind kind)
+ {
+ return (m_nodeTypeEnabled & (NodeTypeBitType(1) << int(kind))) != 0;
+ }
void setKindsEnabled(const Node::Kind* kinds, Index kindsCount, bool isEnabled = true);
@@ -61,29 +63,34 @@ protected:
SlangResult _maybeParseType(Index& ioTemplateDepth, TokenReader::ParsingCursor& outCursor);
SlangResult _parseExpression(List<Token>& outExprTokens);
-
+
SlangResult _maybeParseTemplateArgs(Index& ioTemplateDepth);
SlangResult _maybeParseTemplateArg(Index& ioTemplateDepth);
- /// Parse balanced - if a sink is set will report to that sink
+ /// Parse balanced - if a sink is set will report to that sink
SlangResult _parseBalanced(DiagnosticSink* sink);
bool _isCtor();
- /// Concatenate all tokens from start to the current position
+ /// Concatenate all tokens from start to the current position
UnownedStringSlice _concatTokens(TokenReader::ParsingCursor start);
UnownedStringSlice _concatTokens(const Token* toks, Index toksCount);
- UnownedStringSlice _concatType(TokenReader::ParsingCursor start, TokenReader::ParsingCursor nameCursor);
+ UnownedStringSlice _concatType(
+ TokenReader::ParsingCursor start,
+ TokenReader::ParsingCursor nameCursor);
- void _getTypeTokens(TokenReader::ParsingCursor start, TokenReader::ParsingCursor nameCursor, List<Token>& outToks);
+ void _getTypeTokens(
+ TokenReader::ParsingCursor start,
+ TokenReader::ParsingCursor nameCursor,
+ List<Token>& outToks);
- /// Consume what looks like a template definition
+ /// Consume what looks like a template definition
SlangResult _consumeTemplate();
SlangResult _maybeConsume(IdentifierStyle style);
SlangResult _consumeToSync();
- /// Consumes balanced parens. Will return an error if not matched. Assumes starts on opening (
+ /// Consumes balanced parens. Will return an error if not matched. Assumes starts on opening (
SlangResult _consumeBalancedParens();
NodeTypeBitType m_nodeTypeEnabled;
@@ -93,16 +100,16 @@ protected:
List<ScopeNode*> m_scopeStack;
- ScopeNode* m_currentScope; ///< The current scope being processed
- SourceOrigin* m_sourceOrigin; ///< The source origin that all tokens are in
+ ScopeNode* m_currentScope; ///< The current scope being processed
+ SourceOrigin* m_sourceOrigin; ///< The source origin that all tokens are in
- DiagnosticSink* m_sink; ///< Diagnostic sink
+ DiagnosticSink* m_sink; ///< Diagnostic sink
- NodeTree* m_nodeTree; ///< Shared state between parses. Nodes will be added to this
+ NodeTree* m_nodeTree; ///< Shared state between parses. Nodes will be added to this
const Options* m_options;
};
-} // CppExtract
+} // namespace CppExtract
#endif
diff --git a/tools/slang-cpp-extractor/unit-test.cpp b/tools/slang-cpp-extractor/unit-test.cpp
index 16b4c10dc..3c0edac3c 100644
--- a/tools/slang-cpp-extractor/unit-test.cpp
+++ b/tools/slang-cpp-extractor/unit-test.cpp
@@ -1,26 +1,23 @@
#include "unit-test.h"
-
+#include "../../source/compiler-core/slang-lexer.h"
#include "../../source/compiler-core/slang-name-convention-util.h"
-
-#include "../../source/core/slang-io.h"
-
#include "../../source/compiler-core/slang-source-loc.h"
-#include "../../source/compiler-core/slang-lexer.h"
-
+#include "../../source/core/slang-io.h"
#include "identifier-lookup.h"
#include "node-tree.h"
-#include "parser.h"
#include "options.h"
+#include "parser.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
struct TestState
{
- TestState():
- m_slicePool(StringSlicePool::Style::Default)
+ TestState()
+ : m_slicePool(StringSlicePool::Style::Default)
{
m_identifierLookup.initDefault(UnownedStringSlice::fromLiteral("SLANG_"));
@@ -43,48 +40,47 @@ struct TestState
IdentifierLookup m_identifierLookup;
};
-static const char someSource[] =
-"class ISomeInterface\n"
-"{\n"
-" public:\n"
-" virtual int SLANG_MCALL someMethod(int a, int b) const = 0;\n"
-" virtual float SLANG_MCALL anotherMethod(float a) = 0;\n"
-"};\n"
-"\n"
-"struct SomeStruct\n"
-"{\n"
-" SomeStruct() = default;\n"
-" SomeStruct(float v = 0.0f):b(v) {}\n"
-" ~SomeStruct() {}\n"
-" int a = 10; \n"
-" float b; \n"
-" int another[10];\n"
-" const char* yetAnother = nullptr;\n"
-"};\n"
-"\n"
-"enum SomeEnum\n"
-"{\n"
-" Value,\n"
-" Another = 10,\n"
-"};\n"
-"\n"
-"typedef int (*SomeFunc)(int a);\n"
-"\n"
-"typedef SomeEnum AliasEnum;\n"
-"void someFunc(int a, float b) { }\n"
-"namespace Blah {\n"
-"int add(int a, int b) { return a + b; }\n"
-"unsigned add(unsigned a, unsigned b) { return a + b; }\n"
-"}\n";
-
-
-/* static */SlangResult UnitTestUtil::run()
+static const char someSource[] = "class ISomeInterface\n"
+ "{\n"
+ " public:\n"
+ " virtual int SLANG_MCALL someMethod(int a, int b) const = 0;\n"
+ " virtual float SLANG_MCALL anotherMethod(float a) = 0;\n"
+ "};\n"
+ "\n"
+ "struct SomeStruct\n"
+ "{\n"
+ " SomeStruct() = default;\n"
+ " SomeStruct(float v = 0.0f):b(v) {}\n"
+ " ~SomeStruct() {}\n"
+ " int a = 10; \n"
+ " float b; \n"
+ " int another[10];\n"
+ " const char* yetAnother = nullptr;\n"
+ "};\n"
+ "\n"
+ "enum SomeEnum\n"
+ "{\n"
+ " Value,\n"
+ " Another = 10,\n"
+ "};\n"
+ "\n"
+ "typedef int (*SomeFunc)(int a);\n"
+ "\n"
+ "typedef SomeEnum AliasEnum;\n"
+ "void someFunc(int a, float b) { }\n"
+ "namespace Blah {\n"
+ "int add(int a, int b) { return a + b; }\n"
+ "unsigned add(unsigned a, unsigned b) { return a + b; }\n"
+ "}\n";
+
+
+/* static */ SlangResult UnitTestUtil::run()
{
{
TestState state;
NodeTree tree(&state.m_slicePool, &state.m_namePool, &state.m_identifierLookup);
-
+
UnownedStringSlice contents = UnownedStringSlice::fromLiteral(someSource);
PathInfo pathInfo = PathInfo::makeFromString("source.h");
@@ -95,9 +91,13 @@ static const char someSource[] =
Parser parser(&tree, &state.m_sink);
-
+
{
- const Node::Kind enableKinds[] = { Node::Kind::Enum, Node::Kind::EnumClass, Node::Kind::EnumCase, Node::Kind::TypeDef };
+ const Node::Kind enableKinds[] = {
+ Node::Kind::Enum,
+ Node::Kind::EnumClass,
+ Node::Kind::EnumCase,
+ Node::Kind::TypeDef};
parser.setKindsEnabled(enableKinds, SLANG_COUNT_OF(enableKinds));
}
diff --git a/tools/slang-cpp-extractor/unit-test.h b/tools/slang-cpp-extractor/unit-test.h
index 9c8d9b08c..fd3ab1328 100644
--- a/tools/slang-cpp-extractor/unit-test.h
+++ b/tools/slang-cpp-extractor/unit-test.h
@@ -3,7 +3,8 @@
#include "diagnostics.h"
-namespace CppExtract {
+namespace CppExtract
+{
using namespace Slang;
struct UnitTestUtil
@@ -11,6 +12,6 @@ struct UnitTestUtil
static SlangResult run();
};
-} // CppExtract
+} // namespace CppExtract
#endif
diff --git a/tools/slang-embed/slang-embed.cpp b/tools/slang-embed/slang-embed.cpp
index c3c683f9c..5910e00f8 100644
--- a/tools/slang-embed/slang-embed.cpp
+++ b/tools/slang-embed/slang-embed.cpp
@@ -8,28 +8,30 @@
// libraries.
//
#ifdef _MSC_VER
-#pragma warning(disable: 4996)
+#pragma warning(disable : 4996)
#endif
+#include "../../source/core/slang-dictionary.h"
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-list.h"
+#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-string.h"
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include "../../source/core/slang-list.h"
-#include "../../source/core/slang-string.h"
-#include "../../source/core/slang-string-util.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-dictionary.h"
-
// Utility to free pointers on scope exit
struct ScopedMemory
{
ScopedMemory(void* ptr)
: ptr(ptr)
- {}
+ {
+ }
~ScopedMemory()
{
- if(ptr) free(ptr);
+ if (ptr)
+ free(ptr);
}
void* ptr;
@@ -40,11 +42,13 @@ struct ScopedFile
{
ScopedFile(FILE* file)
: file(file)
- {}
+ {
+ }
~ScopedFile()
{
- if(file) fclose(file);
+ if (file)
+ fclose(file);
}
FILE* file;
@@ -67,25 +71,25 @@ struct App
// Options are currently all specified by position,
// so the parsing logic is simplistic.
- if( argc > 0 )
+ if (argc > 0)
{
appName = *argv++;
argc--;
}
- if( argc > 0 )
+ if (argc > 0)
{
inputPath = *argv++;
argc--;
}
- if( argc > 0 )
+ if (argc > 0)
{
outputPath = *argv++;
argc--;
}
- if( !inputPath || (argc != 0) )
+ if (!inputPath || (argc != 0))
{
fprintf(stderr, "usage: %s inputPath [outputPath]\n", appName);
exit(1);
@@ -126,8 +130,7 @@ struct App
auto trimedLine = line.trimStart();
if (trimedLine.startsWith("#include"))
{
- auto fileName =
- Slang::StringUtil::getAtInSplit(trimedLine, ' ', 1);
+ auto fileName = Slang::StringUtil::getAtInSplit(trimedLine, ' ', 1);
if (fileName[0] == '<')
goto normalProcess;
fileName = Slang::UnownedStringSlice(fileName.begin() + 1, fileName.end() - 1);
@@ -164,18 +167,10 @@ struct App
{
// The common C escape sequencs are handled directly.
//
- case '"':
- fprintf(outputFile, "\\\"");
- break;
- case '\n':
- fprintf(outputFile, "\\n");
- break;
- case '\t':
- fprintf(outputFile, "\\t");
- break;
- case '\\':
- fprintf(outputFile, "\\\\");
- break;
+ case '"': fprintf(outputFile, "\\\""); break;
+ case '\n': fprintf(outputFile, "\\n"); break;
+ case '\t': fprintf(outputFile, "\\t"); break;
+ case '\\': fprintf(outputFile, "\\\\"); break;
default:
// For all other cases, we detect if the byte
// is in the printable ASCII range, and emit
@@ -210,16 +205,16 @@ struct App
// We derive an output path simply by appending `.cpp` to the input
// path, if not otherwise specified
- char* defaultOutputPath = (char*) malloc(strlen(inputPath) + strlen(".cpp") + 1);
+ char* defaultOutputPath = (char*)malloc(strlen(inputPath) + strlen(".cpp") + 1);
ScopedMemory outputPathCleanup(defaultOutputPath);
strcpy(defaultOutputPath, inputPath);
strcat(defaultOutputPath, ".cpp");
- if(!outputPath)
+ if (!outputPath)
outputPath = defaultOutputPath;
FILE* outputFile = fopen(outputPath, "w");
ScopedFile outputFileCleanup(outputFile);
- if( !outputFile )
+ if (!outputFile)
{
fprintf(stderr, "%s: error: failed to open '%s' for reading\n", appName, outputPath);
exit(1);
@@ -233,19 +228,19 @@ struct App
// unconventional names.
//
char const* fileName = inputPath;
- if(auto pos = strrchr(fileName, '\\'))
- fileName = pos+1;
- if(auto pos = strrchr(fileName, '/'))
- fileName = pos+1;
+ if (auto pos = strrchr(fileName, '\\'))
+ fileName = pos + 1;
+ if (auto pos = strrchr(fileName, '/'))
+ fileName = pos + 1;
// The variable name will start as a copy of the file
// name, although we will immediately drop any extension
// that comes after a `.` to trim the name further.
//
- char* variableName = (char*) malloc(strlen(fileName)+1);
+ char* variableName = (char*)malloc(strlen(fileName) + 1);
ScopedMemory variableNameCleanup(variableName);
strcpy(variableName, fileName);
- if(auto pos = strchr(variableName, '.'))
+ if (auto pos = strchr(variableName, '.'))
*pos = 0;
// We will also replace any `-` in the file name with
@@ -253,12 +248,11 @@ struct App
// tool will be compatible with our current naming
// convention of using `-` as the separator in file names.
//
- for( auto cursor = variableName; *cursor; ++cursor)
+ for (auto cursor = variableName; *cursor; ++cursor)
{
- switch( *cursor )
+ switch (*cursor)
{
- default:
- break;
+ default: break;
case '-': *cursor = '_';
}
}
diff --git a/tools/slang-generate/main.cpp b/tools/slang-generate/main.cpp
index c54ee19f3..22e2e7862 100644
--- a/tools/slang-generate/main.cpp
+++ b/tools/slang-generate/main.cpp
@@ -1,14 +1,14 @@
// main.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-list.h"
+#include "../../source/core/slang-secure-crt.h"
+#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-string.h"
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include "../../source/core/slang-secure-crt.h"
-
-#include "../../source/core/slang-list.h"
-#include "../../source/core/slang-string.h"
-#include "../../source/core/slang-string-util.h"
-#include "../../source/core/slang-io.h"
using namespace Slang;
@@ -24,10 +24,10 @@ struct Node
};
// What sort of node is this?
- Flavor flavor;
+ Flavor flavor;
// The text of this node for `Flavor::text`
- StringSpan span;
+ StringSpan span;
// The body of this node for other flavors
Node* body = nullptr;
@@ -38,8 +38,10 @@ struct Node
Node() = default;
~Node()
{
- if (body) delete body;
- if (next) delete next;
+ if (body)
+ delete body;
+ if (next)
+ delete next;
}
};
@@ -47,9 +49,9 @@ struct Node
struct SourceFile : public RefObject
{
String inputPath;
- String linePath; ///< The path to this file for #line output
+ String linePath; ///< The path to this file for #line output
- StringSpan text;
+ StringSpan text;
Node* node = nullptr;
SourceFile() = default;
~SourceFile()
@@ -69,11 +71,7 @@ struct SourceFile : public RefObject
}
};
-void addNode(
- Node**& ioLink,
- Node::Flavor flavor,
- char const* spanBegin,
- char const* spanEnd)
+void addNode(Node**& ioLink, Node::Flavor flavor, char const* spanBegin, char const* spanEnd)
{
Node* node = new Node();
node->flavor = flavor;
@@ -84,10 +82,7 @@ void addNode(
ioLink = &node->next;
}
-void addNode(
- Node**& ioLink,
- Node::Flavor flavor,
- Node* body)
+void addNode(Node**& ioLink, Node::Flavor flavor, Node* body)
{
Node* node = new Node();
node->flavor = flavor;
@@ -100,15 +95,10 @@ void addNode(
bool isAlpha(int c)
{
- return ((c >= 'a') && (c <= 'z'))
- || ((c >= 'A') && (c <= 'Z'))
- || (c == '_');
+ return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || (c == '_');
}
-void addTextSpan(
- Node**& ioLink,
- char const* spanBegin,
- char const* spanEnd)
+void addTextSpan(Node**& ioLink, char const* spanBegin, char const* spanEnd)
{
// Don't add an empty text span.
if (spanBegin == spanEnd)
@@ -117,24 +107,17 @@ void addTextSpan(
addNode(ioLink, Node::Flavor::text, spanBegin, spanEnd);
}
-void addSpliceSpan(
- Node**& ioLink,
- Node* body)
+void addSpliceSpan(Node**& ioLink, Node* body)
{
addNode(ioLink, Node::Flavor::splice, body);
}
-void addEscapeSpan(
- Node**& ioLink,
- Node* body)
+void addEscapeSpan(Node**& ioLink, Node* body)
{
addNode(ioLink, Node::Flavor::escape, body);
}
-void addEscapeSpan(
- Node**& ioLink,
- char const* spanBegin,
- char const* spanEnd)
+void addEscapeSpan(Node**& ioLink, char const* spanBegin, char const* spanEnd)
{
Node* body = nullptr;
Node** link = &body;
@@ -146,12 +129,14 @@ void addEscapeSpan(
bool isIdentifierChar(int c)
{
- if (c >= 'a' && c <= 'z') return true;
- if (c >= 'A' && c <= 'Z') return true;
- if (c == '_') return true;
+ if (c >= 'a' && c <= 'z')
+ return true;
+ if (c >= 'A' && c <= 'Z')
+ return true;
+ if (c == '_')
+ return true;
return false;
-
}
struct Reader
@@ -200,10 +185,10 @@ void skipOptionalNewline(Reader& reader)
{
switch (peek(reader))
{
- default:
- break;
+ default: break;
- case '\r': case '\n':
+ case '\r':
+ case '\n':
{
int c = get(reader);
handleNewline(reader, c);
@@ -218,12 +203,7 @@ enum
kNodeReadFlag_AllowEscape = 1 << 0,
};
-Node* readBody(
- Reader& reader,
- NodeReadFlags flags,
- char openChar,
- int openCount,
- char closeChar)
+Node* readBody(Reader& reader, NodeReadFlags flags, char openChar, int openCount, char closeChar)
{
while (peek(reader) == openChar)
{
@@ -245,9 +225,7 @@ Node* readBody(
switch (c)
{
- default:
- atStartOfLine = false;
- break;
+ default: atStartOfLine = false; break;
case EOF:
{
@@ -255,7 +233,8 @@ Node* readBody(
return nodes;
}
- case '{': case '(':
+ case '{':
+ case '(':
if (c == openChar)
{
depth++;
@@ -263,7 +242,8 @@ Node* readBody(
atStartOfLine = false;
break;
- case ')': case '}':
+ case ')':
+ case '}':
if (c == closeChar)
{
char const* spanEnd = reader.cursor - 1;
@@ -302,10 +282,11 @@ Node* readBody(
break;
- case ' ': case '\t':
- break;
+ case ' ':
+ case '\t': break;
- case '\r': case '\n':
+ case '\r':
+ case '\n':
{
addTextSpan(link, spanBegin, reader.cursor);
@@ -332,12 +313,7 @@ Node* readBody(
//
addTextSpan(link, spanBegin, spanEnd);
- Node* body = readBody(
- reader,
- 0,
- '(',
- 0,
- ')');
+ Node* body = readBody(reader, 0, '(', 0, ')');
addSpliceSpan(link, body);
@@ -351,12 +327,7 @@ Node* readBody(
addTextSpan(link, spanBegin, lineBegin);
- Node* body = readBody(
- reader,
- 0,
- '{',
- 0,
- '}');
+ Node* body = readBody(reader, 0, '{', 0, '}');
addEscapeSpan(link, body);
@@ -384,16 +355,12 @@ Node* readBody(
int c = get(reader);
switch (c)
{
- default:
- continue;
+ default: continue;
- case EOF:
- break;
+ case EOF: break;
case '\r':
- case '\n':
- handleNewline(reader, c);
- break;
+ case '\n': handleNewline(reader, c); break;
}
break;
@@ -436,43 +403,30 @@ Node* readBody(
break;
}
}
-
}
-Node* readInput(
- char const* inputBegin,
- char const* inputEnd)
+Node* readInput(char const* inputBegin, char const* inputEnd)
{
Reader reader;
reader.cursor = inputBegin;
reader.end = inputEnd;
- return readBody(
- reader,
- kNodeReadFlag_AllowEscape,
- -2,
- 0,
- -2);
+ return readBody(reader, kNodeReadFlag_AllowEscape, -2, 0, -2);
}
-void emitRaw(
- FILE* stream,
- char const* begin,
- char const* end)
+void emitRaw(FILE* stream, char const* begin, char const* end)
{
// We will write the raw text to our output file.
// TODO: need to output `#line` directives as well
fputs("sb << \"", stream);
- for( char const* cc = begin; cc != end; ++cc )
+ for (char const* cc = begin; cc != end; ++cc)
{
int c = *cc;
- switch( c )
+ switch (c)
{
- case '\\':
- fputs("\\\\", stream);
- break;
+ case '\\': fputs("\\\\", stream); break;
case '\r': break;
case '\t': fputs("\\t", stream); break;
@@ -483,7 +437,7 @@ void emitRaw(
break;
default:
- if((c >= 32) && (c <= 126))
+ if ((c >= 32) && (c <= 126))
{
fputc(c, stream);
}
@@ -492,35 +446,27 @@ void emitRaw(
assert(false);
}
}
-
}
fprintf(stream, "\";\n");
}
-void emitCode(
- FILE* stream,
- char const* begin,
- char const* end)
+void emitCode(FILE* stream, char const* begin, char const* end)
{
- for( auto cc = begin; cc != end; ++cc )
+ for (auto cc = begin; cc != end; ++cc)
{
- if(*cc == '\r')
+ if (*cc == '\r')
continue;
fputc(*cc, stream);
}
}
-void emit(
- FILE* stream,
- char const* text)
+void emit(FILE* stream, char const* text)
{
fprintf(stream, "%s", text);
}
-void emit(
- FILE* stream,
- StringSpan const& span)
+void emit(FILE* stream, StringSpan const& span)
{
fprintf(stream, "%.*s", int(span.end() - span.begin()), span.begin());
}
@@ -530,9 +476,7 @@ bool isASCIIPrintable(int c)
return (c >= 0x20) && (c <= 0x7E);
}
-void emitStringLiteralText(
- FILE* stream,
- StringSpan const& span)
+void emitStringLiteralText(FILE* stream, StringSpan const& span)
{
char const* cursor = span.begin();
char const* end = span.end();
@@ -542,25 +486,16 @@ void emitStringLiteralText(
int c = *cursor++;
switch (c)
{
- case '\r': case '\n':
- fprintf(stream, "\\n");
- break;
+ case '\r':
+ case '\n': fprintf(stream, "\\n"); break;
- case '\t':
- fprintf(stream, "\\t");
- break;
+ case '\t': fprintf(stream, "\\t"); break;
- case ' ':
- fprintf(stream, " ");
- break;
+ case ' ': fprintf(stream, " "); break;
- case '"':
- fprintf(stream, "\\\"");
- break;
+ case '"': fprintf(stream, "\\\""); break;
- case '\\':
- fprintf(stream, "\\\\");
- break;
+ case '\\': fprintf(stream, "\\\\"); break;
default:
if (isASCIIPrintable(c))
@@ -576,9 +511,7 @@ void emitStringLiteralText(
}
}
-void emitSimpleText(
- FILE* stream,
- StringSpan const& span)
+void emitSimpleText(FILE* stream, StringSpan const& span)
{
UnownedStringSlice content(span), line;
while (StringUtil::extractLine(content, line))
@@ -587,7 +520,8 @@ void emitSimpleText(
fwrite(line.begin(), 1, line.getLength(), stream);
// Specially handle the 'final line', excluding an empty line after \n.
- // We can detect, as if input ends with 'cr/lf' combination, content.begin == span.end(), else if content.begin() == nullptr.
+ // We can detect, as if input ends with 'cr/lf' combination, content.begin == span.end(),
+ // else if content.begin() == nullptr.
if (content.begin() == nullptr || content.begin() == span.end())
{
break;
@@ -597,9 +531,7 @@ void emitSimpleText(
}
}
-void emitCodeNodes(
- FILE* stream,
- Node* node)
+void emitCodeNodes(FILE* stream, Node* node)
{
for (auto nn = node; nn; nn = nn->next)
{
@@ -610,9 +542,7 @@ void emitCodeNodes(
emit(stream, "\n");
break;
- default:
- throw "unexpected";
- break;
+ default: throw "unexpected"; break;
}
}
}
@@ -646,10 +576,7 @@ static Index _findLineIndex(const List<UnownedStringSlice>& lineBreaks, const ch
return lo;
}
-void emitTemplateNodes(
- SourceFile* sourceFile,
- FILE* stream,
- Node* node)
+void emitTemplateNodes(SourceFile* sourceFile, FILE* stream, Node* node)
{
// Work out
List<UnownedStringSlice> lineBreaks;
@@ -660,7 +587,8 @@ void emitTemplateNodes(
{
// If we transition from escape to text, insert line number directive
bool enable = true;
- if (enable && prev && prev->flavor == Node::Flavor::escape && nn->flavor == Node::Flavor::text)
+ if (enable && prev && prev->flavor == Node::Flavor::escape &&
+ nn->flavor == Node::Flavor::text)
{
// Find the line
Index lineIndex = _findLineIndex(lineBreaks, nn->span.begin());
@@ -668,7 +596,8 @@ void emitTemplateNodes(
if (lineIndex >= 0)
{
StringBuilder buf;
- buf << "SLANG_RAW(\"#line " << (lineIndex + 1) << " \\\"" << sourceFile->linePath << "\\\"\")\n";
+ buf << "SLANG_RAW(\"#line " << (lineIndex + 1) << " \\\"" << sourceFile->linePath
+ << "\\\"\")\n";
emit(stream, buf.getUnownedSlice());
}
@@ -688,10 +617,8 @@ void emitTemplateNodes(
emit(stream, ")\n");
break;
- case Node::Flavor::escape:
- emitCodeNodes(stream, nn->body);
- break;
- }
+ case Node::Flavor::escape: emitCodeNodes(stream, nn->body); break;
+ }
}
}
@@ -700,7 +627,7 @@ void usage(char const* appName)
fprintf(stderr, "usage: %s [FILE]... [--target-directory FILE]\n", appName);
}
-SlangResult readAllText(char const * fileName, String& outString)
+SlangResult readAllText(char const* fileName, String& outString)
{
FILE* f;
fopen_s(&f, fileName, "rb");
@@ -714,13 +641,14 @@ SlangResult readAllText(char const * fileName, String& outString)
fseek(f, 0, SEEK_END);
auto size = ftell(f);
- StringRepresentation* stringRep = StringRepresentation::createWithCapacityAndLength(size, size);
+ StringRepresentation* stringRep =
+ StringRepresentation::createWithCapacityAndLength(size, size);
outString = String(stringRep);
char* buffer = stringRep->getData();
// Seems unnecessary
- //memset(buffer, 0, size);
+ // memset(buffer, 0, size);
fseek(f, 0, SEEK_SET);
size_t readCount = fread(buffer, sizeof(char), size, f);
@@ -730,7 +658,7 @@ SlangResult readAllText(char const * fileName, String& outString)
}
}
-void writeAllText(char const *srcFileName, char const* fileName, const char* content)
+void writeAllText(char const* srcFileName, char const* fileName, const char* content)
{
FILE* f = nullptr;
fopen_s(&f, fileName, "wb");
@@ -745,8 +673,7 @@ void writeAllText(char const *srcFileName, char const* fileName, const char* con
}
}
-#define PARSE_HANDLER(NAME) \
- Node* NAME(StringSpan const& text)
+#define PARSE_HANDLER(NAME) Node* NAME(StringSpan const& text)
typedef PARSE_HANDLER((*ParseHandler));
@@ -769,7 +696,6 @@ PARSE_HANDLER(parseUnknownFile)
}
-
Node* parseSourceFile(SourceFile* file)
{
auto path = file->inputPath;
@@ -777,14 +703,13 @@ Node* parseSourceFile(SourceFile* file)
static const struct
{
- char const* extension;
- ParseHandler handler;
- } kHandlers[] =
- {
- { ".meta.slang", &parseTemplateFile },
- { ".meta.cpp", &parseTemplateFile },
- { ".cpp", &parseCxxFile },
- { "", &parseUnknownFile },
+ char const* extension;
+ ParseHandler handler;
+ } kHandlers[] = {
+ {".meta.slang", &parseTemplateFile},
+ {".meta.cpp", &parseTemplateFile},
+ {".cpp", &parseCxxFile},
+ {"", &parseUnknownFile},
};
for (auto hh : kHandlers)
@@ -799,12 +724,11 @@ Node* parseSourceFile(SourceFile* file)
}
-
SourceFile* parseSourceFile(const String& path)
{
FILE* inputStream;
fopen_s(&inputStream, path.getBuffer(), "rb");
- if(!inputStream)
+ if (!inputStream)
{
fprintf(stderr, "unable to read input file: %s\n", path.getBuffer());
return nullptr;
@@ -814,7 +738,7 @@ SourceFile* parseSourceFile(const String& path)
fseek(inputStream, 0, SEEK_SET);
char* input = (char*)malloc(inputSize + 1);
- if(fread(input, inputSize, 1, inputStream) != 1)
+ if (fread(input, inputSize, 1, inputStream) != 1)
{
fprintf(stderr, "unable to read input file: %s\n", path.getBuffer());
return nullptr;
@@ -828,8 +752,8 @@ SourceFile* parseSourceFile(const String& path)
sourceFile->inputPath = path;
- // We use the fileName as the line path, as the path as passed to the command could contain a complicated
- // depending on the project location.
+ // We use the fileName as the line path, as the path as passed to the command could contain a
+ // complicated depending on the project location.
sourceFile->linePath = Path::getFileName(path);
sourceFile->text = span;
@@ -844,9 +768,7 @@ SourceFile* parseSourceFile(const String& path)
List<RefPtr<SourceFile>> gSourceFiles;
-int main(
- int argc,
- const char*const* argv)
+int main(int argc, const char* const* argv)
{
// Parse command-line arguments.
List<String> inputPaths;
@@ -854,10 +776,10 @@ int main(
char const* appName = "slang-generate";
{
- const char*const* argCursor = argv;
- const char*const* argEnd = argv + argc;
+ const char* const* argCursor = argv;
+ const char* const* argEnd = argv + argc;
// Copy the app name
- if( argCursor != argEnd )
+ if (argCursor != argEnd)
{
appName = *argCursor++;
}
@@ -865,10 +787,10 @@ int main(
for (; argCursor != argEnd; ++argCursor)
{
const auto arg = UnownedStringSlice(*argCursor);
- if(arg == "--target-directory")
+ if (arg == "--target-directory")
{
argCursor++;
- if(argCursor == argEnd)
+ if (argCursor == argEnd)
{
usage(appName);
fprintf(stderr, "--target-directory expects an argument\n");
@@ -885,7 +807,7 @@ int main(
}
}
- if(inputPaths.getCount() == 0)
+ if (inputPaths.getCount() == 0)
{
usage(appName);
exit(1);
@@ -893,7 +815,7 @@ int main(
// Read each input file and process it according
// to the type of treatment it requires.
- for (auto& inputPath: inputPaths)
+ for (auto& inputPath : inputPaths)
{
SourceFile* sourceFile = parseSourceFile(inputPath);
gSourceFiles.add(sourceFile);
@@ -901,7 +823,7 @@ int main(
for (auto sourceFile : gSourceFiles)
{
- if(!sourceFile)
+ if (!sourceFile)
{
fprintf(stderr, "failed to parse source files\n");
exit(1);
@@ -933,7 +855,7 @@ int main(
// update final output only when content has changed
StringBuilder outputPathFinal;
- if(outputDir.getLength())
+ if (outputDir.getLength())
outputPathFinal << outputDir << "/" << Slang::Path::getFileName(inputPath) << ".h";
else
outputPathFinal << inputPath << ".h";
@@ -943,7 +865,10 @@ int main(
readAllText(outputPath.getBuffer(), allTextNew);
if (allTextOld != allTextNew)
{
- writeAllText(inputPath.getBuffer(), outputPathFinal.getBuffer(), allTextNew.getBuffer());
+ writeAllText(
+ inputPath.getBuffer(),
+ outputPathFinal.getBuffer(),
+ allTextNew.getBuffer());
}
remove(outputPath.getBuffer());
}
diff --git a/tools/slang-lookup-generator/lookup-generator-main.cpp b/tools/slang-lookup-generator/lookup-generator-main.cpp
index 5806d6397..129e9ff3d 100644
--- a/tools/slang-lookup-generator/lookup-generator-main.cpp
+++ b/tools/slang-lookup-generator/lookup-generator-main.cpp
@@ -1,6 +1,5 @@
// perfect-hash-main.cpp
-#include <stdio.h>
#include "../../source/compiler-core/slang-json-parser.h"
#include "../../source/compiler-core/slang-json-value.h"
#include "../../source/compiler-core/slang-lexer.h"
@@ -9,6 +8,8 @@
#include "../../source/core/slang-secure-crt.h"
#include "../../source/core/slang-string-util.h"
+#include <stdio.h>
+
using namespace Slang;
static SlangResult parseJson(const char* inputPath, DiagnosticSink* sink, JSONListener& listener)
@@ -17,10 +18,10 @@ static SlangResult parseJson(const char* inputPath, DiagnosticSink* sink, JSONLi
String contents;
SLANG_RETURN_ON_FAIL(File::readAllText(inputPath, contents));
- PathInfo pathInfo = PathInfo::makeFromString(inputPath);
+ PathInfo pathInfo = PathInfo::makeFromString(inputPath);
SourceFile* sourceFile = sourceManager->createSourceFileWithString(pathInfo, contents);
SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc());
- JSONLexer lexer;
+ JSONLexer lexer;
lexer.init(sourceView, sink);
JSONParser parser;
SLANG_RETURN_ON_FAIL(parser.parse(&lexer, sourceView, &listener, sink));
@@ -30,7 +31,10 @@ static SlangResult parseJson(const char* inputPath, DiagnosticSink* sink, JSONLi
// Extract from a json value, the "opname" member from all the objects in the
// "instructions" array.
// Returns the empty list on failure
-static List<String> extractOpNames(UnownedStringSlice& error, const JSONValue& v, JSONContainer& container)
+static List<String> extractOpNames(
+ UnownedStringSlice& error,
+ const JSONValue& v,
+ JSONContainer& container)
{
List<String> opnames;
@@ -53,7 +57,8 @@ static List<String> extractOpNames(UnownedStringSlice& error, const JSONValue& v
const auto instructions = container.findObjectValue(v, instKey);
if (!instructions.isValid() || instructions.type != JSONValue::Type::Array)
{
- error = UnownedStringSlice("JSON parsing failed, no \"instructions\" member of array type\n");
+ error =
+ UnownedStringSlice("JSON parsing failed, no \"instructions\" member of array type\n");
return {};
}
for (const auto& inst : container.getArray(instructions))
@@ -61,7 +66,8 @@ static List<String> extractOpNames(UnownedStringSlice& error, const JSONValue& v
const auto opname = container.findObjectValue(inst, opnameKey);
if (!opname.isValid() || opname.getKind() != JSONValue::Kind::String)
{
- error = UnownedStringSlice("JSON parsing failed, no \"opname\" member of string type for instruction\n");
+ error = UnownedStringSlice(
+ "JSON parsing failed, no \"opname\" member of string type for instruction\n");
return {};
}
opnames.add(container.getString(opname));
@@ -102,7 +108,7 @@ int main(int argc, const char* const* argv)
const char* const enumHeader = argv[5];
RefPtr<FileWriter> writer(new FileWriter(stderr, WriterFlag::AutoFlush));
- SourceManager sourceManager;
+ SourceManager sourceManager;
sourceManager.initialize(nullptr, nullptr);
DiagnosticSink sink(&sourceManager, Lexer::sourceLocationLexer);
sink.writer = writer;
@@ -113,7 +119,7 @@ int main(int argc, const char* const* argv)
{
// If source is a json file parse it.
JSONContainer container(sink.getSourceManager());
- JSONBuilder builder(&container);
+ JSONBuilder builder(&container);
if (SLANG_FAILED(parseJson(inPath, &sink, builder)))
{
sink.diagnoseRaw(Severity::Error, "Json parsing failed\n");
@@ -139,7 +145,13 @@ int main(int argc, const char* const* argv)
opnames.add(w);
}
- if (SLANG_FAILED(writePerfectHashLookupCppFile(outCppPath, opnames, enumName, enumerantPrefix, enumHeader, &sink)))
+ if (SLANG_FAILED(writePerfectHashLookupCppFile(
+ outCppPath,
+ opnames,
+ enumName,
+ enumerantPrefix,
+ enumHeader,
+ &sink)))
return -1;
return 0;
diff --git a/tools/slang-profile/slang-profile-main.cpp b/tools/slang-profile/slang-profile-main.cpp
index d23a7ba10..08e74a350 100644
--- a/tools/slang-profile/slang-profile-main.cpp
+++ b/tools/slang-profile/slang-profile-main.cpp
@@ -1,13 +1,10 @@
// slang-profile-main.cpp
#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-std-writers.h"
-
#include "../../source/core/slang-process-util.h"
-
-#include "slang-com-helper.h"
-
+#include "../../source/core/slang-std-writers.h"
#include "../../source/core/slang-string-util.h"
+#include "slang-com-helper.h"
using namespace Slang;
diff --git a/tools/slang-reflection-test/slang-reflection-test-main.cpp b/tools/slang-reflection-test/slang-reflection-test-main.cpp
index fb8d4e30a..a6903fa86 100644
--- a/tools/slang-reflection-test/slang-reflection-test-main.cpp
+++ b/tools/slang-reflection-test/slang-reflection-test-main.cpp
@@ -1,53 +1,47 @@
// slang-reflection-test-main.cpp
+#include "../../source/core/slang-char-util.h"
+#include "../../source/core/slang-string-escape-util.h"
+#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-test-tool-util.h"
+#include "slang-com-helper.h"
+#include "slang.h"
+
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include "slang.h"
-#include "slang-com-helper.h"
-
-#include "../../source/core/slang-string-escape-util.h"
-#include "../../source/core/slang-char-util.h"
-#include "../../source/core/slang-string-util.h"
-
-#include "../../source/core/slang-test-tool-util.h"
-
using namespace Slang;
template<typename T>
struct Range
{
public:
- Range(
- T begin,
- T end)
- : m_begin(begin)
- , m_end(end)
- {}
+ Range(T begin, T end)
+ : m_begin(begin), m_end(end)
+ {
+ }
struct Iterator
{
public:
explicit Iterator(T value)
: m_value(value)
- {}
+ {
+ }
T operator*() const { return m_value; }
void operator++() { m_value++; }
- bool operator!=(Iterator const& other)
- {
- return m_value != other.m_value;
- }
+ bool operator!=(Iterator const& other) { return m_value != other.m_value; }
private:
T m_value;
};
Iterator begin() const { return Iterator(m_begin); }
- Iterator end() const { return Iterator(m_end); }
+ Iterator end() const { return Iterator(m_end); }
private:
T m_begin;
@@ -81,37 +75,37 @@ struct PrettyWriter
void writeRaw(const UnownedStringSlice& slice) { m_builder.append(slice); }
void writeRaw(char const* begin, char const* end);
void writeRaw(PrettyWriter& writer, char const* begin) { writeRaw(UnownedStringSlice(begin)); }
-
+
void writeRawChar(int c) { m_builder.appendChar(char(c)); }
void writeHexChar(int c) { writeRawChar(CharUtil::getHexChar(Index(c))); }
- /// Adjusts indentation if at start of a line
+ /// Adjusts indentation if at start of a line
void adjust();
- /// Increase indentation
+ /// Increase indentation
void indent() { m_indent++; }
- /// Decreate indentation
+ /// Decreate indentation
void dedent();
- /// Write taking into account any CR that might be in a slice
+ /// Write taking into account any CR that might be in a slice
void write(const UnownedStringSlice& slice);
void write(char const* text) { write(UnownedStringSlice(text)); }
void write(char const* text, size_t length) { write(UnownedStringSlice(text, length)); }
- /// Write the slice as an escaped string
+ /// Write the slice as an escaped string
void writeEscapedString(const UnownedStringSlice& slice);
- /// Call before items in a comma-separated JSON list to emit the comma if/when needed
+ /// Call before items in a comma-separated JSON list to emit the comma if/when needed
void maybeComma();
- /// Get the builder the result is being constructed in
+ /// Get the builder the result is being constructed in
StringBuilder& getBuilder() { return m_builder; }
- ThisType& operator<<(const UnownedStringSlice& slice)
- {
- write(slice);
- return *this;
+ ThisType& operator<<(const UnownedStringSlice& slice)
+ {
+ write(slice);
+ return *this;
}
ThisType& operator<<(const char* text)
{
@@ -145,7 +139,8 @@ struct PrettyWriter
ThisType& operator<<(float val)
{
adjust();
- // We want to use a specific format, so we use the StringUtil to specify format, and not just use <<
+ // We want to use a specific format, so we use the StringUtil to specify format, and not
+ // just use <<
StringUtil::appendFormat(m_builder, "%f", val);
return *this;
}
@@ -169,7 +164,7 @@ void PrettyWriter::adjust()
{
// Output current indentation
m_builder.appendRepeatedChar(' ', m_indent * 4);
- m_startOfLine = false;
+ m_startOfLine = false;
}
}
@@ -189,7 +184,8 @@ void PrettyWriter::write(const UnownedStringSlice& slice)
const char* cur = start;
// Search for \n if there is one
- while (cur < end && *cur != '\n') cur++;
+ while (cur < end && *cur != '\n')
+ cur++;
// If there were some chars, adjust and write
if (cur > start)
@@ -232,20 +228,16 @@ void PrettyWriter::maybeComma()
write(toSlice(",\n"));
}
- /// Type for tracking whether a comma is needed in a comma-separated JSON list
+/// Type for tracking whether a comma is needed in a comma-separated JSON list
struct CommaTrackerRAII
{
CommaTrackerRAII(PrettyWriter& writer)
- : m_writer(&writer)
- , m_previousState(writer.m_commaState)
+ : m_writer(&writer), m_previousState(writer.m_commaState)
{
writer.m_commaState = &m_state;
}
- ~CommaTrackerRAII()
- {
- m_writer->m_commaState = m_previousState;
- }
+ ~CommaTrackerRAII() { m_writer->m_commaState = m_previousState; }
private:
PrettyWriter::CommaState m_state;
@@ -259,13 +251,13 @@ static void emitReflectionTypeLayoutJSON(PrettyWriter& writer, slang::TypeLayout
static void emitReflectionTypeJSON(PrettyWriter& writer, slang::TypeReflection* type);
static void emitReflectionVarBindingInfoJSON(
- PrettyWriter& writer,
- SlangParameterCategory category,
- SlangUInt index,
- SlangUInt count,
- SlangUInt space = 0)
+ PrettyWriter& writer,
+ SlangParameterCategory category,
+ SlangUInt index,
+ SlangUInt count,
+ SlangUInt space = 0)
{
- if( category == SLANG_PARAMETER_CATEGORY_UNIFORM )
+ if (category == SLANG_PARAMETER_CATEGORY_UNIFORM)
{
writer << "\"kind\": \"uniform\"";
writer << ", ";
@@ -276,25 +268,26 @@ static void emitReflectionVarBindingInfoJSON(
else
{
writer << "\"kind\": \"";
- switch( category )
+ switch (category)
{
- #define CASE(NAME, KIND) case SLANG_PARAMETER_CATEGORY_##NAME: writer.write(toSlice(#KIND)); break
- CASE(CONSTANT_BUFFER, constantBuffer);
- CASE(SHADER_RESOURCE, shaderResource);
- CASE(UNORDERED_ACCESS, unorderedAccess);
- CASE(VARYING_INPUT, varyingInput);
- CASE(VARYING_OUTPUT, varyingOutput);
- CASE(SAMPLER_STATE, samplerState);
- CASE(UNIFORM, uniform);
- CASE(PUSH_CONSTANT_BUFFER, pushConstantBuffer);
- CASE(DESCRIPTOR_TABLE_SLOT, descriptorTableSlot);
- CASE(SPECIALIZATION_CONSTANT, specializationConstant);
- CASE(MIXED, mixed);
- CASE(REGISTER_SPACE, registerSpace);
- CASE(SUB_ELEMENT_REGISTER_SPACE, subElementRegisterSpace);
- CASE(GENERIC, generic);
- CASE(METAL_ARGUMENT_BUFFER_ELEMENT, metalArgumentBufferElement);
- #undef CASE
+#define CASE(NAME, KIND) \
+ case SLANG_PARAMETER_CATEGORY_##NAME: writer.write(toSlice(#KIND)); break
+ CASE(CONSTANT_BUFFER, constantBuffer);
+ CASE(SHADER_RESOURCE, shaderResource);
+ CASE(UNORDERED_ACCESS, unorderedAccess);
+ CASE(VARYING_INPUT, varyingInput);
+ CASE(VARYING_OUTPUT, varyingOutput);
+ CASE(SAMPLER_STATE, samplerState);
+ CASE(UNIFORM, uniform);
+ CASE(PUSH_CONSTANT_BUFFER, pushConstantBuffer);
+ CASE(DESCRIPTOR_TABLE_SLOT, descriptorTableSlot);
+ CASE(SPECIALIZATION_CONSTANT, specializationConstant);
+ CASE(MIXED, mixed);
+ CASE(REGISTER_SPACE, registerSpace);
+ CASE(SUB_ELEMENT_REGISTER_SPACE, subElementRegisterSpace);
+ CASE(GENERIC, generic);
+ CASE(METAL_ARGUMENT_BUFFER_ELEMENT, metalArgumentBufferElement);
+#undef CASE
default:
writer << "unknown";
@@ -302,7 +295,7 @@ static void emitReflectionVarBindingInfoJSON(
break;
}
writer << "\"";
- if( space && category != SLANG_PARAMETER_CATEGORY_REGISTER_SPACE)
+ if (space && category != SLANG_PARAMETER_CATEGORY_REGISTER_SPACE)
{
writer << ", ";
writer << "\"space\": " << space;
@@ -310,11 +303,11 @@ static void emitReflectionVarBindingInfoJSON(
writer << ", ";
writer << "\"index\": ";
writer << index;
- if( count != 1)
+ if (count != 1)
{
writer << ", ";
writer << "\"count\": ";
- if( count == SLANG_UNBOUNDED_SIZE )
+ if (count == SLANG_UNBOUNDED_SIZE)
{
writer << "\"unbounded\"";
}
@@ -327,10 +320,10 @@ static void emitReflectionVarBindingInfoJSON(
}
static void emitReflectionVarBindingInfoJSON(
- PrettyWriter& writer,
- slang::VariableLayoutReflection* var,
- SlangCompileRequest* request = nullptr,
- int entryPointIndex = -1)
+ PrettyWriter& writer,
+ slang::VariableLayoutReflection* var,
+ SlangCompileRequest* request = nullptr,
+ int entryPointIndex = -1)
{
auto stage = var->getStage();
if (stage != SLANG_STAGE_NONE)
@@ -339,15 +332,14 @@ static void emitReflectionVarBindingInfoJSON(
char const* stageName = "UNKNOWN";
switch (stage)
{
- case SLANG_STAGE_VERTEX: stageName = "vertex"; break;
- case SLANG_STAGE_HULL: stageName = "hull"; break;
- case SLANG_STAGE_DOMAIN: stageName = "domain"; break;
- case SLANG_STAGE_GEOMETRY: stageName = "geometry"; break;
- case SLANG_STAGE_FRAGMENT: stageName = "fragment"; break;
- case SLANG_STAGE_COMPUTE: stageName = "compute"; break;
-
- default:
- break;
+ case SLANG_STAGE_VERTEX: stageName = "vertex"; break;
+ case SLANG_STAGE_HULL: stageName = "hull"; break;
+ case SLANG_STAGE_DOMAIN: stageName = "domain"; break;
+ case SLANG_STAGE_GEOMETRY: stageName = "geometry"; break;
+ case SLANG_STAGE_FRAGMENT: stageName = "fragment"; break;
+ case SLANG_STAGE_COMPUTE: stageName = "compute"; break;
+
+ default: break;
}
writer << "\"stage\": \"" << stageName << "\"";
@@ -359,7 +351,7 @@ static void emitReflectionVarBindingInfoJSON(
if (categoryCount)
{
writer.maybeComma();
- if( categoryCount != 1 )
+ if (categoryCount != 1)
{
writer << "\"bindings\": [\n";
}
@@ -369,7 +361,7 @@ static void emitReflectionVarBindingInfoJSON(
}
writer.indent();
- for(uint32_t cc = 0; cc < categoryCount; ++cc )
+ for (uint32_t cc = 0; cc < categoryCount; ++cc)
{
auto category = SlangParameterCategory(var->getCategoryByIndex(cc));
auto index = var->getOffset(category);
@@ -377,21 +369,25 @@ static void emitReflectionVarBindingInfoJSON(
auto count = typeLayout->getSize(category);
// Query the paramater usage for the specified entry point.
- // Note: both `request` and `entryPointIndex` may be invalid here, but that should just make the function return a failure.
+ // Note: both `request` and `entryPointIndex` may be invalid here, but that should just
+ // make the function return a failure.
bool used = false;
- bool usedAvailable = spIsParameterLocationUsed(request, entryPointIndex, 0, category, space, index, used) == SLANG_OK;
-
- if (cc != 0) writer << ",\n";
+ bool usedAvailable = spIsParameterLocationUsed(
+ request,
+ entryPointIndex,
+ 0,
+ category,
+ space,
+ index,
+ used) == SLANG_OK;
+
+ if (cc != 0)
+ writer << ",\n";
writer << "{";
-
- emitReflectionVarBindingInfoJSON(
- writer,
- category,
- index,
- count,
- space);
-
+
+ emitReflectionVarBindingInfoJSON(writer, category, index, count, space);
+
if (usedAvailable)
{
writer << ", \"used\": ";
@@ -402,7 +398,7 @@ static void emitReflectionVarBindingInfoJSON(
}
writer.dedent();
- if( categoryCount != 1 )
+ if (categoryCount != 1)
{
writer << "\n]";
}
@@ -422,9 +418,7 @@ static void emitReflectionVarBindingInfoJSON(
}
}
-static void emitReflectionNameInfoJSON(
- PrettyWriter& writer,
- char const* name)
+static void emitReflectionNameInfoJSON(PrettyWriter& writer, char const* name)
{
// TODO: deal with escaping special characters if/when needed
writer << "\"name\": ";
@@ -433,11 +427,9 @@ static void emitReflectionNameInfoJSON(
static void emitUserAttributes(PrettyWriter& writer, slang::VariableReflection* var);
-static void emitReflectionModifierInfoJSON(
- PrettyWriter& writer,
- slang::VariableReflection* var)
+static void emitReflectionModifierInfoJSON(PrettyWriter& writer, slang::VariableReflection* var)
{
- if( var->findModifier(slang::Modifier::Shared) )
+ if (var->findModifier(slang::Modifier::Shared))
{
writer.maybeComma();
writer << "\"shared\": true";
@@ -516,16 +508,14 @@ static void emitUserAttributes(PrettyWriter& writer, slang::VariableReflection*
}
}
-static void emitReflectionVarLayoutJSON(
- PrettyWriter& writer,
- slang::VariableLayoutReflection* var)
+static void emitReflectionVarLayoutJSON(PrettyWriter& writer, slang::VariableLayoutReflection* var)
{
writer << "{\n";
writer.indent();
CommaTrackerRAII commaTracker(writer);
- if( auto name = var->getName() )
+ if (auto name = var->getName())
{
writer.maybeComma();
emitReflectionNameInfoJSON(writer, name);
@@ -544,9 +534,7 @@ static void emitReflectionVarLayoutJSON(
writer << "\n}";
}
-static void emitReflectionScalarTypeInfoJSON(
- PrettyWriter& writer,
- SlangScalarType scalarType)
+static void emitReflectionScalarTypeInfoJSON(PrettyWriter& writer, SlangScalarType scalarType)
{
writer << "\"scalarType\": \"";
switch (scalarType)
@@ -555,7 +543,10 @@ static void emitReflectionScalarTypeInfoJSON(
writer << "unknown";
assert(!"unhandled case");
break;
-#define CASE(TAG, ID) case static_cast<SlangScalarType>(slang::TypeReflection::ScalarType::TAG): writer.write(toSlice(#ID)); break
+#define CASE(TAG, ID) \
+ case static_cast<SlangScalarType>(slang::TypeReflection::ScalarType::TAG): \
+ writer.write(toSlice(#ID)); \
+ break
CASE(Void, void);
CASE(Bool, bool);
@@ -577,10 +568,10 @@ static void emitReflectionScalarTypeInfoJSON(
}
static void emitReflectionResourceTypeBaseInfoJSON(
- PrettyWriter& writer,
- slang::TypeReflection* type)
+ PrettyWriter& writer,
+ slang::TypeReflection* type)
{
- auto shape = type->getResourceShape();
+ auto shape = type->getResourceShape();
auto access = type->getResourceAccess();
writer.maybeComma();
writer << "\"kind\": \"resource\"";
@@ -593,7 +584,8 @@ static void emitReflectionResourceTypeBaseInfoJSON(
assert(!"unhandled case");
break;
-#define CASE(SHAPE, NAME) case SLANG_##SHAPE: writer.write(toSlice(#NAME)); break
+#define CASE(SHAPE, NAME) \
+ case SLANG_##SHAPE: writer.write(toSlice(#NAME)); break
CASE(TEXTURE_1D, texture1D);
CASE(TEXTURE_2D, texture2D);
CASE(TEXTURE_3D, texture3D);
@@ -620,37 +612,34 @@ static void emitReflectionResourceTypeBaseInfoJSON(
writer << "\"feedback\": true";
}
- if( access != SLANG_RESOURCE_ACCESS_READ )
+ if (access != SLANG_RESOURCE_ACCESS_READ)
{
writer.maybeComma();
writer << "\"access\": \"";
- switch(access)
+ switch (access)
{
default:
writer << "unknown";
assert(!"unhandled case");
break;
- case SLANG_RESOURCE_ACCESS_READ:
- break;
- case SLANG_RESOURCE_ACCESS_WRITE: writer << "write"; break;
- case SLANG_RESOURCE_ACCESS_READ_WRITE: writer << "readWrite"; break;
- case SLANG_RESOURCE_ACCESS_RASTER_ORDERED: writer << "rasterOrdered"; break;
- case SLANG_RESOURCE_ACCESS_APPEND: writer << "append"; break;
- case SLANG_RESOURCE_ACCESS_CONSUME: writer << "consume"; break;
- case SLANG_RESOURCE_ACCESS_FEEDBACK: writer << "feedback"; break;
+ case SLANG_RESOURCE_ACCESS_READ: break;
+ case SLANG_RESOURCE_ACCESS_WRITE: writer << "write"; break;
+ case SLANG_RESOURCE_ACCESS_READ_WRITE: writer << "readWrite"; break;
+ case SLANG_RESOURCE_ACCESS_RASTER_ORDERED: writer << "rasterOrdered"; break;
+ case SLANG_RESOURCE_ACCESS_APPEND: writer << "append"; break;
+ case SLANG_RESOURCE_ACCESS_CONSUME: writer << "consume"; break;
+ case SLANG_RESOURCE_ACCESS_FEEDBACK: writer << "feedback"; break;
}
writer << "\"";
}
}
-static void emitReflectionTypeInfoJSON(
- PrettyWriter& writer,
- slang::TypeReflection* type)
+static void emitReflectionTypeInfoJSON(PrettyWriter& writer, slang::TypeReflection* type)
{
auto kind = type->getKind();
- switch(kind)
+ switch (kind)
{
case slang::TypeReflection::Kind::SamplerState:
writer.maybeComma();
@@ -665,20 +654,17 @@ static void emitReflectionTypeInfoJSON(
// types, but current test output depends on the old behavior, so
// we only add result type output for structured buffers at first.
//
- auto shape = type->getResourceShape();
+ auto shape = type->getResourceShape();
switch (shape & SLANG_RESOURCE_BASE_SHAPE_MASK)
{
- default:
- break;
+ default: break;
case SLANG_STRUCTURED_BUFFER:
- if( auto resultType = type->getResourceResultType() )
+ if (auto resultType = type->getResourceResultType())
{
writer.maybeComma();
writer << "\"resultType\": ";
- emitReflectionTypeJSON(
- writer,
- resultType);
+ emitReflectionTypeJSON(writer, resultType);
}
break;
}
@@ -690,9 +676,7 @@ static void emitReflectionTypeInfoJSON(
writer << "\"kind\": \"constantBuffer\"";
writer.maybeComma();
writer << "\"elementType\": ";
- emitReflectionTypeJSON(
- writer,
- type->getElementType());
+ emitReflectionTypeJSON(writer, type->getElementType());
break;
case slang::TypeReflection::Kind::ParameterBlock:
@@ -700,9 +684,7 @@ static void emitReflectionTypeInfoJSON(
writer << "\"kind\": \"parameterBlock\"";
writer.maybeComma();
writer << "\"elementType\": ";
- emitReflectionTypeJSON(
- writer,
- type->getElementType());
+ emitReflectionTypeJSON(writer, type->getElementType());
break;
case slang::TypeReflection::Kind::TextureBuffer:
@@ -710,9 +692,7 @@ static void emitReflectionTypeInfoJSON(
writer << "\"kind\": \"textureBuffer\"";
writer.maybeComma();
writer << "\"elementType\": ";
- emitReflectionTypeJSON(
- writer,
- type->getElementType());
+ emitReflectionTypeJSON(writer, type->getElementType());
break;
case slang::TypeReflection::Kind::ShaderStorageBuffer:
@@ -720,18 +700,14 @@ static void emitReflectionTypeInfoJSON(
writer << "\"kind\": \"shaderStorageBuffer\"";
writer.maybeComma();
writer << "\"elementType\": ";
- emitReflectionTypeJSON(
- writer,
- type->getElementType());
+ emitReflectionTypeJSON(writer, type->getElementType());
break;
case slang::TypeReflection::Kind::Scalar:
writer.maybeComma();
writer << "\"kind\": \"scalar\"";
writer.maybeComma();
- emitReflectionScalarTypeInfoJSON(
- writer,
- SlangScalarType(type->getScalarType()));
+ emitReflectionScalarTypeInfoJSON(writer, SlangScalarType(type->getScalarType()));
break;
case slang::TypeReflection::Kind::Vector:
@@ -742,9 +718,7 @@ static void emitReflectionTypeInfoJSON(
writer << int(type->getElementCount());
writer.maybeComma();
writer << "\"elementType\": ";
- emitReflectionTypeJSON(
- writer,
- type->getElementType());
+ emitReflectionTypeJSON(writer, type->getElementType());
break;
case slang::TypeReflection::Kind::Matrix:
@@ -758,9 +732,7 @@ static void emitReflectionTypeInfoJSON(
writer << type->getColumnCount();
writer.maybeComma();
writer << "\"elementType\": ";
- emitReflectionTypeJSON(
- writer,
- type->getElementType());
+ emitReflectionTypeJSON(writer, type->getElementType());
break;
case slang::TypeReflection::Kind::Array:
@@ -797,12 +769,11 @@ static void emitReflectionTypeInfoJSON(
auto structType = type;
auto fieldCount = structType->getFieldCount();
- for( uint32_t ff = 0; ff < fieldCount; ++ff )
+ for (uint32_t ff = 0; ff < fieldCount; ++ff)
{
- if (ff != 0) writer << ",\n";
- emitReflectionVarInfoJSON(
- writer,
- structType->getFieldByIndex(ff));
+ if (ff != 0)
+ writer << ",\n";
+ emitReflectionVarInfoJSON(writer, structType->getFieldByIndex(ff));
}
writer.dedent();
writer << "\n]";
@@ -831,26 +802,22 @@ static void emitReflectionTypeInfoJSON(
writer.maybeComma();
writer << "\"kind\": \"DynamicResource\"";
break;
- default:
- assert(!"unhandled case");
- break;
+ default: assert(!"unhandled case"); break;
}
emitUserAttributes(writer, type);
}
static void emitReflectionParameterGroupTypeLayoutInfoJSON(
- PrettyWriter& writer,
- slang::TypeLayoutReflection* typeLayout,
- const char* kind)
+ PrettyWriter& writer,
+ slang::TypeLayoutReflection* typeLayout,
+ const char* kind)
{
writer << "\"kind\": \"";
writer.write(kind);
writer << "\"";
writer << ",\n\"elementType\": ";
- emitReflectionTypeLayoutJSON(
- writer,
- typeLayout->getElementTypeLayout());
+ emitReflectionTypeLayoutJSON(writer, typeLayout->getElementTypeLayout());
// Note: There is a subtle detail below when it comes to the
// container/element variable layouts that get nested inside
@@ -881,7 +848,7 @@ static void emitReflectionParameterGroupTypeLayoutInfoJSON(
// We thus have to guard here against the recursive path where
// we are emitting reflection info for the "container" part of things.
//
- // TODO: We should probably
+ // TODO: We should probably
{
CommaTrackerRAII commaTracker(writer);
@@ -894,20 +861,16 @@ static void emitReflectionParameterGroupTypeLayoutInfoJSON(
}
writer << ",\n\"elementVarLayout\": ";
- emitReflectionVarLayoutJSON(
- writer,
- typeLayout->getElementVarLayout());
+ emitReflectionVarLayoutJSON(writer, typeLayout->getElementVarLayout());
}
static void emitReflectionTypeLayoutInfoJSON(
- PrettyWriter& writer,
- slang::TypeLayoutReflection* typeLayout)
+ PrettyWriter& writer,
+ slang::TypeLayoutReflection* typeLayout)
{
- switch( typeLayout->getKind() )
+ switch (typeLayout->getKind())
{
- default:
- emitReflectionTypeInfoJSON(writer, typeLayout->getType());
- break;
+ default: emitReflectionTypeInfoJSON(writer, typeLayout->getType()); break;
case slang::TypeReflection::Kind::Pointer:
{
@@ -931,7 +894,7 @@ static void emitReflectionTypeLayoutInfoJSON(
}
else
{
- // TODO(JS): We will need to generate name that we will associate with this type
+ // TODO(JS): We will need to generate name that we will associate with this type
// as it doesn't seem to have one
writer.writeEscapedString(toSlice("unknown name!"));
SLANG_ASSERT(!"Doesn't have an associated name");
@@ -956,9 +919,7 @@ static void emitReflectionTypeLayoutInfoJSON(
writer.maybeComma();
writer << "\"elementType\": ";
- emitReflectionTypeLayoutJSON(
- writer,
- elementTypeLayout);
+ emitReflectionTypeLayoutJSON(writer, elementTypeLayout);
if (arrayTypeLayout->getSize(SLANG_PARAMETER_CATEGORY_UNIFORM) != 0)
{
@@ -975,7 +936,7 @@ static void emitReflectionTypeLayoutInfoJSON(
writer.maybeComma();
writer << "\"kind\": \"struct\"";
- if( auto name = structTypeLayout->getName() )
+ if (auto name = structTypeLayout->getName())
{
writer.maybeComma();
emitReflectionNameInfoJSON(writer, structTypeLayout->getName());
@@ -985,17 +946,15 @@ static void emitReflectionTypeLayoutInfoJSON(
writer.indent();
auto fieldCount = structTypeLayout->getFieldCount();
- for( uint32_t ff = 0; ff < fieldCount; ++ff )
+ for (uint32_t ff = 0; ff < fieldCount; ++ff)
{
- if (ff != 0) writer << ",\n";
- emitReflectionVarLayoutJSON(
- writer,
- structTypeLayout->getFieldByIndex(ff));
+ if (ff != 0)
+ writer << ",\n";
+ emitReflectionVarLayoutJSON(writer, structTypeLayout->getFieldByIndex(ff));
}
writer.dedent();
writer << "\n]";
emitUserAttributes(writer, structTypeLayout->getType());
-
}
break;
@@ -1017,9 +976,7 @@ static void emitReflectionTypeLayoutInfoJSON(
writer.maybeComma();
writer << "\"elementType\": ";
- emitReflectionTypeLayoutJSON(
- writer,
- typeLayout->getElementTypeLayout());
+ emitReflectionTypeLayoutJSON(writer, typeLayout->getElementTypeLayout());
break;
case slang::TypeReflection::Kind::GenericTypeParameter:
writer.maybeComma();
@@ -1052,13 +1009,11 @@ static void emitReflectionTypeLayoutInfoJSON(
{
emitReflectionResourceTypeBaseInfoJSON(writer, type);
- if( auto resultTypeLayout = typeLayout->getElementTypeLayout() )
+ if (auto resultTypeLayout = typeLayout->getElementTypeLayout())
{
writer.maybeComma();
writer << "\"resultType\": ";
- emitReflectionTypeLayoutJSON(
- writer,
- resultTypeLayout);
+ emitReflectionTypeLayoutJSON(writer, resultTypeLayout);
}
}
else if (shape & SLANG_TEXTURE_FEEDBACK_FLAG)
@@ -1082,8 +1037,8 @@ static void emitReflectionTypeLayoutInfoJSON(
}
static void emitReflectionTypeLayoutJSON(
- PrettyWriter& writer,
- slang::TypeLayoutReflection* typeLayout)
+ PrettyWriter& writer,
+ slang::TypeLayoutReflection* typeLayout)
{
CommaTrackerRAII commaTracker(writer);
writer << "{\n";
@@ -1093,9 +1048,7 @@ static void emitReflectionTypeLayoutJSON(
writer << "\n}";
}
-static void emitReflectionTypeJSON(
- PrettyWriter& writer,
- slang::TypeReflection* type)
+static void emitReflectionTypeJSON(PrettyWriter& writer, slang::TypeReflection* type)
{
CommaTrackerRAII commaTracker(writer);
writer << "{\n";
@@ -1105,9 +1058,7 @@ static void emitReflectionTypeJSON(
writer << "\n}";
}
-static void emitReflectionVarInfoJSON(
- PrettyWriter& writer,
- slang::VariableReflection* var)
+static void emitReflectionVarInfoJSON(PrettyWriter& writer, slang::VariableReflection* var)
{
emitReflectionNameInfoJSON(writer, var->getName());
@@ -1118,9 +1069,7 @@ static void emitReflectionVarInfoJSON(
emitReflectionTypeJSON(writer, var->getType());
}
-static void emitReflectionParamJSON(
- PrettyWriter& writer,
- slang::VariableLayoutReflection* param)
+static void emitReflectionParamJSON(PrettyWriter& writer, slang::VariableLayoutReflection* param)
{
// TODO: This function is likely redundant with `emitReflectionVarLayoutJSON`
// and we should try to collapse them into one.
@@ -1130,7 +1079,7 @@ static void emitReflectionParamJSON(
CommaTrackerRAII commaTracker(writer);
- if( auto name = param->getName() )
+ if (auto name = param->getName())
{
writer.maybeComma();
emitReflectionNameInfoJSON(writer, name);
@@ -1150,15 +1099,15 @@ static void emitReflectionParamJSON(
static void emitEntryPointParamJSON(
- PrettyWriter& writer,
- slang::VariableLayoutReflection* param,
- SlangCompileRequest* request,
- int entryPointIndex)
+ PrettyWriter& writer,
+ slang::VariableLayoutReflection* param,
+ SlangCompileRequest* request,
+ int entryPointIndex)
{
writer << "{\n";
writer.indent();
- if( auto name = param->getName() )
+ if (auto name = param->getName())
{
emitReflectionNameInfoJSON(writer, name);
}
@@ -1171,7 +1120,7 @@ static void emitEntryPointParamJSON(
static void emitReflectionTypeParamJSON(
- PrettyWriter& writer,
+ PrettyWriter& writer,
slang::TypeParameterReflection* typeParam)
{
writer << "{\n";
@@ -1184,7 +1133,8 @@ static void emitReflectionTypeParamJSON(
auto constraintCount = typeParam->getConstraintCount();
for (auto ee : makeRange(constraintCount))
{
- if (ee != 0) writer << ",\n";
+ if (ee != 0)
+ writer << ",\n";
writer << "{\n";
writer.indent();
CommaTrackerRAII commaTracker(writer);
@@ -1199,12 +1149,13 @@ static void emitReflectionTypeParamJSON(
}
static void emitReflectionEntryPointJSON(
- PrettyWriter& writer,
- SlangCompileRequest* request,
- slang::ShaderReflection* programReflection,
- int entryPointIndex)
+ PrettyWriter& writer,
+ SlangCompileRequest* request,
+ slang::ShaderReflection* programReflection,
+ int entryPointIndex)
{
- slang::EntryPointReflection* entryPoint = programReflection->getEntryPointByIndex(entryPointIndex);
+ slang::EntryPointReflection* entryPoint =
+ programReflection->getEntryPointByIndex(entryPointIndex);
writer << "{\n";
writer.indent();
@@ -1213,14 +1164,13 @@ static void emitReflectionEntryPointJSON(
switch (entryPoint->getStage())
{
- case SLANG_STAGE_VERTEX: writer << ",\n\"stage:\": \"vertex\""; break;
- case SLANG_STAGE_HULL: writer << ",\n\"stage:\": \"hull\""; break;
- case SLANG_STAGE_DOMAIN: writer << ",\n\"stage:\": \"domain\""; break;
- case SLANG_STAGE_GEOMETRY: writer << ",\n\"stage:\": \"geometry\""; break;
- case SLANG_STAGE_FRAGMENT: writer << ",\n\"stage:\": \"fragment\""; break;
- case SLANG_STAGE_COMPUTE: writer << ",\n\"stage:\": \"compute\""; break;
- default:
- break;
+ case SLANG_STAGE_VERTEX: writer << ",\n\"stage:\": \"vertex\""; break;
+ case SLANG_STAGE_HULL: writer << ",\n\"stage:\": \"hull\""; break;
+ case SLANG_STAGE_DOMAIN: writer << ",\n\"stage:\": \"domain\""; break;
+ case SLANG_STAGE_GEOMETRY: writer << ",\n\"stage:\": \"geometry\""; break;
+ case SLANG_STAGE_FRAGMENT: writer << ",\n\"stage:\": \"fragment\""; break;
+ case SLANG_STAGE_COMPUTE: writer << ",\n\"stage:\": \"compute\""; break;
+ default: break;
}
auto parameterCount = entryPoint->getParameterCount();
@@ -1229,9 +1179,10 @@ static void emitReflectionEntryPointJSON(
writer << ",\n\"parameters\": [\n";
writer.indent();
- for( auto pp : makeRange(parameterCount) )
+ for (auto pp : makeRange(parameterCount))
{
- if(pp != 0) writer << ",\n";
+ if (pp != 0)
+ writer << ",\n";
auto parameter = entryPoint->getParameterByIndex(pp);
emitReflectionParamJSON(writer, parameter);
@@ -1244,7 +1195,7 @@ static void emitReflectionEntryPointJSON(
{
writer << ",\n\"usesAnySampleRateInput\": true";
}
- if( auto resultVarLayout = entryPoint->getResultVarLayout() )
+ if (auto resultVarLayout = entryPoint->getResultVarLayout())
{
writer << ",\n\"result:\": ";
emitReflectionParamJSON(writer, resultVarLayout);
@@ -1258,7 +1209,8 @@ static void emitReflectionEntryPointJSON(
writer << ",\n\"threadGroupSize\": [";
for (int ii = 0; ii < 3; ++ii)
{
- if (ii != 0) writer << ", ";
+ if (ii != 0)
+ writer << ", ";
writer << threadGroupSize[ii];
}
writer << "]";
@@ -1271,9 +1223,10 @@ static void emitReflectionEntryPointJSON(
writer.indent();
auto parameterCount = programReflection->getParameterCount();
- for( auto pp : makeRange(parameterCount) )
+ for (auto pp : makeRange(parameterCount))
{
- if(pp != 0) writer << ",\n";
+ if (pp != 0)
+ writer << ",\n";
auto parameter = programReflection->getParameterByIndex(pp);
emitEntryPointParamJSON(writer, parameter, request, entryPointIndex);
@@ -1288,9 +1241,9 @@ static void emitReflectionEntryPointJSON(
}
static void emitReflectionJSON(
- PrettyWriter& writer,
- SlangCompileRequest* request,
- slang::ShaderReflection* programReflection)
+ PrettyWriter& writer,
+ SlangCompileRequest* request,
+ slang::ShaderReflection* programReflection)
{
writer << "{\n";
writer.indent();
@@ -1298,9 +1251,10 @@ static void emitReflectionJSON(
writer.indent();
auto parameterCount = programReflection->getParameterCount();
- for( auto pp : makeRange(parameterCount) )
+ for (auto pp : makeRange(parameterCount))
{
- if(pp != 0) writer << ",\n";
+ if (pp != 0)
+ writer << ",\n";
auto parameter = programReflection->getParameterByIndex(pp);
emitReflectionParamJSON(writer, parameter);
@@ -1314,10 +1268,11 @@ static void emitReflectionJSON(
{
writer << ",\n\"entryPoints\": [\n";
writer.indent();
-
+
for (auto ee : makeRange(entryPointCount))
{
- if (ee != 0) writer << ",\n";
+ if (ee != 0)
+ writer << ",\n";
emitReflectionEntryPointJSON(writer, request, programReflection, (int)ee);
}
@@ -1334,7 +1289,8 @@ static void emitReflectionJSON(
writer.indent();
for (auto ee : makeRange(genParamCount))
{
- if (ee != 0) writer << ",\n";
+ if (ee != 0)
+ writer << ",\n";
auto typeParam = programReflection->getTypeParameterByIndex(ee);
emitReflectionTypeParamJSON(writer, typeParam);
@@ -1376,14 +1332,12 @@ static void emitReflectionJSON(
writer << "\n}\n";
}
-void emitReflectionJSON(
- SlangCompileRequest* request,
- SlangReflection* reflection)
+void emitReflectionJSON(SlangCompileRequest* request, SlangReflection* reflection)
{
- auto programReflection = (slang::ShaderReflection*) reflection;
+ auto programReflection = (slang::ShaderReflection*)reflection;
PrettyWriter writer;
-
+
emitReflectionJSON(writer, request, programReflection);
// Get the contents of the writer
@@ -1403,9 +1357,13 @@ static SlangResult maybeDumpDiagnostic(SlangResult res, SlangCompileRequest* req
return res;
}
-SlangResult performCompilationAndReflection(SlangCompileRequest* request, int argc, const char*const* argv)
+SlangResult performCompilationAndReflection(
+ SlangCompileRequest* request,
+ int argc,
+ const char* const* argv)
{
- SLANG_RETURN_ON_FAIL(maybeDumpDiagnostic(spProcessCommandLineArguments(request, &argv[1], argc - 1), request));
+ SLANG_RETURN_ON_FAIL(
+ maybeDumpDiagnostic(spProcessCommandLineArguments(request, &argv[1], argc - 1), request));
SLANG_RETURN_ON_FAIL(maybeDumpDiagnostic(spCompile(request), request));
// Okay, let's go through and emit reflection info on whatever
@@ -1417,10 +1375,11 @@ SlangResult performCompilationAndReflection(SlangCompileRequest* request, int ar
return SLANG_OK;
}
-SLANG_TEST_TOOL_API SlangResult innerMain(Slang::StdWriters* stdWriters, SlangSession* session, int argc, const char*const* argv)
+SLANG_TEST_TOOL_API SlangResult
+innerMain(Slang::StdWriters* stdWriters, SlangSession* session, int argc, const char* const* argv)
{
Slang::StdWriters::setSingleton(stdWriters);
-
+
SlangCompileRequest* request = spCreateCompileRequest(session);
for (int i = 0; i < SLANG_WRITER_CHANNEL_COUNT_OF; ++i)
{
@@ -1429,7 +1388,8 @@ SLANG_TEST_TOOL_API SlangResult innerMain(Slang::StdWriters* stdWriters, SlangSe
}
char const* appName = "slang-reflection-test";
- if (argc > 0) appName = argv[0];
+ if (argc > 0)
+ appName = argv[0];
SlangResult res = performCompilationAndReflection(request, argc, argv);
@@ -1438,16 +1398,14 @@ SLANG_TEST_TOOL_API SlangResult innerMain(Slang::StdWriters* stdWriters, SlangSe
return res;
}
-int main(
- int argc,
- char** argv)
+int main(int argc, char** argv)
{
using namespace Slang;
SlangSession* session = spCreateSession(nullptr);
auto stdWriters = StdWriters::initDefaultSingleton();
-
+
SlangResult res = innerMain(stdWriters, session, argc, argv);
spDestroySession(session);
slang::shutdown();
diff --git a/tools/slang-replay/main.cpp b/tools/slang-replay/main.cpp
index ac7654794..d27faacb3 100644
--- a/tools/slang-replay/main.cpp
+++ b/tools/slang-replay/main.cpp
@@ -1,16 +1,15 @@
-#include <memory>
-#include <stdio.h>
+#include "../../source/core/slang-io.h"
-#include <replay/recordFile-processor.h>
+#include <memory>
#include <replay/json-consumer.h>
+#include <replay/recordFile-processor.h>
#include <replay/replay-consumer.h>
#include <replay/slang-decoder.h>
-
-#include "../../source/core/slang-io.h"
+#include <stdio.h>
struct Options
{
- bool convertToJson {false};
+ bool convertToJson{false};
Slang::String recordFileName;
};
@@ -18,14 +17,15 @@ void printUsage()
{
printf("Usage: slang-replay [options] <record-file>\n");
printf("Options:\n");
- printf(" --convert-json, -cj: Convert the record file to a JSON file in the same directory with record file.\n\
+ printf(
+ " --convert-json, -cj: Convert the record file to a JSON file in the same directory with record file.\n\
When this option is set, it won't replay the record file.\n");
}
-Options parseOption(int argc, char *argv[])
+Options parseOption(int argc, char* argv[])
{
Options option;
- char const* arg {};
+ char const* arg{};
if (argc <= 1)
{
printUsage();
@@ -33,7 +33,7 @@ Options parseOption(int argc, char *argv[])
}
int argIndex = 1;
- while(argIndex < argc)
+ while (argIndex < argc)
{
arg = argv[argIndex];
@@ -43,14 +43,12 @@ Options parseOption(int argc, char *argv[])
option.recordFileName = arg;
argIndex++;
}
- else if ( (strcmp("--convert-json", arg) == 0) ||
- (strcmp("-cj", arg) == 0) )
+ else if ((strcmp("--convert-json", arg) == 0) || (strcmp("-cj", arg) == 0))
{
option.convertToJson = true;
argIndex++;
}
- else if ( (strcmp("--help", arg) == 0) ||
- (strcmp("-h", arg) == 0) )
+ else if ((strcmp("--help", arg) == 0) || (strcmp("-h", arg) == 0))
{
printUsage();
exit(0);
@@ -73,7 +71,7 @@ Options parseOption(int argc, char *argv[])
return option;
}
-int main(int argc, char *argv[])
+int main(int argc, char* argv[])
{
Options options = parseOption(argc, argv);
@@ -97,9 +95,9 @@ int main(int argc, char *argv[])
recordFileProcessor.addDecoder(&decoder);
- while(true)
+ while (true)
{
- if(!recordFileProcessor.processNextBlock())
+ if (!recordFileProcessor.processNextBlock())
{
break;
}
diff --git a/tools/slang-spirv-embed-generator/spirv-embed-generator-main.cpp b/tools/slang-spirv-embed-generator/spirv-embed-generator-main.cpp
index fd29ed714..e9fde6e01 100644
--- a/tools/slang-spirv-embed-generator/spirv-embed-generator-main.cpp
+++ b/tools/slang-spirv-embed-generator/spirv-embed-generator-main.cpp
@@ -1,12 +1,12 @@
-#include <cstdio>
-
-#include "../../source/core/slang-dictionary.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-writer.h"
#include "../../source/compiler-core/slang-diagnostic-sink.h"
+#include "../../source/compiler-core/slang-lexer.h"
#include "../../source/compiler-core/slang-perfect-hash.h"
#include "../../source/compiler-core/slang-spirv-core-grammar.h"
-#include "../../source/compiler-core/slang-lexer.h"
+#include "../../source/core/slang-dictionary.h"
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-writer.h"
+
+#include <cstdio>
using namespace Slang;
@@ -22,13 +22,13 @@ String dictToPerfectHash(
{
HashParams hashParams;
List<String> names;
- for(const auto& [name, val] : dict)
+ for (const auto& [name, val] : dict)
names.add(name);
auto r = minimalPerfectHash(names, hashParams);
SLANG_ASSERT(r == HashFindResult::Success);
List<String> values;
values.reserve(hashParams.destTable.getCount());
- for(const auto& v : hashParams.destTable)
+ for (const auto& v : hashParams.destTable)
{
values.add(valueToString(dict.getValue(v.getUnownedSlice())));
}
@@ -49,7 +49,8 @@ void dictToSwitch(
const F2 valueToAssignmentString,
WriterHelper& w)
{
- const auto line = [&](const auto& l){
+ const auto line = [&](const auto& l)
+ {
w.put(l);
w.put("\n");
};
@@ -58,7 +59,7 @@ void dictToSwitch(
line("{");
w.print(" switch(%s)\n", unpackKey);
line(" {");
- for(const auto& [k, v] : dict)
+ for (const auto& [k, v] : dict)
{
const auto kStr = keyToString(k);
const auto vStr = valueToAssignmentString(v);
@@ -69,8 +70,7 @@ void dictToSwitch(
" return true;\n"
" }\n",
kStr.getBuffer(),
- vStr.getBuffer()
- );
+ vStr.getBuffer());
}
line(" default: return false;");
line(" }");
@@ -92,7 +92,8 @@ void qualifiedEnumValueNameSwitch(
const F valueToAssignmentString,
WriterHelper& w)
{
- const auto line = [&](const auto& l){
+ const auto line = [&](const auto& l)
+ {
w.put(l);
w.put("\n");
};
@@ -100,7 +101,7 @@ void qualifiedEnumValueNameSwitch(
using K1 = Slang::SPIRVCoreGrammarInfo::OperandKind;
using K2 = SpvWord;
Dictionary<K1, Dictionary<K2, V>> stepDict;
- for(const auto& [k, v] : dict)
+ for (const auto& [k, v] : dict)
{
const auto& [k1, k2] = k;
stepDict[k1][k2] = v;
@@ -111,14 +112,14 @@ void qualifiedEnumValueNameSwitch(
line(" const auto& [k1, k2] = k;");
w.print(" switch(%s)\n", unpackKey1);
line(" {");
- for(const auto& [k1, inner] : stepDict)
+ for (const auto& [k1, inner] : stepDict)
{
const auto k1Str = String(k1.index);
w.print(" case %s:\n", k1Str.getBuffer());
line(" switch(k2)");
line(" {");
- for(const auto& [k2, v] : inner)
+ for (const auto& [k2, v] : inner)
{
const auto k2Str = String(k2);
const auto vStr = valueToAssignmentString(v);
@@ -135,9 +136,10 @@ void qualifiedEnumValueNameSwitch(
static const char* opClassToString(Slang::SPIRVCoreGrammarInfo::OpInfo::Class c)
{
- switch(c)
+ switch (c)
{
-#define GO(n) case SPIRVCoreGrammarInfo::OpInfo::n: return #n;
+#define GO(n) \
+ case SPIRVCoreGrammarInfo::OpInfo::n: return #n;
GO(Miscellaneous)
GO(Debug)
GO(Annotation)
@@ -163,8 +165,7 @@ static const char* opClassToString(Slang::SPIRVCoreGrammarInfo::OpInfo::Class c)
GO(Pipe)
GO(NonUniform)
GO(Reserved)
- default:
- GO(Other)
+ default: GO(Other)
#undef GO
}
}
@@ -172,14 +173,13 @@ static const char* opClassToString(Slang::SPIRVCoreGrammarInfo::OpInfo::Class c)
//
// Write a C++ embedding of the SPIRVCoreGrammarInfo struct
//
-void writeInfo(
- const char* const outCppPath,
- const SPIRVCoreGrammarInfo& info)
+void writeInfo(const char* const outCppPath, const SPIRVCoreGrammarInfo& info)
{
StringBuilder sb;
StringWriter writer(&sb, WriterFlags(0));
WriterHelper w(&writer);
- const auto line = [&](const auto& l){
+ const auto line = [&](const auto& l)
+ {
w.put(l);
w.put("\n");
};
@@ -212,42 +212,45 @@ void writeInfo(
memberAssignments.add("info->opcodes.embedded = &lookupSpvOp;");
w.put("static ");
w.put(dictToPerfectHash(
- info.opcodes.dict,
- UnownedStringSlice("SpvOp"),
- UnownedStringSlice("lookupSpvOp"),
- [](const auto n){
- const auto radix = 10;
- return "static_cast<SpvOp>(" + String(n, radix) + ")";
- }
- ).getBuffer());
+ info.opcodes.dict,
+ UnownedStringSlice("SpvOp"),
+ UnownedStringSlice("lookupSpvOp"),
+ [](const auto n)
+ {
+ const auto radix = 10;
+ return "static_cast<SpvOp>(" + String(n, radix) + ")";
+ })
+ .getBuffer());
}
{
memberAssignments.add("info->capabilities.embedded = &lookupSpvCapability;");
w.put("static ");
w.put(dictToPerfectHash(
- info.capabilities.dict,
- UnownedStringSlice("SpvCapability"),
- UnownedStringSlice("lookupSpvCapability"),
- [](const auto n){
- const auto radix = 10;
- return "static_cast<SpvCapability>(" + String(n, radix) + ")";
- }
- ).getBuffer());
+ info.capabilities.dict,
+ UnownedStringSlice("SpvCapability"),
+ UnownedStringSlice("lookupSpvCapability"),
+ [](const auto n)
+ {
+ const auto radix = 10;
+ return "static_cast<SpvCapability>(" + String(n, radix) + ")";
+ })
+ .getBuffer());
}
{
memberAssignments.add("info->allEnumsWithTypePrefix.embedded = &lookupEnumWithTypePrefix;");
w.put("static ");
w.put(dictToPerfectHash(
- info.allEnumsWithTypePrefix.dict,
- UnownedStringSlice("SpvWord"),
- UnownedStringSlice("lookupEnumWithTypePrefix"),
- [](const auto n){
- const auto radix = 10;
- return "SpvWord{" + String(n, radix) + "}";
- }
- ).getBuffer());
+ info.allEnumsWithTypePrefix.dict,
+ UnownedStringSlice("SpvWord"),
+ UnownedStringSlice("lookupEnumWithTypePrefix"),
+ [](const auto n)
+ {
+ const auto radix = 10;
+ return "SpvWord{" + String(n, radix) + "}";
+ })
+ .getBuffer());
}
{
@@ -258,38 +261,33 @@ void writeInfo(
"SpvOp",
"SPIRVCoreGrammarInfo::OpInfo",
"k",
- [&](SpvOp o){
- return "Spv" + String(info.opNames.dict.getValue(o));
- },
- [](const Slang::SPIRVCoreGrammarInfo::OpInfo& i){
+ [&](SpvOp o) { return "Spv" + String(info.opNames.dict.getValue(o)); },
+ [](const Slang::SPIRVCoreGrammarInfo::OpInfo& i)
+ {
const char* classStr = opClassToString(i.class_);
String ret;
- if(i.numOperandTypes)
+ if (i.numOperandTypes)
{
ret.append("const static OperandKind operandTypes[] = {");
String operandTypes;
- for(Index o = 0; o < i.numOperandTypes; ++o)
+ for (Index o = 0; o < i.numOperandTypes; ++o)
{
- if(o != 0)
+ if (o != 0)
ret.append(", ");
ret.append("{" + String(i.operandTypes[o].index) + "}");
}
ret.append("};\n ");
}
ret.append(
- String("v = {SPIRVCoreGrammarInfo::OpInfo::")
- + classStr + ", "
- + String(i.resultTypeIndex) + ", "
- + String(i.resultIdIndex) + ", "
- + String(i.minOperandCount) + ", "
- + (i.maxOperandCount == 0xffff ? String("0xffff") : String(i.maxOperandCount)) + ", "
- + String(i.numOperandTypes) + ", "
- + (i.numOperandTypes ? "operandTypes" : "nullptr")
- + "}");
+ String("v = {SPIRVCoreGrammarInfo::OpInfo::") + classStr + ", " +
+ String(i.resultTypeIndex) + ", " + String(i.resultIdIndex) + ", " +
+ String(i.minOperandCount) + ", " +
+ (i.maxOperandCount == 0xffff ? String("0xffff") : String(i.maxOperandCount)) +
+ ", " + String(i.numOperandTypes) + ", " +
+ (i.numOperandTypes ? "operandTypes" : "nullptr") + "}");
return ret;
},
- w
- );
+ w);
}
{
@@ -300,28 +298,25 @@ void writeInfo(
"SpvOp",
"UnownedStringSlice",
"k",
- [&](SpvOp o){
- return "Spv" + String(info.opNames.dict.getValue(o));
- },
- [](const UnownedStringSlice& i){
- return "v = UnownedStringSlice{\"" + String(i) + "\"}";
- },
- w
- );
+ [&](SpvOp o) { return "Spv" + String(info.opNames.dict.getValue(o)); },
+ [](const UnownedStringSlice& i)
+ { return "v = UnownedStringSlice{\"" + String(i) + "\"}"; },
+ w);
}
{
memberAssignments.add("info->operandKinds.embedded = &lookupOperandKind;");
w.put("static ");
w.put(dictToPerfectHash(
- info.operandKinds.dict,
- UnownedStringSlice("OperandKind"),
- UnownedStringSlice("lookupOperandKind"),
- [](const auto n){
- const auto radix = 10;
- return "OperandKind{" + String(n.index, radix) + "}";
- }
- ).getBuffer());
+ info.operandKinds.dict,
+ UnownedStringSlice("OperandKind"),
+ UnownedStringSlice("lookupOperandKind"),
+ [](const auto n)
+ {
+ const auto radix = 10;
+ return "OperandKind{" + String(n.index, radix) + "}";
+ })
+ .getBuffer());
}
{
@@ -332,7 +327,7 @@ void writeInfo(
// reuse the existing string-based perfect hasher
Dictionary<String, SpvWord> enumDict;
Index maxNameLength = 0;
- for(const auto& [q, v] : info.allEnums.dict)
+ for (const auto& [q, v] : info.allEnums.dict)
{
const auto i = q.kind.index;
String k;
@@ -343,11 +338,11 @@ void writeInfo(
maxNameLength = std::max(maxNameLength, k.getLength());
}
w.put(dictToPerfectHash(
- enumDict,
- UnownedStringSlice("SpvWord"),
- UnownedStringSlice("lookupEnumWithHexPrefix"),
- [&](const auto n){ return "SpvWord{" + String(n) + "}"; }
- ).getBuffer());
+ enumDict,
+ UnownedStringSlice("SpvWord"),
+ UnownedStringSlice("lookupEnumWithHexPrefix"),
+ [&](const auto n) { return "SpvWord{" + String(n) + "}"; })
+ .getBuffer());
// Utilise this helper
line("static bool lookupQualifiedEnum(const QualifiedEnumName& k, SpvWord& v)");
@@ -359,7 +354,8 @@ void writeInfo(
line(" name[0] = char((k.kind.index >> 4) + 'a');");
line(" name[1] = char((k.kind.index & 0xf) + 'a');");
line(" memcpy(name+2, k.name.begin(), k.name.getLength());");
- line(" return lookupEnumWithHexPrefix(UnownedStringSlice(name, k.name.getLength() + 2), v);");
+ line(" return lookupEnumWithHexPrefix(UnownedStringSlice(name, k.name.getLength() + 2), "
+ "v);");
line("}");
line("");
}
@@ -372,11 +368,9 @@ void writeInfo(
"QualifiedEnumValue",
"UnownedStringSlice",
"k1.index",
- [](const UnownedStringSlice& i){
- return "v = UnownedStringSlice{\"" + String(i) + "\"}";
- },
- w
- );
+ [](const UnownedStringSlice& i)
+ { return "v = UnownedStringSlice{\"" + String(i) + "\"}"; },
+ w);
}
{
@@ -387,32 +381,25 @@ void writeInfo(
"OperandKind",
"UnownedStringSlice",
"k.index",
- [&](Slang::SPIRVCoreGrammarInfo::OperandKind o){
- return String(o.index);
- },
- [](const UnownedStringSlice& i){
- return "v = UnownedStringSlice{\"" + String(i) + "\"}";
- },
- w
- );
+ [&](Slang::SPIRVCoreGrammarInfo::OperandKind o) { return String(o.index); },
+ [](const UnownedStringSlice& i)
+ { return "v = UnownedStringSlice{\"" + String(i) + "\"}"; },
+ w);
}
{
- memberAssignments.add("info->operandKindUnderneathIds.embedded = &getOperandKindUnderneathId;");
+ memberAssignments.add(
+ "info->operandKindUnderneathIds.embedded = &getOperandKindUnderneathId;");
dictToSwitch(
info.operandKindUnderneathIds.dict,
"getOperandKindUnderneathId",
"OperandKind",
"OperandKind",
"k.index",
- [](Slang::SPIRVCoreGrammarInfo::OperandKind o){
- return String(o.index);
- },
- [](Slang::SPIRVCoreGrammarInfo::OperandKind i){
- return "v = OperandKind{" + String(i.index) + "}";
- },
- w
- );
+ [](Slang::SPIRVCoreGrammarInfo::OperandKind o) { return String(o.index); },
+ [](Slang::SPIRVCoreGrammarInfo::OperandKind i)
+ { return "v = OperandKind{" + String(i.index) + "}"; },
+ w);
}
//
@@ -422,7 +409,7 @@ void writeInfo(
line("{");
line(" static RefPtr<SPIRVCoreGrammarInfo> embedded = [](){");
line(" RefPtr<SPIRVCoreGrammarInfo> info = new SPIRVCoreGrammarInfo();");
- for(const auto& a : memberAssignments)
+ for (const auto& a : memberAssignments)
line((" " + a).getBuffer());
//
@@ -452,14 +439,14 @@ int main(int argc, const char* const* argv)
const char* const outCppPath = argv[2];
RefPtr<FileWriter> writer(new FileWriter(stderr, WriterFlag::AutoFlush));
- SourceManager sourceManager;
+ SourceManager sourceManager;
sourceManager.initialize(nullptr, nullptr);
DiagnosticSink sink(&sourceManager, Lexer::sourceLocationLexer);
sink.writer = writer;
String contents;
SLANG_RETURN_ON_FAIL(File::readAllText(inPath, contents));
- PathInfo pathInfo = PathInfo::makeFromString(inPath);
+ PathInfo pathInfo = PathInfo::makeFromString(inPath);
SourceFile* sourceFile = sourceManager.createSourceFileWithString(pathInfo, contents);
SourceView* sourceView = sourceManager.createSourceView(sourceFile, nullptr, SourceLoc());
diff --git a/tools/slang-test/directory-util.cpp b/tools/slang-test/directory-util.cpp
index 39d06a2a2..d52ef9c92 100644
--- a/tools/slang-test/directory-util.cpp
+++ b/tools/slang-test/directory-util.cpp
@@ -5,7 +5,9 @@
using namespace Slang;
-/* static */SlangResult DirectoryUtil::findDirectories(const Slang::String& directoryPath, Slang::List<Slang::String>& outPaths)
+/* static */ SlangResult DirectoryUtil::findDirectories(
+ const Slang::String& directoryPath,
+ Slang::List<Slang::String>& outPaths)
{
outPaths.clear();
CombinePathVisitor visitor(directoryPath, Path::TypeFlag::Directory);
@@ -14,7 +16,10 @@ using namespace Slang;
return SLANG_OK;
}
-/* static */SlangResult DirectoryUtil::findFilesMatchingPattern(const Slang::String& directoryPath, const char* pattern, Slang::List<Slang::String>& outPaths)
+/* static */ SlangResult DirectoryUtil::findFilesMatchingPattern(
+ const Slang::String& directoryPath,
+ const char* pattern,
+ Slang::List<Slang::String>& outPaths)
{
outPaths.clear();
CombinePathVisitor visitor(directoryPath, Path::TypeFlag::File);
@@ -23,7 +28,9 @@ using namespace Slang;
return SLANG_OK;
}
-/* static */SlangResult DirectoryUtil::findFiles(const Slang::String& directoryPath, Slang::List<Slang::String>& outPaths)
+/* static */ SlangResult DirectoryUtil::findFiles(
+ const Slang::String& directoryPath,
+ Slang::List<Slang::String>& outPaths)
{
return findFilesMatchingPattern(directoryPath, nullptr, outPaths);
}
diff --git a/tools/slang-test/directory-util.h b/tools/slang-test/directory-util.h
index dbda3e616..06a0b2086 100644
--- a/tools/slang-test/directory-util.h
+++ b/tools/slang-test/directory-util.h
@@ -6,27 +6,26 @@
class CombinePathVisitor : public Slang::Path::Visitor
{
public:
- virtual void accept(Slang::Path::Type type, const Slang::UnownedStringSlice& filename) SLANG_OVERRIDE
+ virtual void accept(Slang::Path::Type type, const Slang::UnownedStringSlice& filename)
+ SLANG_OVERRIDE
{
using namespace Slang;
const Path::TypeFlags flags = Path::TypeFlags(1) << int(type);
if (flags & m_allowedFlags)
{
- m_paths.add(Path::combine(m_directoryPath, filename));
+ m_paths.add(Path::combine(m_directoryPath, filename));
}
}
- /// Ctor
- CombinePathVisitor(const Slang::String& directoryPath, Slang::Path::TypeFlags allowedFlags):
- m_directoryPath(directoryPath),
- m_allowedFlags(allowedFlags)
+ /// Ctor
+ CombinePathVisitor(const Slang::String& directoryPath, Slang::Path::TypeFlags allowedFlags)
+ : m_directoryPath(directoryPath), m_allowedFlags(allowedFlags)
{
}
Slang::List<Slang::String> m_paths;
protected:
-
Slang::Path::TypeFlags m_allowedFlags;
Slang::String m_directoryPath;
};
@@ -35,19 +34,26 @@ protected:
class DirectoryUtil
{
public:
- /// Enumerate subdirectories in the given `directoryPath`, storing in outPaths.
- /// @return SLANG_OK on success or SLANG_E_NOT_FOUND if directory is not found.
- static SlangResult findDirectories(const Slang::String& directoryPath, Slang::List<Slang::String>& outPaths);
-
- /// Enumerate files in the given `directoryPath` that match the provided
- /// `pattern` as a simplified regex for files to return (e.g., "*.txt")
- /// Note that the specifics of the pattern matching are *target specific*
- /// @return SLANG_OK on success or SLANG_E_NOT_FOUND if directory is not found.
- static SlangResult findFilesMatchingPattern(const Slang::String& directoryPath, const char* pattern, Slang::List<Slang::String>& outPaths);
-
- /// Enumerate files in the given `directoryPath`, storing in outPaths.
- /// @return SLANG_OK on success or SLANG_E_NOT_FOUND if directory is not found.
- static SlangResult findFiles(const Slang::String& directoryPath, Slang::List<Slang::String>& outPaths);
+ /// Enumerate subdirectories in the given `directoryPath`, storing in outPaths.
+ /// @return SLANG_OK on success or SLANG_E_NOT_FOUND if directory is not found.
+ static SlangResult findDirectories(
+ const Slang::String& directoryPath,
+ Slang::List<Slang::String>& outPaths);
+
+ /// Enumerate files in the given `directoryPath` that match the provided
+ /// `pattern` as a simplified regex for files to return (e.g., "*.txt")
+ /// Note that the specifics of the pattern matching are *target specific*
+ /// @return SLANG_OK on success or SLANG_E_NOT_FOUND if directory is not found.
+ static SlangResult findFilesMatchingPattern(
+ const Slang::String& directoryPath,
+ const char* pattern,
+ Slang::List<Slang::String>& outPaths);
+
+ /// Enumerate files in the given `directoryPath`, storing in outPaths.
+ /// @return SLANG_OK on success or SLANG_E_NOT_FOUND if directory is not found.
+ static SlangResult findFiles(
+ const Slang::String& directoryPath,
+ Slang::List<Slang::String>& outPaths);
};
#endif // SLANG_DIRECTORY_UTIL_H
diff --git a/tools/slang-test/filecheck.h b/tools/slang-test/filecheck.h
index 4f527bf14..1a26606b1 100644
--- a/tools/slang-test/filecheck.h
+++ b/tools/slang-test/filecheck.h
@@ -1,7 +1,7 @@
#pragma once
-#include "../../source/core/slang-common.h"
#include "../../source/compiler-core/slang-artifact.h"
+#include "../../source/core/slang-common.h"
#include "../../tools/unit-test/slang-unit-test.h"
namespace Slang
@@ -10,21 +10,25 @@ namespace Slang
class IFileCheck : public ICastable
{
public:
- SLANG_COM_INTERFACE( 0x046bfe4a, 0x99a3, 0x402f, {0x83, 0xd7, 0x81, 0x8d, 0xa1, 0x38, 0xed, 0xfa})
+ SLANG_COM_INTERFACE(
+ 0x046bfe4a,
+ 0x99a3,
+ 0x402f,
+ {0x83, 0xd7, 0x81, 0x8d, 0xa1, 0x38, 0xed, 0xfa})
- using ReportDiagnostic = void (SLANG_STDCALL *)(void*, TestMessageType, const char*) noexcept;
+ using ReportDiagnostic = void(SLANG_STDCALL*)(void*, TestMessageType, const char*) noexcept;
virtual TestResult SLANG_MCALL performTest(
- const char* programName, // Included in diagnostic messages, for example "slang-test"
- const char* rulesFilePath, // The file from which to read the FileCheck rules
- const char* fileCheckPrefix, // The name of the FileCheck files to use in the rules file
- const char* stringToCheck, // The string to match with the rules
- const char* stringToCheckName, // The name of that string, for example "actual-output"
- ReportDiagnostic testReporter, // A callback for reporting diagnostic messages
- void* reporterData, // Some data to pass on to the callback
- bool colorDiagnosticOutput // Include color control codes in the string passed to testReporter
- ) noexcept = 0;
+ const char* programName, // Included in diagnostic messages, for example "slang-test"
+ const char* rulesFilePath, // The file from which to read the FileCheck rules
+ const char* fileCheckPrefix, // The name of the FileCheck files to use in the rules file
+ const char* stringToCheck, // The string to match with the rules
+ const char* stringToCheckName, // The name of that string, for example "actual-output"
+ ReportDiagnostic testReporter, // A callback for reporting diagnostic messages
+ void* reporterData, // Some data to pass on to the callback
+ bool colorDiagnosticOutput // Include color control codes in the string passed to
+ // testReporter
+ ) noexcept = 0;
};
-}
-
+} // namespace Slang
diff --git a/tools/slang-test/options.cpp b/tools/slang-test/options.cpp
index 0f3abfdf2..10f98f3a2 100644
--- a/tools/slang-test/options.cpp
+++ b/tools/slang-test/options.cpp
@@ -1,8 +1,9 @@
// test-context.cpp
#include "options.h"
-#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-string-util.h"
+
#include <stdio.h>
#include <stdlib.h>
@@ -58,7 +59,12 @@ static bool _isSubCommand(const char* arg)
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!! Options !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
-/* static */Result Options::parse(int argc, char** argv, TestCategorySet* categorySet, Slang::WriterHelper stdError, Options* optionsOut)
+/* static */ Result Options::parse(
+ int argc,
+ char** argv,
+ TestCategorySet* categorySet,
+ Slang::WriterHelper stdError,
+ Options* optionsOut)
{
// Reset the options
*optionsOut = Options();
@@ -200,7 +206,7 @@ static bool _isSubCommand(const char* arg)
stdError.print("error: expected operand for '%s'\n", arg);
return SLANG_FAIL;
}
- optionsOut->serverCount = stringToInt(* argCursor++);
+ optionsOut->serverCount = stringToInt(*argCursor++);
if (optionsOut->serverCount <= 0)
{
optionsOut->serverCount = 1;
@@ -258,12 +264,17 @@ static bool _isSubCommand(const char* arg)
{
if (argCursor == argEnd)
{
- stdError.print("error: expecting an api expression (eg 'vk+dx12' or '+dx11') '%s'\n", arg);
+ stdError.print(
+ "error: expecting an api expression (eg 'vk+dx12' or '+dx11') '%s'\n",
+ arg);
return SLANG_FAIL;
}
const char* apiList = *argCursor++;
- SlangResult res = RenderApiUtil::parseApiFlags(UnownedStringSlice(apiList), optionsOut->enabledApis, &optionsOut->enabledApis);
+ SlangResult res = RenderApiUtil::parseApiFlags(
+ UnownedStringSlice(apiList),
+ optionsOut->enabledApis,
+ &optionsOut->enabledApis);
if (SLANG_FAILED(res))
{
stdError.print("error: unable to parse api expression '%s'\n", apiList);
@@ -274,12 +285,17 @@ static bool _isSubCommand(const char* arg)
{
if (argCursor == argEnd)
{
- stdError.print("error: expected an api expression (eg 'vk+dx12' or '+dx11') '%s'\n", arg);
+ stdError.print(
+ "error: expected an api expression (eg 'vk+dx12' or '+dx11') '%s'\n",
+ arg);
return SLANG_FAIL;
}
const char* apiList = *argCursor++;
- SlangResult res = RenderApiUtil::parseApiFlags(UnownedStringSlice(apiList), optionsOut->synthesizedTestApis, &optionsOut->synthesizedTestApis);
+ SlangResult res = RenderApiUtil::parseApiFlags(
+ UnownedStringSlice(apiList),
+ optionsOut->synthesizedTestApis,
+ &optionsOut->synthesizedTestApis);
if (SLANG_FAILED(res))
{
stdError.print("error: unable to parse api expression '%s'\n", apiList);
diff --git a/tools/slang-test/options.h b/tools/slang-test/options.h
index 2485ee2e1..f84240c71 100644
--- a/tools/slang-test/options.h
+++ b/tools/slang-test/options.h
@@ -4,13 +4,12 @@
#define OPTIONS_H_INCLUDED
#include "../../source/core/slang-dictionary.h"
-
-#include "test-reporter.h"
#include "../../source/core/slang-render-api-util.h"
#include "../../source/core/slang-smart-pointer.h"
+#include "test-reporter.h"
// A category that a test can be tagged with
-struct TestCategory: public Slang::RefObject
+struct TestCategory : public Slang::RefObject
{
// The name of the category, from the user perspective
Slang::String name;
@@ -22,27 +21,27 @@ struct TestCategory: public Slang::RefObject
struct TestCategorySet
{
public:
- /// Find a category with the specified name. Returns nullptr if not found
+ /// Find a category with the specified name. Returns nullptr if not found
TestCategory* find(Slang::String const& name);
- /// Adds a category with the specified name, and parent. Returns the category object.
- /// Parent can be nullptr
+ /// Adds a category with the specified name, and parent. Returns the category object.
+ /// Parent can be nullptr
TestCategory* add(Slang::String const& name, TestCategory* parent);
- /// Finds a category by name, else reports and writes an error
+ /// Finds a category by name, else reports and writes an error
TestCategory* findOrError(Slang::String const& name);
- Slang::RefPtr<TestCategory> defaultCategory; ///< The default category
+ Slang::RefPtr<TestCategory> defaultCategory; ///< The default category
protected:
- Slang::Dictionary<Slang::String, Slang::RefPtr<TestCategory> > m_categoryMap;
+ Slang::Dictionary<Slang::String, Slang::RefPtr<TestCategory>> m_categoryMap;
};
enum class SpawnType
{
- Default, ///< Default - typically uses shared library, on CI may use TestServer
- UseExe, ///< Tests using executable (for example slangc)
- UseSharedLibrary, ///< Runs testing in process (a crash tan take down the
- UseTestServer, ///< Use the test server to isolate testing
- UseFullyIsolatedTestServer, ///< Uses a test server for each test (slow!)
+ Default, ///< Default - typically uses shared library, on CI may use TestServer
+ UseExe, ///< Tests using executable (for example slangc)
+ UseSharedLibrary, ///< Runs testing in process (a crash tan take down the
+ UseTestServer, ///< Use the test server to isolate testing
+ UseFullyIsolatedTestServer, ///< Uses a test server for each test (slow!)
};
struct Options
@@ -82,7 +81,7 @@ struct Options
// Having tests isolated, slows down testing considerably, so using UseSharedLibrary is the most
// desirable default usually.
SpawnType defaultSpawnType = SpawnType::Default;
-
+
// kind of output to generate
TestOutputMode outputMode = TestOutputMode::Default;
@@ -92,21 +91,23 @@ struct Options
// Exclude test that match one these categories
Slang::Dictionary<TestCategory*, TestCategory*> excludeCategories;
- // By default we can test against all apis. If is set to anything other than AllOf only tests that *require* the API
- // will be run.
+ // By default we can test against all apis. If is set to anything other than AllOf only tests
+ // that *require* the API will be run.
Slang::RenderApiFlags enabledApis = Slang::RenderApiFlag::AllOf;
- // The subCommand to execute. Will be empty if there is no subCommand
- Slang::String subCommand;
+ // The subCommand to execute. Will be empty if there is no subCommand
+ Slang::String subCommand;
- // Arguments to the sub command. Note that if there is a subCommand the first parameter is always the subCommand itself.
+ // Arguments to the sub command. Note that if there is a subCommand the first parameter is
+ // always the subCommand itself.
Slang::List<Slang::String> subCommandArgs;
- // By default we potentially synthesize test for all
+ // By default we potentially synthesize test for all
// TODO: Vulkan is disabled by default for now as the majority as vulkan synthesized tests
// CPU is disabled by default
// CUDA is disabled by default
- Slang::RenderApiFlags synthesizedTestApis = Slang::RenderApiFlag::AllOf & ~(Slang::RenderApiFlag::Vulkan | Slang::RenderApiFlag::CPU);
+ Slang::RenderApiFlags synthesizedTestApis =
+ Slang::RenderApiFlag::AllOf & ~(Slang::RenderApiFlag::Vulkan | Slang::RenderApiFlag::CPU);
// The adapter to use. If empty will match first found adapter.
Slang::String adapter;
@@ -118,8 +119,13 @@ struct Options
Slang::HashSet<Slang::String> expectedFailureList;
- /// Parse the args, report any errors into stdError, and write the results into optionsOut
- static SlangResult parse(int argc, char** argv, TestCategorySet* categorySet, Slang::WriterHelper stdError, Options* optionsOut);
+ /// Parse the args, report any errors into stdError, and write the results into optionsOut
+ static SlangResult parse(
+ int argc,
+ char** argv,
+ TestCategorySet* categorySet,
+ Slang::WriterHelper stdError,
+ Options* optionsOut);
};
#endif // OPTIONS_H_INCLUDED
diff --git a/tools/slang-test/parse-diagnostic-util.cpp b/tools/slang-test/parse-diagnostic-util.cpp
index f5b76a07e..74012d4d2 100644
--- a/tools/slang-test/parse-diagnostic-util.cpp
+++ b/tools/slang-test/parse-diagnostic-util.cpp
@@ -2,24 +2,26 @@
#include "parse-diagnostic-util.h"
+#include "../../source/compiler-core/slang-artifact-associated-impl.h"
+#include "../../source/compiler-core/slang-artifact-diagnostic-util.h"
+#include "../../source/compiler-core/slang-downstream-compiler.h"
+#include "../../source/core/slang-byte-encode-util.h"
+#include "../../source/core/slang-char-util.h"
#include "../../source/core/slang-hex-dump-util.h"
+#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-type-text-util.h"
-
#include "slang-com-helper.h"
-#include "../../source/core/slang-string-util.h"
-#include "../../source/core/slang-byte-encode-util.h"
-#include "../../source/core/slang-char-util.h"
-
-#include "../../source/compiler-core/slang-artifact-diagnostic-util.h"
-#include "../../source/compiler-core/slang-artifact-associated-impl.h"
-#include "../../source/compiler-core/slang-downstream-compiler.h"
-
using namespace Slang;
-/* static */SlangResult ParseDiagnosticUtil::parseGenericLine(SliceAllocator& allocator, const UnownedStringSlice& line, List<UnownedStringSlice>& lineSlices, ArtifactDiagnostic& outDiagnostic)
+/* static */ SlangResult ParseDiagnosticUtil::parseGenericLine(
+ SliceAllocator& allocator,
+ const UnownedStringSlice& line,
+ List<UnownedStringSlice>& lineSlices,
+ ArtifactDiagnostic& outDiagnostic)
{
- /* e:\git\somewhere\tests\diagnostics\syntax-error-intrinsic.slang(13): error C2018: unknown character '0x40' */
+ /* e:\git\somewhere\tests\diagnostics\syntax-error-intrinsic.slang(13): error C2018: unknown
+ * character '0x40' */
if (lineSlices.getCount() < 3)
{
return SLANG_FAIL;
@@ -28,9 +30,11 @@ using namespace Slang;
{
const UnownedStringSlice severityAndCodeSlice = lineSlices[1].trim();
// Get the code
- outDiagnostic.code = allocator.allocate(StringUtil::getAtInSplit(severityAndCodeSlice, ' ', 1).trim());
+ outDiagnostic.code =
+ allocator.allocate(StringUtil::getAtInSplit(severityAndCodeSlice, ' ', 1).trim());
- const UnownedStringSlice severitySlice = StringUtil::getAtInSplit(severityAndCodeSlice, ' ', 0);
+ const UnownedStringSlice severitySlice =
+ StringUtil::getAtInSplit(severityAndCodeSlice, ' ', 0);
outDiagnostic.severity = ArtifactDiagnostic::Severity::Error;
if (severitySlice == UnownedStringSlice::fromLiteral("warning"))
@@ -44,25 +48,27 @@ using namespace Slang;
}
// Get the location info
- SLANG_RETURN_ON_FAIL(ArtifactDiagnosticUtil::splitPathLocation(allocator, lineSlices[0], outDiagnostic));
+ SLANG_RETURN_ON_FAIL(
+ ArtifactDiagnosticUtil::splitPathLocation(allocator, lineSlices[0], outDiagnostic));
outDiagnostic.text = allocator.allocate(lineSlices[2].begin(), line.end());
return SLANG_OK;
}
-static SlangResult _getSlangDiagnosticSeverity(const UnownedStringSlice& inText, ArtifactDiagnostic::Severity& outSeverity, Int& outCode)
+static SlangResult _getSlangDiagnosticSeverity(
+ const UnownedStringSlice& inText,
+ ArtifactDiagnostic::Severity& outSeverity,
+ Int& outCode)
{
UnownedStringSlice text(inText.trim());
- static const UnownedStringSlice prefixes[] =
- {
+ static const UnownedStringSlice prefixes[] = {
UnownedStringSlice::fromLiteral("note"),
UnownedStringSlice::fromLiteral("warning"),
UnownedStringSlice::fromLiteral("error"),
UnownedStringSlice::fromLiteral("fatal error"),
UnownedStringSlice::fromLiteral("internal error"),
- UnownedStringSlice::fromLiteral("unknown error")
- };
+ UnownedStringSlice::fromLiteral("unknown error")};
Int index = -1;
@@ -78,10 +84,10 @@ static SlangResult _getSlangDiagnosticSeverity(const UnownedStringSlice& inText,
switch (index)
{
- case -1: return SLANG_FAIL;
- case 0: outSeverity = ArtifactDiagnostic::Severity::Info; break;
- case 1: outSeverity = ArtifactDiagnostic::Severity::Warning; break;
- default: outSeverity = ArtifactDiagnostic::Severity::Error; break;
+ case -1: return SLANG_FAIL;
+ case 0: outSeverity = ArtifactDiagnostic::Severity::Info; break;
+ case 1: outSeverity = ArtifactDiagnostic::Severity::Warning; break;
+ default: outSeverity = ArtifactDiagnostic::Severity::Error; break;
}
outCode = 0;
@@ -98,12 +104,13 @@ static SlangResult _getSlangDiagnosticSeverity(const UnownedStringSlice& inText,
static bool _isSlangDiagnostic(const UnownedStringSlice& line)
{
/*
- tests/diagnostics/accessors.slang(11): error 31101: accessors other than 'set' must not have parameters
+ tests/diagnostics/accessors.slang(11): error 31101: accessors other than 'set' must not have
+ parameters
*/
UnownedStringSlice initial = StringUtil::getAtInSplit(line, ':', 0);
- // Handle if path has :
+ // Handle if path has :
const Index typeIndex = (initial.getLength() == 1 && CharUtil::isAlpha(initial[0])) ? 2 : 1;
// Extract the type/code slice
UnownedStringSlice typeSlice = StringUtil::getAtInSplit(line, ':', typeIndex);
@@ -113,10 +120,15 @@ static bool _isSlangDiagnostic(const UnownedStringSlice& line)
return SLANG_SUCCEEDED(_getSlangDiagnosticSeverity(typeSlice, type, code));
}
-/* static */SlangResult ParseDiagnosticUtil::parseSlangLine(SliceAllocator& allocator, const UnownedStringSlice& line, List<UnownedStringSlice>& lineSlices, ArtifactDiagnostic& outDiagnostic)
+/* static */ SlangResult ParseDiagnosticUtil::parseSlangLine(
+ SliceAllocator& allocator,
+ const UnownedStringSlice& line,
+ List<UnownedStringSlice>& lineSlices,
+ ArtifactDiagnostic& outDiagnostic)
{
/*
- tests/diagnostics/accessors.slang(11): error 31101: accessors other than 'set' must not have parameters
+ tests/diagnostics/accessors.slang(11): error 31101: accessors other than 'set' must not have
+ parameters
*/
// Can be larger than 3, because might be : in the actual error text
@@ -125,7 +137,8 @@ static bool _isSlangDiagnostic(const UnownedStringSlice& line)
return SLANG_FAIL;
}
- SLANG_RETURN_ON_FAIL(ArtifactDiagnosticUtil::splitPathLocation(allocator, lineSlices[0], outDiagnostic));
+ SLANG_RETURN_ON_FAIL(
+ ArtifactDiagnosticUtil::splitPathLocation(allocator, lineSlices[0], outDiagnostic));
Int code;
SLANG_RETURN_ON_FAIL(_getSlangDiagnosticSeverity(lineSlices[1], outDiagnostic.severity, code));
@@ -140,11 +153,16 @@ static bool _isSlangDiagnostic(const UnownedStringSlice& line)
return SLANG_OK;
}
-/* static */ SlangResult ParseDiagnosticUtil::splitDiagnosticLine(const CompilerIdentity& compilerIdentity, const UnownedStringSlice& line, const UnownedStringSlice& linePrefix, List<UnownedStringSlice>& outSlices)
+/* static */ SlangResult ParseDiagnosticUtil::splitDiagnosticLine(
+ const CompilerIdentity& compilerIdentity,
+ const UnownedStringSlice& line,
+ const UnownedStringSlice& linePrefix,
+ List<UnownedStringSlice>& outSlices)
{
StringUtil::split(line, ':', outSlices);
- // If we have a prefix (typically identifying the compiler), remove so same code can be used for output with prefixes and without
+ // If we have a prefix (typically identifying the compiler), remove so same code can be used for
+ // output with prefixes and without
if (linePrefix.getLength())
{
SLANG_ASSERT(outSlices[0].startsWith(linePrefix));
@@ -154,10 +172,12 @@ static bool _isSlangDiagnostic(const UnownedStringSlice& line)
/*
glslang: ERROR: tests/diagnostics/syntax-error-intrinsic.slang:13: '@' : unexpected token
dxc: tests/diagnostics/syntax-error-intrinsic.slang:14:2: error: expected expression
- fxc: tests/diagnostics/syntax-error-intrinsic.slang(14,2): error X3000: syntax error: unexpected token '@'
- Visual Studio 14.0: e:\git\somewhere\tests\diagnostics\syntax-error-intrinsic.slang(13): error C2018: unknown character '0x40'
- NVRTC 11.0: tests/diagnostics/syntax-error-intrinsic.slang(13): error : unrecognized token
- tests/diagnostics/accessors.slang(11): error 31101: accessors other than 'set' must not have parameters
+ fxc: tests/diagnostics/syntax-error-intrinsic.slang(14,2): error X3000: syntax error: unexpected
+ token '@' Visual Studio 14.0:
+ e:\git\somewhere\tests\diagnostics\syntax-error-intrinsic.slang(13): error C2018: unknown
+ character '0x40' NVRTC 11.0: tests/diagnostics/syntax-error-intrinsic.slang(13): error :
+ unrecognized token tests/diagnostics/accessors.slang(11): error 31101: accessors other than
+ 'set' must not have parameters
*/
// The index where the path starts
@@ -171,7 +191,8 @@ static bool _isSlangDiagnostic(const UnownedStringSlice& line)
if (pathStart.getLength() == 1 && CharUtil::isAlpha(pathStart[0]))
{
// Splice back together
- outSlices[pathIndex] = UnownedStringSlice(outSlices[pathIndex].begin(), outSlices[pathIndex + 1].end());
+ outSlices[pathIndex] =
+ UnownedStringSlice(outSlices[pathIndex].begin(), outSlices[pathIndex + 1].end());
outSlices.removeAt(pathIndex + 1);
}
}
@@ -179,7 +200,9 @@ static bool _isSlangDiagnostic(const UnownedStringSlice& line)
return SLANG_OK;
}
-static SlangResult _findDownstreamCompiler(const UnownedStringSlice& slice, SlangPassThrough& outDownstreamCompiler)
+static SlangResult _findDownstreamCompiler(
+ const UnownedStringSlice& slice,
+ SlangPassThrough& outDownstreamCompiler)
{
for (Index i = SLANG_PASS_THROUGH_NONE + 1; i < SLANG_PASS_THROUGH_COUNT_OF; ++i)
{
@@ -195,14 +218,17 @@ static SlangResult _findDownstreamCompiler(const UnownedStringSlice& slice, Slan
return SLANG_FAIL;
}
-/* static */SlangResult ParseDiagnosticUtil::identifyCompiler(const UnownedStringSlice& inText, CompilerIdentity& outIdentity)
+/* static */ SlangResult ParseDiagnosticUtil::identifyCompiler(
+ const UnownedStringSlice& inText,
+ CompilerIdentity& outIdentity)
{
outIdentity = CompilerIdentity();
- // This might be overkill - we should be able to identify the compiler from the first line, of the diagnostics.
- // Here, we go through each line trying to identify the compiler.
- // For downstream compilers, the only way to identify unambiguously is via the compiler name prefix.
- // For Slang we *assume* if there isn't such a prefix, and it 'looks like' a Slang diagnostic that it is
+ // This might be overkill - we should be able to identify the compiler from the first line, of
+ // the diagnostics. Here, we go through each line trying to identify the compiler. For
+ // downstream compilers, the only way to identify unambiguously is via the compiler name prefix.
+ // For Slang we *assume* if there isn't such a prefix, and it 'looks like' a Slang diagnostic
+ // that it is
UnownedStringSlice text(inText), line;
while (StringUtil::extractLine(text, line))
@@ -229,13 +255,14 @@ static SlangResult _findDownstreamCompiler(const UnownedStringSlice& slice, Slan
return SLANG_FAIL;
}
-/* static */ParseDiagnosticUtil::LineParser ParseDiagnosticUtil::getLineParser(const CompilerIdentity& compilerIdentity)
+/* static */ ParseDiagnosticUtil::LineParser ParseDiagnosticUtil::getLineParser(
+ const CompilerIdentity& compilerIdentity)
{
switch (compilerIdentity.m_type)
{
- case CompilerIdentity::Slang: return &parseSlangLine;
- case CompilerIdentity::DownstreamCompiler: return &parseGenericLine;
- default: return nullptr;
+ case CompilerIdentity::Slang: return &parseSlangLine;
+ case CompilerIdentity::DownstreamCompiler: return &parseGenericLine;
+ default: return nullptr;
}
}
@@ -251,7 +278,9 @@ static bool _isWhitespace(const UnownedStringSlice& slice)
return true;
}
-/* static */SlangResult ParseDiagnosticUtil::parseDiagnostics(const UnownedStringSlice& inText, IArtifactDiagnostics* diagnostics)
+/* static */ SlangResult ParseDiagnosticUtil::parseDiagnostics(
+ const UnownedStringSlice& inText,
+ IArtifactDiagnostics* diagnostics)
{
if (_isWhitespace(inText))
{
@@ -276,7 +305,11 @@ static bool _isWhitespace(const UnownedStringSlice& slice)
return parseDiagnostics(inText, compilerIdentity, linePrefix, diagnostics);
}
-/* static */SlangResult ParseDiagnosticUtil::parseDiagnostics(const UnownedStringSlice& inText, const CompilerIdentity& compilerIdentity, const UnownedStringSlice& linePrefix, IArtifactDiagnostics* diagnostics)
+/* static */ SlangResult ParseDiagnosticUtil::parseDiagnostics(
+ const UnownedStringSlice& inText,
+ const CompilerIdentity& compilerIdentity,
+ const UnownedStringSlice& linePrefix,
+ IArtifactDiagnostics* diagnostics)
{
auto lineParser = getLineParser(compilerIdentity);
if (!lineParser)
@@ -296,13 +329,16 @@ static bool _isWhitespace(const UnownedStringSlice& slice)
if (linePrefix.getLength() > 0 && line.startsWith(linePrefix))
{
// Try with the line prefix
- isValidSplit = SLANG_SUCCEEDED(splitDiagnosticLine(compilerIdentity, line, linePrefix, splitLine));
+ isValidSplit =
+ SLANG_SUCCEEDED(splitDiagnosticLine(compilerIdentity, line, linePrefix, splitLine));
}
if (!isValidSplit)
{
- // Try without the prefix, as some output output's only some lines with the prefix (GLSL for example)
- isValidSplit = SLANG_SUCCEEDED(splitDiagnosticLine(compilerIdentity, line, UnownedStringSlice(), splitLine));
+ // Try without the prefix, as some output output's only some lines with the prefix (GLSL
+ // for example)
+ isValidSplit = SLANG_SUCCEEDED(
+ splitDiagnosticLine(compilerIdentity, line, UnownedStringSlice(), splitLine));
}
// If we don't have a valid split then just assume it's a note
@@ -316,7 +352,7 @@ static bool _isWhitespace(const UnownedStringSlice& slice)
diagnostic.severity = ArtifactDiagnostic::Severity::Error;
diagnostic.stage = ArtifactDiagnostic::Stage::Compile;
diagnostic.location.line = 0;
-
+
if (SLANG_SUCCEEDED(lineParser(allocator, line, splitLine, diagnostic)))
{
diagnostics->add(diagnostic);
@@ -324,7 +360,7 @@ static bool _isWhitespace(const UnownedStringSlice& slice)
else
{
// If couldn't parse, just add as a note
- ArtifactDiagnosticUtil::maybeAddNote(line, diagnostics);
+ ArtifactDiagnosticUtil::maybeAddNote(line, diagnostics);
}
}
@@ -355,7 +391,9 @@ static bool _isAtEnd(const UnownedStringSlice& text, const UnownedStringSlice& l
return (nextLine != toSlice("}"));
}
-/* static */SlangResult ParseDiagnosticUtil::parseOutputInfo(const UnownedStringSlice& inText, OutputInfo& out)
+/* static */ SlangResult ParseDiagnosticUtil::parseOutputInfo(
+ const UnownedStringSlice& inText,
+ OutputInfo& out)
{
enum State
{
@@ -368,7 +406,7 @@ static bool _isAtEnd(const UnownedStringSlice& text, const UnownedStringSlice& l
UnownedStringSlice stdErrorPrefix = UnownedStringSlice::fromLiteral("standard error");
UnownedStringSlice stdOutputPrefix = UnownedStringSlice::fromLiteral("standard output");
-
+
List<UnownedStringSlice> lines;
State state = State::Normal;
@@ -378,12 +416,13 @@ static bool _isAtEnd(const UnownedStringSlice& text, const UnownedStringSlice& l
{
switch (state)
{
- case State::Normal:
+ case State::Normal:
{
if (line.startsWith(resultCodePrefix))
{
// Split past the equal
- const UnownedStringSlice valueSlice = _getEquals(line.tail(resultCodePrefix.getLength()));
+ const UnownedStringSlice valueSlice =
+ _getEquals(line.tail(resultCodePrefix.getLength()));
Int value;
SLANG_RETURN_ON_FAIL(StringUtil::parseInt(valueSlice, value));
out.resultCode = int(value);
@@ -405,19 +444,21 @@ static bool _isAtEnd(const UnownedStringSlice& text, const UnownedStringSlice& l
// Clear the lines buffer
lines.clear();
- UnownedStringSlice valueSlice = _getEquals(line.tail(startsWith->getLength()));
+ UnownedStringSlice valueSlice =
+ _getEquals(line.tail(startsWith->getLength()));
if (!valueSlice.isChar('{'))
{
return SLANG_FAIL;
}
// Okay we now inside std out or std error, so update the state
- state = (startsWith == &stdErrorPrefix) ? State::InStdError : State::InStdOut;
+ state =
+ (startsWith == &stdErrorPrefix) ? State::InStdError : State::InStdOut;
}
}
break;
}
- case State::InStdError:
- case State::InStdOut:
+ case State::InStdError:
+ case State::InStdOut:
{
if (_isAtEnd(text, line))
{
@@ -440,7 +481,10 @@ static bool _isAtEnd(const UnownedStringSlice& text, const UnownedStringSlice& l
}
-/* static */bool ParseDiagnosticUtil::areEqual(const UnownedStringSlice& a, const UnownedStringSlice& b, EqualityFlags flags)
+/* static */ bool ParseDiagnosticUtil::areEqual(
+ const UnownedStringSlice& a,
+ const UnownedStringSlice& b,
+ EqualityFlags flags)
{
auto diagsA = ArtifactDiagnostics::create();
auto diagsB = ArtifactDiagnostics::create();
@@ -464,8 +508,7 @@ static bool _isAtEnd(const UnownedStringSlice& text, const UnownedStringSlice& l
*/
// Must have both succeeded, and have the same amount of lines
- if (SLANG_SUCCEEDED(resA) && SLANG_SUCCEEDED(resB) &&
- diagsA->getCount() == diagsB->getCount())
+ if (SLANG_SUCCEEDED(resA) && SLANG_SUCCEEDED(resB) && diagsA->getCount() == diagsB->getCount())
{
const auto count = diagsA->getCount();
for (Index i = 0; i < count; ++i)
@@ -490,6 +533,6 @@ static bool _isAtEnd(const UnownedStringSlice& text, const UnownedStringSlice& l
return true;
}
-
+
return false;
}
diff --git a/tools/slang-test/parse-diagnostic-util.h b/tools/slang-test/parse-diagnostic-util.h
index 44707b9ff..269c90483 100644
--- a/tools/slang-test/parse-diagnostic-util.h
+++ b/tools/slang-test/parse-diagnostic-util.h
@@ -3,13 +3,10 @@
#ifndef PARSE_DIAGNOSTIC_UTIL_H
#define PARSE_DIAGNOSTIC_UTIL_H
+#include "../../source/compiler-core/slang-artifact-diagnostic-util.h"
+#include "../../source/compiler-core/slang-downstream-compiler.h"
#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-string.h"
-
-#include "../../source/compiler-core/slang-downstream-compiler.h"
-
-#include "../../source/compiler-core/slang-artifact-diagnostic-util.h"
-
#include "slang-com-ptr.h"
struct ParseDiagnosticUtil
@@ -21,11 +18,11 @@ struct ParseDiagnosticUtil
Slang::String stdOut;
};
- /// We need a way to identify downstream compilers and others - specifically here Slang.
- /// Ideally we'd have an enum that included Slang.
- /// Just adding to SlangPassThrough doesn't seem right. If we had an enumeration with a
- /// more appropriate name, then including downstream and slang compilers wouldn't be a problem.
- /// So for now this is punted, and this type is used to represent possible compiler identities.
+ /// We need a way to identify downstream compilers and others - specifically here Slang.
+ /// Ideally we'd have an enum that included Slang.
+ /// Just adding to SlangPassThrough doesn't seem right. If we had an enumeration with a
+ /// more appropriate name, then including downstream and slang compilers wouldn't be a problem.
+ /// So for now this is punted, and this type is used to represent possible compiler identities.
struct CompilerIdentity
{
typedef CompilerIdentity ThisType;
@@ -37,14 +34,26 @@ struct ParseDiagnosticUtil
DownstreamCompiler,
};
- static CompilerIdentity make(Type type, SlangPassThrough downstreamCompiler) { CompilerIdentity ident; ident.m_type = type; ident.m_downstreamCompiler = downstreamCompiler; return ident; }
- static CompilerIdentity make(SlangPassThrough downstreamCompiler) { return make(Type::DownstreamCompiler, downstreamCompiler); }
+ static CompilerIdentity make(Type type, SlangPassThrough downstreamCompiler)
+ {
+ CompilerIdentity ident;
+ ident.m_type = type;
+ ident.m_downstreamCompiler = downstreamCompiler;
+ return ident;
+ }
+ static CompilerIdentity make(SlangPassThrough downstreamCompiler)
+ {
+ return make(Type::DownstreamCompiler, downstreamCompiler);
+ }
static CompilerIdentity makeSlang() { return make(Type::Slang, SLANG_PASS_THROUGH_NONE); }
- bool operator==(const ThisType& rhs) const { return m_type == rhs.m_type && m_downstreamCompiler == rhs.m_downstreamCompiler; }
+ bool operator==(const ThisType& rhs) const
+ {
+ return m_type == rhs.m_type && m_downstreamCompiler == rhs.m_downstreamCompiler;
+ }
bool operator!=(const ThisType& rhs) const { return !(*this == rhs); }
- Type m_type = Type::Unknown;
+ Type m_type = Type::Unknown;
SlangPassThrough m_downstreamCompiler = SLANG_PASS_THROUGH_NONE;
};
@@ -57,36 +66,65 @@ struct ParseDiagnosticUtil
};
};
- typedef SlangResult (*LineParser)(Slang::SliceAllocator& allocator, const Slang::UnownedStringSlice& line, Slang::List<Slang::UnownedStringSlice>& lineSlices, Slang::ArtifactDiagnostic& outDiagnostic);
+ typedef SlangResult (*LineParser)(
+ Slang::SliceAllocator& allocator,
+ const Slang::UnownedStringSlice& line,
+ Slang::List<Slang::UnownedStringSlice>& lineSlices,
+ Slang::ArtifactDiagnostic& outDiagnostic);
- /// Given a compiler identity returns a line parsing function.
+ /// Given a compiler identity returns a line parsing function.
static LineParser getLineParser(const CompilerIdentity& compilerIdentity);
- /// For a 'generic' (as in uses DownstreamCompiler mechanism) line parsing
- static SlangResult parseGenericLine(Slang::SliceAllocator& allocator, const Slang::UnownedStringSlice& line, Slang::List<Slang::UnownedStringSlice>& lineSlices, Slang::ArtifactDiagnostic& outDiagnostic);
-
- /// For parsing diagnostics from Slang
- static SlangResult parseSlangLine(Slang::SliceAllocator& allocator, const Slang::UnownedStringSlice& line, Slang::List<Slang::UnownedStringSlice>& lineSlices, Slang::ArtifactDiagnostic& outDiagnostic);
-
- /// Parse diagnostics into output text
- static SlangResult parseDiagnostics(const Slang::UnownedStringSlice& inText, Slang::IArtifactDiagnostics* diagnostics);
-
- /// Parse diagnostics with known compiler identity.
- /// If the prefix is empty, it is assumed there is no prefix and it won't be checked.
- static SlangResult parseDiagnostics(const Slang::UnownedStringSlice& inText, const CompilerIdentity& identity, const Slang::UnownedStringSlice& prefix, Slang::IArtifactDiagnostics* diagnostics);
-
- /// Given the file output style used by tests, get components of the output into Diagnostic
+ /// For a 'generic' (as in uses DownstreamCompiler mechanism) line parsing
+ static SlangResult parseGenericLine(
+ Slang::SliceAllocator& allocator,
+ const Slang::UnownedStringSlice& line,
+ Slang::List<Slang::UnownedStringSlice>& lineSlices,
+ Slang::ArtifactDiagnostic& outDiagnostic);
+
+ /// For parsing diagnostics from Slang
+ static SlangResult parseSlangLine(
+ Slang::SliceAllocator& allocator,
+ const Slang::UnownedStringSlice& line,
+ Slang::List<Slang::UnownedStringSlice>& lineSlices,
+ Slang::ArtifactDiagnostic& outDiagnostic);
+
+ /// Parse diagnostics into output text
+ static SlangResult parseDiagnostics(
+ const Slang::UnownedStringSlice& inText,
+ Slang::IArtifactDiagnostics* diagnostics);
+
+ /// Parse diagnostics with known compiler identity.
+ /// If the prefix is empty, it is assumed there is no prefix and it won't be checked.
+ static SlangResult parseDiagnostics(
+ const Slang::UnownedStringSlice& inText,
+ const CompilerIdentity& identity,
+ const Slang::UnownedStringSlice& prefix,
+ Slang::IArtifactDiagnostics* diagnostics);
+
+ /// Given the file output style used by tests, get components of the output into Diagnostic
static SlangResult parseOutputInfo(const Slang::UnownedStringSlice& in, OutputInfo& out);
- /// Given a line split it into slices - taking into account compiler output, path considerations, and potentially line prefixing
- static SlangResult splitDiagnosticLine(const CompilerIdentity& compilerIdentity, const Slang::UnownedStringSlice& line, const Slang::UnownedStringSlice& linePrefix, Slang::List<Slang::UnownedStringSlice>& outSlices);
-
- /// Give text of diagnostic determine which compiler the output is from
- static SlangResult identifyCompiler(const Slang::UnownedStringSlice& in, CompilerIdentity& outIdentity);
-
- /// Determines if the diagnostics in a and b (they are parsed via parseDiagnostics) are equal, taking into account flags
- /// Note! If the parse of either a or b fails, then equality is returns as false.
- static bool areEqual(const Slang::UnownedStringSlice& a, const Slang::UnownedStringSlice& b, EqualityFlags flags);
+ /// Given a line split it into slices - taking into account compiler output, path
+ /// considerations, and potentially line prefixing
+ static SlangResult splitDiagnosticLine(
+ const CompilerIdentity& compilerIdentity,
+ const Slang::UnownedStringSlice& line,
+ const Slang::UnownedStringSlice& linePrefix,
+ Slang::List<Slang::UnownedStringSlice>& outSlices);
+
+ /// Give text of diagnostic determine which compiler the output is from
+ static SlangResult identifyCompiler(
+ const Slang::UnownedStringSlice& in,
+ CompilerIdentity& outIdentity);
+
+ /// Determines if the diagnostics in a and b (they are parsed via parseDiagnostics) are equal,
+ /// taking into account flags Note! If the parse of either a or b fails, then equality is
+ /// returns as false.
+ static bool areEqual(
+ const Slang::UnownedStringSlice& a,
+ const Slang::UnownedStringSlice& b,
+ EqualityFlags flags);
};
#endif // PARSE_DIAGNOSTIC_UTIL_H
diff --git a/tools/slang-test/slang-test-main.cpp b/tools/slang-test/slang-test-main.cpp
index c62e2b10e..904f6683a 100644
--- a/tools/slang-test/slang-test-main.cpp
+++ b/tools/slang-test/slang-test-main.cpp
@@ -1,51 +1,43 @@
// slang-test-main.cpp
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-token-reader.h"
-#include "../../source/core/slang-std-writers.h"
-#include "../../source/core/slang-hex-dump-util.h"
-#include "../../source/core/slang-type-text-util.h"
-#include "../../source/core/slang-memory-arena.h"
-#include "../../source/core/slang-castable.h"
-
#include "../../source/compiler-core/slang-artifact-desc-util.h"
#include "../../source/compiler-core/slang-artifact-helper.h"
-
-#include "slang-com-helper.h"
-
-#include "../../source/core/slang-string-util.h"
-#include "../../source/core/slang-string-escape-util.h"
-
#include "../../source/core/slang-byte-encode-util.h"
+#include "../../source/core/slang-castable.h"
#include "../../source/core/slang-char-util.h"
+#include "../../source/core/slang-hex-dump-util.h"
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-memory-arena.h"
#include "../../source/core/slang-process-util.h"
#include "../../source/core/slang-render-api-util.h"
-
#include "../../source/core/slang-shared-library.h"
-
+#include "../../source/core/slang-std-writers.h"
+#include "../../source/core/slang-string-escape-util.h"
+#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-token-reader.h"
+#include "../../source/core/slang-type-text-util.h"
+#include "slang-com-helper.h"
#include "tools/unit-test/slang-unit-test.h"
#undef SLANG_UNIT_TEST
+#include "../../source/compiler-core/slang-artifact-associated-impl.h"
+#include "../../source/compiler-core/slang-downstream-compiler.h"
+#include "../../source/compiler-core/slang-language-server-protocol.h"
+#include "../../source/compiler-core/slang-nvrtc-compiler.h"
#include "directory-util.h"
-#include "test-context.h"
-#include "test-reporter.h"
#include "options.h"
-#include "slangc-tool.h"
#include "parse-diagnostic-util.h"
-
-#include "../../source/compiler-core/slang-downstream-compiler.h"
-#include "../../source/compiler-core/slang-nvrtc-compiler.h"
-#include "../../source/compiler-core/slang-language-server-protocol.h"
-
-#include "../../source/compiler-core/slang-artifact-associated-impl.h"
+#include "slangc-tool.h"
+#include "test-context.h"
+#include "test-reporter.h"
#define STB_IMAGE_IMPLEMENTATION
#include "external/stb/stb_image.h"
#include <math.h>
+#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
-#include <stdarg.h>
#define SLANG_PRELUDE_NAMESPACE CPPPrelude
#include "../../prelude/slang-cpp-types.h"
@@ -60,8 +52,8 @@ struct TestOptions
{
enum Type
{
- Normal, ///< A regular test
- Diagnostic, ///< Diagnostic tests will always run (as form of failure is being tested)
+ Normal, ///< A regular test
+ Diagnostic, ///< Diagnostic tests will always run (as form of failure is being tested)
};
void addCategory(TestCategory* category)
@@ -71,7 +63,7 @@ struct TestOptions
categories.add(category);
}
}
- void addCategories(TestCategory*const* inCategories, Index count)
+ void addCategories(TestCategory* const* inCategories, Index count)
{
for (Index i = 0; i < count; ++i)
{
@@ -114,12 +106,13 @@ struct FileTestInfoImpl : public FileTestInfo
struct TestDetails
{
TestDetails() {}
- explicit TestDetails(const TestOptions& inOptions):
- options(inOptions)
- {}
+ explicit TestDetails(const TestOptions& inOptions)
+ : options(inOptions)
+ {
+ }
- TestOptions options; ///< The options for the test
- TestRequirements requirements; ///< The requirements for the test to work
+ TestOptions options; ///< The options for the test
+ TestRequirements requirements; ///< The requirements for the test to work
};
// Information on tests to run for a particular file
@@ -132,22 +125,22 @@ struct FileTestList
struct TestInput
{
// Path to the input file for the test
- String filePath;
+ String filePath;
// Prefix for the path that test output should write to
// (usually the same as `filePath`, but will differ when
// we run multiple tests out of the same file)
- String outputStem;
+ String outputStem;
// Arguments for the test (usually to be interpreted
// as command line args)
- TestOptions const* testOptions;
+ TestOptions const* testOptions;
// Determines how the test will be spawned
SpawnType spawnType;
};
-typedef TestResult(*TestCallback)(TestContext* context, TestInput& input);
+typedef TestResult (*TestCallback)(TestContext* context, TestInput& input);
// Globals
@@ -163,7 +156,7 @@ static SlangResult _readTestFile(const TestInput& input, const String& suffix, S
{
StringBuilder buf;
buf << input.outputStem << suffix;
- if(auto r = Slang::File::readAllText(buf, out); SLANG_SUCCEEDED(r))
+ if (auto r = Slang::File::readAllText(buf, out); SLANG_SUCCEEDED(r))
{
return r;
}
@@ -177,12 +170,13 @@ static SlangResult _readTestFile(const TestInput& input, const String& suffix, S
bool match(char const** ioCursor, char const* expected)
{
char const* cursor = *ioCursor;
- while(*expected && *cursor == *expected)
+ while (*expected && *cursor == *expected)
{
cursor++;
expected++;
}
- if(*expected != 0) return false;
+ if (*expected != 0)
+ return false;
*ioCursor = cursor;
return true;
@@ -191,17 +185,14 @@ bool match(char const** ioCursor, char const* expected)
void skipHorizontalSpace(char const** ioCursor)
{
char const* cursor = *ioCursor;
- for( ;;)
+ for (;;)
{
- switch( *cursor )
+ switch (*cursor)
{
case ' ':
- case '\t':
- cursor++;
- continue;
+ case '\t': cursor++; continue;
- default:
- break;
+ default: break;
}
break;
@@ -212,33 +203,30 @@ void skipHorizontalSpace(char const** ioCursor)
void skipToEndOfLine(char const** ioCursor)
{
char const* cursor = *ioCursor;
- for( ;;)
+ for (;;)
{
int c = *cursor;
- switch( c )
+ switch (c)
{
- default:
- cursor++;
- continue;
+ default: cursor++; continue;
- case '\r': case '\n':
+ case '\r':
+ case '\n':
{
cursor++;
int d = *cursor;
- if( (c ^ d) == ('\r' ^ '\n') )
+ if ((c ^ d) == ('\r' ^ '\n'))
{
cursor++;
}
}
[[fallthrough]];
- case 0:
- *ioCursor = cursor;
- return;
+ case 0: *ioCursor = cursor; return;
}
}
}
-String getString(char const* textBegin, char const* textEnd)
+String getString(char const* textBegin, char const* textEnd)
{
StringBuilder sb;
sb.append(textBegin, textEnd - textBegin);
@@ -261,18 +249,21 @@ static bool _isEndOfLineOrParens(char c)
{
switch (c)
{
- case '\n':
- case '\r':
- case 0:
- case ')':
+ case '\n':
+ case '\r':
+ case 0:
+ case ')':
{
return true;
}
- default: return false;
+ default: return false;
}
}
-static SlangResult _parseCategories(TestCategorySet* categorySet, char const** ioCursor, TestOptions& out)
+static SlangResult _parseCategories(
+ TestCategorySet* categorySet,
+ char const** ioCursor,
+ TestOptions& out)
{
char const* cursor = *ioCursor;
@@ -280,10 +271,11 @@ static SlangResult _parseCategories(TestCategorySet* categorySet, char const** i
if (*cursor == '(')
{
cursor++;
- const char*const start = cursor;
+ const char* const start = cursor;
// Find the end
- for (; !_isEndOfLineOrParens(*cursor); ++cursor);
+ for (; !_isEndOfLineOrParens(*cursor); ++cursor)
+ ;
if (*cursor != ')')
{
*ioCursor = cursor;
@@ -324,10 +316,11 @@ static SlangResult _parseCommandArguments(char const** ioCursor, TestOptions& ou
if (*cursor == '(')
{
cursor++;
- const char*const start = cursor;
+ const char* const start = cursor;
// Find the end
- for (; !_isEndOfLineOrParens(*cursor); ++cursor);
+ for (; !_isEndOfLineOrParens(*cursor); ++cursor)
+ ;
if (*cursor != ')')
{
*ioCursor = cursor;
@@ -341,13 +334,13 @@ static SlangResult _parseCommandArguments(char const** ioCursor, TestOptions& ou
for (auto& option : options)
{
auto i = option.indexOf('=');
- if(i == -1)
+ if (i == -1)
{
out.commandOptions.add(option.trim(), "");
}
else
{
- out.commandOptions.add(option.head(i).trim(), option.tail(i+1).trim());
+ out.commandOptions.add(option.head(i).trim(), option.tail(i + 1).trim());
}
}
}
@@ -359,30 +352,30 @@ static SlangResult _parseCommandArguments(char const** ioCursor, TestOptions& ou
static SlangResult _parseArg(const char** ioCursor, UnownedStringSlice& outArg)
{
const char* cursor = *ioCursor;
- const char*const argBegin = cursor;
-
+ const char* const argBegin = cursor;
+
// Let's try to read one option
for (;;)
{
switch (*cursor)
{
- default:
+ default:
{
++cursor;
break;
}
- case '"':
+ case '"':
{
// If we have quotes let's just parse them as is and make output
auto escapeHandler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Space);
SLANG_RETURN_ON_FAIL(escapeHandler->lexQuoted(cursor, &cursor));
break;
}
- case 0:
- case '\r':
- case '\n':
- case ' ':
- case '\t':
+ case 0:
+ case '\r':
+ case '\n':
+ case ' ':
+ case '\t':
{
char const* argEnd = cursor;
assert(argBegin != argEnd);
@@ -396,36 +389,34 @@ static SlangResult _parseArg(const char** ioCursor, UnownedStringSlice& outArg)
}
static SlangResult _gatherTestOptions(
- TestCategorySet* categorySet,
- char const** ioCursor,
- TestOptions& outOptions)
+ TestCategorySet* categorySet,
+ char const** ioCursor,
+ TestOptions& outOptions)
{
SLANG_RETURN_ON_FAIL(_parseCategories(categorySet, ioCursor, outOptions));
char const* cursor = *ioCursor;
- if(*cursor != ':')
+ if (*cursor != ':')
{
return SLANG_FAIL;
}
cursor++;
-
+
// Next scan for a sub-command name
char const* commandStart = cursor;
- for(;;)
+ for (;;)
{
- switch(*cursor)
+ switch (*cursor)
{
- default:
- cursor++;
- continue;
+ default: cursor++; continue;
case '(':
- case ':':
- break;
-
- case 0: case '\r': case '\n':
- return SLANG_FAIL;
+ case ':': break;
+
+ case 0:
+ case '\r':
+ case '\n': return SLANG_FAIL;
}
break;
@@ -441,7 +432,7 @@ static SlangResult _gatherTestOptions(
// Format is: (foo=bar, baz = 2)
SLANG_RETURN_ON_FAIL(_parseCommandArguments(&cursor, outOptions));
- if(*cursor == ':')
+ if (*cursor == ':')
cursor++;
else
{
@@ -450,21 +441,22 @@ static SlangResult _gatherTestOptions(
// Now scan for arguments. For now we just assume that
// any whitespace separation indicates a new argument
- for(;;)
+ for (;;)
{
skipHorizontalSpace(&cursor);
// End of line? then no more options.
- switch( *cursor )
+ switch (*cursor)
{
- case 0: case '\r': case '\n':
+ case 0:
+ case '\r':
+ case '\n':
skipToEndOfLine(&cursor);
*ioCursor = cursor;
return SLANG_OK;
- default:
- break;
+ default: break;
}
// Let's try to read one option
@@ -496,7 +488,7 @@ static void _combineOptions(
static SlangResult _extractCommand(const char** ioCursor, UnownedStringSlice& outCommand)
{
const char* cursor = *ioCursor;
- const char*const start = cursor;
+ const char* const start = cursor;
while (true)
{
@@ -521,9 +513,9 @@ static SlangResult _extractCommand(const char** ioCursor, UnownedStringSlice& ou
// Try to read command-line options from the test file itself
static SlangResult _gatherTestsForFile(
- TestCategorySet* categorySet,
- String filePath,
- FileTestList* outTestList)
+ TestCategorySet* categorySet,
+ String filePath,
+ FileTestList* outTestList)
{
outTestList->tests.clear();
@@ -537,13 +529,13 @@ static SlangResult _gatherTestsForFile(
// Options that are specified across all tests in the file.
TestOptions fileOptions;
- while(*cursor)
+ while (*cursor)
{
// We are at the start of a line of input.
skipHorizontalSpace(&cursor);
- if(!match(&cursor, "//"))
+ if (!match(&cursor, "//"))
{
skipToEndOfLine(&cursor);
continue;
@@ -580,20 +572,22 @@ static SlangResult _gatherTestsForFile(
if (command == "TEST_CATEGORY")
{
SlangResult res = _parseCategories(categorySet, &cursor, fileOptions);
-
+
// If if failed we are done, unless it was just 'not available'
- if (SLANG_FAILED(res) && res != SLANG_E_NOT_AVAILABLE) return res;
+ if (SLANG_FAILED(res) && res != SLANG_E_NOT_AVAILABLE)
+ return res;
skipToEndOfLine(&cursor);
continue;
}
- if(command == "TEST")
+ if (command == "TEST")
{
SLANG_RETURN_ON_FAIL(_gatherTestOptions(categorySet, &cursor, testDetails.options));
// See if the type of test needs certain APIs available
- const RenderApiFlags testRequiredApis = _getRequiredRenderApisByCommand(testDetails.options.command.getUnownedSlice());
+ const RenderApiFlags testRequiredApis =
+ _getRequiredRenderApisByCommand(testDetails.options.command.getUnownedSlice());
testDetails.requirements.addUsedRenderApis(testRequiredApis);
// Apply the file wide options
@@ -623,7 +617,10 @@ static SlangResult _gatherTestsForFile(
return SLANG_OK;
}
-static void SLANG_STDCALL _fileCheckDiagnosticCallback(void* data, const TestMessageType messageType, const char* message) noexcept
+static void SLANG_STDCALL _fileCheckDiagnosticCallback(
+ void* data,
+ const TestMessageType messageType,
+ const char* message) noexcept
{
auto& testReporter = *reinterpret_cast<TestReporter*>(data);
testReporter.message(messageType, message);
@@ -641,7 +638,7 @@ static TestResult _fileCheckTest(
auto& testReporter = *context.getTestReporter();
IFileCheck* fc = context.getFileCheck();
- if(!fc)
+ if (!fc)
{
// Ignore if FileCheck is not available.
// We could report an error, but our ARM64 CI doesn't have FileCheck yet.
@@ -675,13 +672,14 @@ static TestResult _fileComparisonTest(
if (SLANG_FAILED(_readTestFile(input, expectedFileSuffix, expectedOutput)))
{
- if(defaultExpectedContent)
+ if (defaultExpectedContent)
{
expectedOutput = defaultExpectedContent;
}
else
{
- context.getTestReporter()->messageFormat(TestMessageType::RunError,
+ context.getTestReporter()->messageFormat(
+ TestMessageType::RunError,
"Unable to read %s output for '%s'\n",
expectedFileSuffix,
input.outputStem.getBuffer());
@@ -719,7 +717,13 @@ static TestResult _validateOutput(
const TestResult result =
input.testOptions->getFileCheckPrefix(fileCheckPrefix)
? _fileCheckTest(*context, input.filePath, fileCheckPrefix, actualOutput)
- : _fileComparisonTest(*context, input, defaultExpectedContent, ".expected", actualOutput, compare);
+ : _fileComparisonTest(
+ *context,
+ input,
+ defaultExpectedContent,
+ ".expected",
+ actualOutput,
+ compare);
// If the test failed, then we write the actual output to a file
// so that we can easily diff it from the command line and
@@ -736,7 +740,11 @@ static TestResult _validateOutput(
}
}
-Result spawnAndWaitExe(TestContext* context, const String& testPath, const CommandLine& cmdLine, ExecuteResult& outRes)
+Result spawnAndWaitExe(
+ TestContext* context,
+ const String& testPath,
+ const CommandLine& cmdLine,
+ ExecuteResult& outRes)
{
std::lock_guard<std::mutex> lock(context->mutex);
@@ -746,7 +754,9 @@ Result spawnAndWaitExe(TestContext* context, const String& testPath, const Comma
{
String commandLine = cmdLine.toString();
context->getTestReporter()->messageFormat(
- TestMessageType::Info, "%s\n", commandLine.begin());
+ TestMessageType::Info,
+ "%s\n",
+ commandLine.begin());
}
Result res = ProcessUtil::execute(cmdLine, outRes);
@@ -754,13 +764,19 @@ Result spawnAndWaitExe(TestContext* context, const String& testPath, const Comma
{
// fprintf(stderr, "failed to run test '%S'\n", testPath.ToWString());
context->getTestReporter()->messageFormat(
- TestMessageType::RunError, "failed to run test '%S'", testPath.toWString().begin());
+ TestMessageType::RunError,
+ "failed to run test '%S'",
+ testPath.toWString().begin());
}
return res;
}
-Result spawnAndWaitSharedLibrary(TestContext* context, const String& testPath, const CommandLine& cmdLine, ExecuteResult& outRes)
+Result spawnAndWaitSharedLibrary(
+ TestContext* context,
+ const String& testPath,
+ const CommandLine& cmdLine,
+ ExecuteResult& outRes)
{
std::lock_guard<std::mutex> lock(context->mutex);
@@ -783,7 +799,9 @@ Result spawnAndWaitSharedLibrary(TestContext* context, const String& testPath, c
testCmdLine.m_args.addRange(cmdLine.m_args);
context->getTestReporter()->messageFormat(
- TestMessageType::Info, "%s\n", testCmdLine.toString().getBuffer());
+ TestMessageType::Info,
+ "%s\n",
+ testCmdLine.toString().getBuffer());
}
auto func = context->getInnerMainFunc(context->options.binDir, exeName);
@@ -816,7 +834,8 @@ Result spawnAndWaitSharedLibrary(TestContext* context, const String& testPath, c
args.add(cmdArg.getBuffer());
}
- SlangResult res = func(&stdWriters, context->getSession(), int(args.getCount()), args.begin());
+ SlangResult res =
+ func(&stdWriters, context->getSession(), int(args.getCount()), args.begin());
StdWriters::setSingleton(prevStdWriters);
@@ -832,7 +851,11 @@ Result spawnAndWaitSharedLibrary(TestContext* context, const String& testPath, c
}
-Result spawnAndWaitProxy(TestContext* context, const String& testPath, const CommandLine& inCmdLine, ExecuteResult& outRes)
+Result spawnAndWaitProxy(
+ TestContext* context,
+ const String& testPath,
+ const CommandLine& inCmdLine,
+ ExecuteResult& outRes)
{
std::lock_guard<std::mutex> lock(context->mutex);
@@ -842,7 +865,7 @@ Result spawnAndWaitProxy(TestContext* context, const String& testPath, const Com
if (exeName == "slangc")
{
// If the test is slangc there is a command line version we can just directly use
- //return spawnAndWaitExe(context, testPath, inCmdLine, outRes);
+ // return spawnAndWaitExe(context, testPath, inCmdLine, outRes);
return spawnAndWaitSharedLibrary(context, testPath, inCmdLine, outRes);
}
@@ -857,7 +880,9 @@ Result spawnAndWaitProxy(TestContext* context, const String& testPath, const Com
{
String commandLine = cmdLine.toString();
context->getTestReporter()->messageFormat(
- TestMessageType::Info, "%s\n", commandLine.begin());
+ TestMessageType::Info,
+ "%s\n",
+ commandLine.begin());
}
// Execute
@@ -866,13 +891,21 @@ Result spawnAndWaitProxy(TestContext* context, const String& testPath, const Com
{
// fprintf(stderr, "failed to run test '%S'\n", testPath.ToWString());
context->getTestReporter()->messageFormat(
- TestMessageType::RunError, "failed to run test '%S'", testPath.toWString().begin());
+ TestMessageType::RunError,
+ "failed to run test '%S'",
+ testPath.toWString().begin());
}
return res;
}
-static Result _executeRPC(TestContext* context, SpawnType spawnType, const UnownedStringSlice& method, const RttiInfo* rttiInfo, const void* args, ExecuteResult& outRes)
+static Result _executeRPC(
+ TestContext* context,
+ SpawnType spawnType,
+ const UnownedStringSlice& method,
+ const RttiInfo* rttiInfo,
+ const void* args,
+ ExecuteResult& outRes)
{
// If we are 'fully isolated', we cannot share a test server.
// So tear down the RPC connection if there is one currently.
@@ -925,13 +958,23 @@ static Result _executeRPC(TestContext* context, SpawnType spawnType, const Unown
return SLANG_OK;
}
-template <typename T>
-static Result _executeRPC(TestContext* context, SpawnType spawnType, const UnownedStringSlice& method, const T* msg, ExecuteResult& outRes)
+template<typename T>
+static Result _executeRPC(
+ TestContext* context,
+ SpawnType spawnType,
+ const UnownedStringSlice& method,
+ const T* msg,
+ ExecuteResult& outRes)
{
return _executeRPC(context, spawnType, method, GetRttiInfo<T>::get(), (const void*)msg, outRes);
}
-Result spawnAndWaitTestServer(TestContext* context, SpawnType spawnType, const String& testPath, const CommandLine& inCmdLine, ExecuteResult& outRes)
+Result spawnAndWaitTestServer(
+ TestContext* context,
+ SpawnType spawnType,
+ const String& testPath,
+ const CommandLine& inCmdLine,
+ ExecuteResult& outRes)
{
String exeName = Path::getFileNameWithoutExt(inCmdLine.m_executableLocation.m_pathOrName);
@@ -941,7 +984,12 @@ Result spawnAndWaitTestServer(TestContext* context, SpawnType spawnType, const S
args.toolName = exeName;
args.args = inCmdLine.m_args;
- return _executeRPC(context, spawnType, TestServerProtocol::ExecuteToolTestArgs::g_methodName, &args, outRes);
+ return _executeRPC(
+ context,
+ spawnType,
+ TestServerProtocol::ExecuteToolTestArgs::g_methodName,
+ &args,
+ outRes);
}
static SlangResult _extractArg(const CommandLine& cmdLine, const String& argName, String& outValue)
@@ -966,62 +1014,62 @@ static PassThroughFlags _getPassThroughFlagsForTarget(SlangCompileTarget target)
{
switch (target)
{
- case SLANG_TARGET_UNKNOWN:
-
- case SLANG_HLSL:
- case SLANG_GLSL:
- case SLANG_C_SOURCE:
- case SLANG_CPP_SOURCE:
- case SLANG_CPP_PYTORCH_BINDING:
- case SLANG_HOST_CPP_SOURCE:
- case SLANG_CUDA_SOURCE:
- case SLANG_METAL:
- case SLANG_WGSL:
+ case SLANG_TARGET_UNKNOWN:
+
+ case SLANG_HLSL:
+ case SLANG_GLSL:
+ case SLANG_C_SOURCE:
+ case SLANG_CPP_SOURCE:
+ case SLANG_CPP_PYTORCH_BINDING:
+ case SLANG_HOST_CPP_SOURCE:
+ case SLANG_CUDA_SOURCE:
+ case SLANG_METAL:
+ case SLANG_WGSL:
{
return 0;
}
- case SLANG_WGSL_SPIRV:
- case SLANG_WGSL_SPIRV_ASM:
+ case SLANG_WGSL_SPIRV:
+ case SLANG_WGSL_SPIRV_ASM:
{
return PassThroughFlag::Tint;
}
- case SLANG_DXBC:
- case SLANG_DXBC_ASM:
+ case SLANG_DXBC:
+ case SLANG_DXBC_ASM:
{
return PassThroughFlag::Fxc;
}
- case SLANG_SPIRV:
- case SLANG_SPIRV_ASM:
+ case SLANG_SPIRV:
+ case SLANG_SPIRV_ASM:
{
return PassThroughFlag::Glslang;
}
- case SLANG_DXIL:
- case SLANG_DXIL_ASM:
+ case SLANG_DXIL:
+ case SLANG_DXIL_ASM:
{
return PassThroughFlag::Dxc;
}
- case SLANG_METAL_LIB:
- case SLANG_METAL_LIB_ASM:
+ case SLANG_METAL_LIB:
+ case SLANG_METAL_LIB_ASM:
{
return PassThroughFlag::Metal;
}
- case SLANG_SHADER_HOST_CALLABLE:
- case SLANG_HOST_HOST_CALLABLE:
+ case SLANG_SHADER_HOST_CALLABLE:
+ case SLANG_HOST_HOST_CALLABLE:
- case SLANG_HOST_EXECUTABLE:
- case SLANG_SHADER_SHARED_LIBRARY:
- case SLANG_HOST_SHARED_LIBRARY:
+ case SLANG_HOST_EXECUTABLE:
+ case SLANG_SHADER_SHARED_LIBRARY:
+ case SLANG_HOST_SHARED_LIBRARY:
{
return PassThroughFlag::Generic_C_CPP;
}
- case SLANG_PTX:
+ case SLANG_PTX:
{
return PassThroughFlag::NVRTC;
}
- default:
+ default:
{
SLANG_ASSERT(!"Unknown type");
return 0;
@@ -1029,13 +1077,15 @@ static PassThroughFlags _getPassThroughFlagsForTarget(SlangCompileTarget target)
}
}
-static SlangResult _extractRenderTestRequirements(const CommandLine& cmdLine, TestRequirements* ioRequirements)
+static SlangResult _extractRenderTestRequirements(
+ const CommandLine& cmdLine,
+ TestRequirements* ioRequirements)
{
const auto& args = cmdLine.m_args;
-
- // TODO(JS):
+
+ // TODO(JS):
// This is rather convoluted in that it has to work out from the command line parameters passed
- // to render-test what renderer will be used.
+ // to render-test what renderer will be used.
// That a similar logic has to be kept inside the implementation of render-test and both this
// and render-test will have to be kept in sync.
@@ -1049,13 +1099,14 @@ static SlangResult _extractRenderTestRequirements(const CommandLine& cmdLine, Te
RenderApiType foundRenderApiType = RenderApiType::Unknown;
RenderApiType foundLanguageRenderType = RenderApiType::Unknown;
- for (const auto& arg: args)
+ for (const auto& arg : args)
{
Slang::UnownedStringSlice argSlice = arg.getUnownedSlice();
if (argSlice.getLength() && argSlice[0] == '-')
{
// Look up the rendering API if set
- UnownedStringSlice argName = UnownedStringSlice(argSlice.begin() + 1, argSlice.end());
+ UnownedStringSlice argName =
+ UnownedStringSlice(argSlice.begin() + 1, argSlice.end());
RenderApiType renderApiType = RenderApiUtil::findApiTypeByName(argName);
if (renderApiType != RenderApiType::Unknown)
@@ -1063,7 +1114,9 @@ static SlangResult _extractRenderTestRequirements(const CommandLine& cmdLine, Te
foundRenderApiType = renderApiType;
// There should be only one explicit api
- SLANG_ASSERT(ioRequirements->explicitRenderApi == RenderApiType::Unknown || ioRequirements->explicitRenderApi == renderApiType);
+ SLANG_ASSERT(
+ ioRequirements->explicitRenderApi == RenderApiType::Unknown ||
+ ioRequirements->explicitRenderApi == renderApiType);
// Set the explicitly set render api
ioRequirements->explicitRenderApi = renderApiType;
@@ -1071,7 +1124,8 @@ static SlangResult _extractRenderTestRequirements(const CommandLine& cmdLine, Te
}
// Lookup the target language type
- RenderApiType languageRenderType = RenderApiUtil::findImplicitLanguageRenderApiType(argName);
+ RenderApiType languageRenderType =
+ RenderApiUtil::findImplicitLanguageRenderApiType(argName);
if (languageRenderType != RenderApiType::Unknown)
{
foundLanguageRenderType = languageRenderType;
@@ -1084,8 +1138,9 @@ static SlangResult _extractRenderTestRequirements(const CommandLine& cmdLine, Te
}
}
- // If a render option isn't set use defaultRenderType
- renderApiType = (foundRenderApiType == RenderApiType::Unknown) ? foundLanguageRenderType : foundRenderApiType;
+ // If a render option isn't set use defaultRenderType
+ renderApiType = (foundRenderApiType == RenderApiType::Unknown) ? foundLanguageRenderType
+ : foundRenderApiType;
}
// The native language for the API
@@ -1095,46 +1150,46 @@ static SlangResult _extractRenderTestRequirements(const CommandLine& cmdLine, Te
switch (renderApiType)
{
- case RenderApiType::D3D11:
- target = SLANG_DXBC;
- nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
- passThru = SLANG_PASS_THROUGH_FXC;
- break;
- case RenderApiType::D3D12:
- target = SLANG_DXBC;
- nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
- passThru = SLANG_PASS_THROUGH_FXC;
- if (useDxil)
- {
- target = SLANG_DXIL;
- passThru = SLANG_PASS_THROUGH_DXC;
- }
- break;
- case RenderApiType::Vulkan:
- target = SLANG_SPIRV;
- nativeLanguage = SLANG_SOURCE_LANGUAGE_GLSL;
- passThru = SLANG_PASS_THROUGH_GLSLANG;
- break;
- case RenderApiType::Metal:
- target = SLANG_METAL_LIB;
- nativeLanguage = SLANG_SOURCE_LANGUAGE_METAL;
- passThru = SLANG_PASS_THROUGH_METAL;
- break;
- case RenderApiType::CPU:
- target = SLANG_SHADER_HOST_CALLABLE;
- nativeLanguage = SLANG_SOURCE_LANGUAGE_CPP;
- passThru = SLANG_PASS_THROUGH_GENERIC_C_CPP;
- break;
- case RenderApiType::CUDA:
- target = SLANG_PTX;
- nativeLanguage = SLANG_SOURCE_LANGUAGE_CUDA;
- passThru = SLANG_PASS_THROUGH_NVRTC;
- break;
- case RenderApiType::WebGPU:
- target = SLANG_WGSL;
- nativeLanguage = SLANG_SOURCE_LANGUAGE_WGSL;
- passThru = SLANG_PASS_THROUGH_TINT;
- break;
+ case RenderApiType::D3D11:
+ target = SLANG_DXBC;
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
+ passThru = SLANG_PASS_THROUGH_FXC;
+ break;
+ case RenderApiType::D3D12:
+ target = SLANG_DXBC;
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
+ passThru = SLANG_PASS_THROUGH_FXC;
+ if (useDxil)
+ {
+ target = SLANG_DXIL;
+ passThru = SLANG_PASS_THROUGH_DXC;
+ }
+ break;
+ case RenderApiType::Vulkan:
+ target = SLANG_SPIRV;
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_GLSL;
+ passThru = SLANG_PASS_THROUGH_GLSLANG;
+ break;
+ case RenderApiType::Metal:
+ target = SLANG_METAL_LIB;
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_METAL;
+ passThru = SLANG_PASS_THROUGH_METAL;
+ break;
+ case RenderApiType::CPU:
+ target = SLANG_SHADER_HOST_CALLABLE;
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_CPP;
+ passThru = SLANG_PASS_THROUGH_GENERIC_C_CPP;
+ break;
+ case RenderApiType::CUDA:
+ target = SLANG_PTX;
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_CUDA;
+ passThru = SLANG_PASS_THROUGH_NVRTC;
+ break;
+ case RenderApiType::WebGPU:
+ target = SLANG_WGSL;
+ nativeLanguage = SLANG_SOURCE_LANGUAGE_WGSL;
+ passThru = SLANG_PASS_THROUGH_TINT;
+ break;
}
SlangSourceLanguage sourceLanguage = nativeLanguage;
@@ -1160,7 +1215,9 @@ static SlangResult _extractRenderTestRequirements(const CommandLine& cmdLine, Te
return SLANG_OK;
}
-static SlangResult _extractSlangCTestRequirements(const CommandLine& cmdLine, TestRequirements* ioRequirements)
+static SlangResult _extractSlangCTestRequirements(
+ const CommandLine& cmdLine,
+ TestRequirements* ioRequirements)
{
// This determines what the requirements are for a slangc like command line
// First check pass through
@@ -1168,7 +1225,8 @@ static SlangResult _extractSlangCTestRequirements(const CommandLine& cmdLine, Te
String passThrough;
if (SLANG_SUCCEEDED(_extractArg(cmdLine, "-pass-through", passThrough)))
{
- ioRequirements->addUsedBackEnd(TypeTextUtil::findPassThrough(passThrough.getUnownedSlice()));
+ ioRequirements->addUsedBackEnd(
+ TypeTextUtil::findPassThrough(passThrough.getUnownedSlice()));
}
}
@@ -1177,15 +1235,17 @@ static SlangResult _extractSlangCTestRequirements(const CommandLine& cmdLine, Te
String targetName;
if (SLANG_SUCCEEDED(_extractArg(cmdLine, "-target", targetName)))
{
- const SlangCompileTarget target = TypeTextUtil::findCompileTargetFromName(targetName.getUnownedSlice());
+ const SlangCompileTarget target =
+ TypeTextUtil::findCompileTargetFromName(targetName.getUnownedSlice());
ioRequirements->addUsedBackends(_getPassThroughFlagsForTarget(target));
}
}
return SLANG_OK;
-
}
-static SlangResult _extractReflectionTestRequirements(const CommandLine& cmdLine, TestRequirements* ioRequirements)
+static SlangResult _extractReflectionTestRequirements(
+ const CommandLine& cmdLine,
+ TestRequirements* ioRequirements)
{
// There are no specialized constraints for a reflection test
return SLANG_OK;
@@ -1234,8 +1294,11 @@ static RenderApiFlags _getAvailableRenderApiFlags(TestContext* context)
continue;
}
- // Check that the session has the generic C/CPP compiler availability - which is all we should need for CPU target
- if (SLANG_SUCCEEDED(spSessionCheckPassThroughSupport(context->getSession(), SLANG_PASS_THROUGH_GENERIC_C_CPP)))
+ // Check that the session has the generic C/CPP compiler availability - which is all
+ // we should need for CPU target
+ if (SLANG_SUCCEEDED(spSessionCheckPassThroughSupport(
+ context->getSession(),
+ SLANG_PASS_THROUGH_GENERIC_C_CPP)))
{
availableRenderApiFlags |= RenderApiFlags(1) << int(apiType);
}
@@ -1252,7 +1315,8 @@ static RenderApiFlags _getAvailableRenderApiFlags(TestContext* context)
}
// Try starting up the device
CommandLine cmdLine;
- cmdLine.setExecutableLocation(ExecutableLocation(context->options.binDir, "render-test"));
+ cmdLine.setExecutableLocation(
+ ExecutableLocation(context->options.binDir, "render-test"));
_addRenderTestOptions(context->options, cmdLine);
// We just want to see if the device can be started up
cmdLine.addArg("-only-startup");
@@ -1263,22 +1327,26 @@ static RenderApiFlags _getAvailableRenderApiFlags(TestContext* context)
cmdLine.addArg(builder);
// Run the render-test tool and see if the device could startup
ExecuteResult exeRes;
- if (SLANG_SUCCEEDED(spawnAndWaitSharedLibrary(context, "device-startup", cmdLine, exeRes))
- && TestToolUtil::getReturnCodeFromInt(exeRes.resultCode) == ToolReturnCode::Success)
+ if (SLANG_SUCCEEDED(
+ spawnAndWaitSharedLibrary(context, "device-startup", cmdLine, exeRes)) &&
+ TestToolUtil::getReturnCodeFromInt(exeRes.resultCode) ==
+ ToolReturnCode::Success)
{
availableRenderApiFlags |= RenderApiFlags(1) << int(apiType);
StdWriters::getOut().print(
- "Check %s: Supported\n", RenderApiUtil::getApiName(apiType).begin());
+ "Check %s: Supported\n",
+ RenderApiUtil::getApiName(apiType).begin());
}
else
{
StdWriters::getOut().print(
- "Check %s: Not Supported\n", RenderApiUtil::getApiName(apiType).begin());
+ "Check %s: Not Supported\n",
+ RenderApiUtil::getApiName(apiType).begin());
const auto out = exeRes.standardOutput;
const auto err = exeRes.standardError;
- if(err.getLength())
+ if (err.getLength())
StdWriters::getOut().print("%s\n", err.getBuffer());
- if(out.getLength())
+ if (out.getLength())
StdWriters::getOut().print("%s\n", out.getBuffer());
}
}
@@ -1296,7 +1364,12 @@ ToolReturnCode getReturnCode(const ExecuteResult& exeRes)
return TestToolUtil::getReturnCodeFromInt(exeRes.resultCode);
}
-ToolReturnCode spawnAndWait(TestContext* context, const String& testPath, SpawnType spawnType, const CommandLine& cmdLine, ExecuteResult& outExeRes)
+ToolReturnCode spawnAndWait(
+ TestContext* context,
+ const String& testPath,
+ SpawnType spawnType,
+ const CommandLine& cmdLine,
+ ExecuteResult& outExeRes)
{
if (context->isCollectingRequirements())
{
@@ -1317,24 +1390,25 @@ ToolReturnCode spawnAndWait(TestContext* context, const String& testPath, SpawnT
SlangResult spawnResult = SLANG_FAIL;
switch (finalSpawnType)
{
- case SpawnType::UseExe:
+ case SpawnType::UseExe:
{
spawnResult = spawnAndWaitExe(context, testPath, cmdLine, outExeRes);
break;
}
- case SpawnType::Default:
- case SpawnType::UseSharedLibrary:
+ case SpawnType::Default:
+ case SpawnType::UseSharedLibrary:
{
spawnResult = spawnAndWaitSharedLibrary(context, testPath, cmdLine, outExeRes);
break;
}
- case SpawnType::UseFullyIsolatedTestServer:
- case SpawnType::UseTestServer:
+ case SpawnType::UseFullyIsolatedTestServer:
+ case SpawnType::UseTestServer:
{
- spawnResult = spawnAndWaitTestServer(context, finalSpawnType, testPath, cmdLine, outExeRes);
+ spawnResult =
+ spawnAndWaitTestServer(context, finalSpawnType, testPath, cmdLine, outExeRes);
break;
}
- default: break;
+ default: break;
}
if (SLANG_FAILED(spawnResult))
@@ -1348,10 +1422,10 @@ ToolReturnCode spawnAndWait(TestContext* context, const String& testPath, SpawnT
String getOutput(const ExecuteResult& exeRes)
{
ExecuteResult::ResultCode resultCode = exeRes.resultCode;
-
+
String standardOuptut = exeRes.standardOutput;
String standardError = exeRes.standardError;
-
+
// We construct a single output string that captures the results
StringBuilder actualOutputBuilder;
actualOutputBuilder.append("result code = ");
@@ -1365,7 +1439,7 @@ String getOutput(const ExecuteResult& exeRes)
return actualOutputBuilder.produceString();
}
-// Finds the specialized or default path for expected data for a test.
+// Finds the specialized or default path for expected data for a test.
// If neither are found, will return an empty string
String findExpectedPath(const TestInput& input, const char* postFix)
{
@@ -1397,8 +1471,12 @@ String findExpectedPath(const TestInput& input, const char* postFix)
return defaultBuf;
}
- // Couldn't find either
- fprintf(stderr, "referenceOutput '%s' or '%s' not found.\n", defaultBuf.getBuffer(), specializedBuf.getBuffer());
+ // Couldn't find either
+ fprintf(
+ stderr,
+ "referenceOutput '%s' or '%s' not found.\n",
+ defaultBuf.getBuffer(),
+ specializedBuf.getBuffer());
return "";
}
@@ -1423,27 +1501,32 @@ static SlangResult _initSlangCompiler(TestContext* context, CommandLine& ioCmdLi
{
if (arg.startsWith(prefix))
{
- // Has NVAPI prefix, meaning
+ // Has NVAPI prefix, meaning
usesNVAPI = true;
break;
}
}
- // This is necessary because the session can be shared, and the prelude overwritten by the renderer.
+ // This is necessary because the session can be shared, and the prelude overwritten by the
+ // renderer.
if (usesNVAPI)
{
// We want to set the path to NVAPI
String rootPath;
SLANG_RETURN_ON_FAIL(TestToolUtil::getRootPath(context->exePath.getBuffer(), rootPath));
String includePath;
- SLANG_RETURN_ON_FAIL(TestToolUtil::getIncludePath(rootPath, "external/nvapi/nvHLSLExtns.h", includePath))
+ SLANG_RETURN_ON_FAIL(
+ TestToolUtil::getIncludePath(rootPath, "external/nvapi/nvHLSLExtns.h", includePath))
StringBuilder buf;
-
+
// Include the NVAPI header
buf << "#include ";
- StringEscapeUtil::appendQuoted(StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp), includePath.getUnownedSlice(), buf);
+ StringEscapeUtil::appendQuoted(
+ StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp),
+ includePath.getUnownedSlice(),
+ buf);
buf << "\n\n";
context->getSession()->setLanguagePrelude(SLANG_SOURCE_LANGUAGE_HLSL, buf.getBuffer());
@@ -1457,22 +1540,25 @@ TestResult asTestResult(ToolReturnCode code)
{
switch (code)
{
- case ToolReturnCode::Success: return TestResult::Pass;
- case ToolReturnCode::Ignored: return TestResult::Ignored;
- default: return TestResult::Fail;
+ case ToolReturnCode::Success: return TestResult::Pass;
+ case ToolReturnCode::Ignored: return TestResult::Ignored;
+ default: return TestResult::Fail;
}
}
-#define TEST_RETURN_ON_DONE(x) \
- { \
- const ToolReturnCode toolRet_ = x; \
+#define TEST_RETURN_ON_DONE(x) \
+ { \
+ const ToolReturnCode toolRet_ = x; \
if (TestToolUtil::isDone(toolRet_)) \
- { \
- return asTestResult(toolRet_); \
- } \
+ { \
+ return asTestResult(toolRet_); \
+ } \
}
-static SlangResult _createArtifactFromHexDump(const UnownedStringSlice& hexDump, const ArtifactDesc& desc, ComPtr<IArtifact>& outArtifact)
+static SlangResult _createArtifactFromHexDump(
+ const UnownedStringSlice& hexDump,
+ const ArtifactDesc& desc,
+ ComPtr<IArtifact>& outArtifact)
{
// We need to extract the binary
List<uint8_t> data;
@@ -1489,7 +1575,13 @@ static SlangResult _createArtifactFromHexDump(const UnownedStringSlice& hexDump,
static SlangResult _executeBinary(const UnownedStringSlice& hexDump, ExecuteResult& outExeRes)
{
ComPtr<IArtifact> artifact;
- SLANG_RETURN_ON_FAIL(_createArtifactFromHexDump(hexDump, ArtifactDesc::make(ArtifactKind::Executable, ArtifactPayload::HostCPU, ArtifactStyle::Unknown), artifact));
+ SLANG_RETURN_ON_FAIL(_createArtifactFromHexDump(
+ hexDump,
+ ArtifactDesc::make(
+ ArtifactKind::Executable,
+ ArtifactPayload::HostCPU,
+ ArtifactStyle::Unknown),
+ artifact));
ComPtr<IOSFileArtifactRepresentation> fileRep;
SLANG_RETURN_ON_FAIL(artifact->requireFile(ArtifactKeep::Yes, fileRep.writeRef()));
@@ -1525,17 +1617,21 @@ static bool _areDiagnosticsEqual(const UnownedStringSlice& a, const UnownedStrin
}
// Parse the compiler diagnostics and make sure they are the same.
- // Ignores line number differences
- return ParseDiagnosticUtil::areEqual(outA.stdError.getUnownedSlice(), outB.stdError.getUnownedSlice(), ParseDiagnosticUtil::EqualityFlag::IgnoreLineNos);
+ // Ignores line number differences
+ return ParseDiagnosticUtil::areEqual(
+ outA.stdError.getUnownedSlice(),
+ outB.stdError.getUnownedSlice(),
+ ParseDiagnosticUtil::EqualityFlag::IgnoreLineNos);
}
-
+
static bool _areResultsEqual(TestOptions::Type type, const String& a, const String& b)
{
switch (type)
{
- case TestOptions::Type::Diagnostic: return _areDiagnosticsEqual(a.getUnownedSlice(), b.getUnownedSlice());
- case TestOptions::Type::Normal: return a == b;
- default:
+ case TestOptions::Type::Diagnostic:
+ return _areDiagnosticsEqual(a.getUnownedSlice(), b.getUnownedSlice());
+ case TestOptions::Type::Normal: return a == b;
+ default:
{
SLANG_ASSERT(!"Unknown test type");
return false;
@@ -1554,11 +1650,12 @@ static String _calcModulePath(const TestInput& input)
TestResult runDocTest(TestContext* context, TestInput& input)
{
- // need to execute the stand-alone Slang compiler on the file, and compare its output to what we expect
+ // need to execute the stand-alone Slang compiler on the file, and compare its output to what we
+ // expect
auto outputStem = input.outputStem;
CommandLine cmdLine;
-
+
cmdLine.addArg(input.filePath);
@@ -1640,7 +1737,8 @@ TestResult runExecutableTest(TestContext* context, TestInput& input)
// Make the module name the same as the current executable path, so it can discover
// the slang-rt library if needed.
String modulePath = Path::combine(
- Path::getParentDirectory(Path::getExecutablePath()), Path::getFileNameWithoutExt(filePath));
+ Path::getParentDirectory(Path::getExecutablePath()),
+ Path::getFileNameWithoutExt(filePath));
// String testRoot
// for(;;)
@@ -1667,7 +1765,8 @@ TestResult runExecutableTest(TestContext* context, TestInput& input)
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
- StringEscapeHandler* escapeHandler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Space);
+ StringEscapeHandler* escapeHandler =
+ StringEscapeUtil::getHandler(StringEscapeUtil::Style::Space);
List<String> args;
args.add(filePath);
@@ -1696,9 +1795,10 @@ TestResult runExecutableTest(TestContext* context, TestInput& input)
ExecuteResult exeRes;
// TODO(Yong) HACK:
- // Just use shared library now, TestServer spawn mode seems to cause slangc to fail to find its own
- // executable path, and thus failed to find the `gfx.slang` file sitting along side `slangc.exe`.
- // We need to figure out what happened to `Path::getExecutablePath()` inside test-server.
+ // Just use shared library now, TestServer spawn mode seems to cause slangc to fail to find its
+ // own executable path, and thus failed to find the `gfx.slang` file sitting along side
+ // `slangc.exe`. We need to figure out what happened to `Path::getExecutablePath()` inside
+ // test-server.
SpawnType slangcSpawnType = input.spawnType;
if (slangcSpawnType == SpawnType::UseTestServer)
slangcSpawnType = SpawnType::UseExe;
@@ -1744,7 +1844,8 @@ TestResult runExecutableTest(TestContext* context, TestInput& input)
// Compare if they are the same
if (!StringUtil::areLinesEqual(
- actualOutput.getUnownedSlice(), expectedOutput.getUnownedSlice()))
+ actualOutput.getUnownedSlice(),
+ expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
@@ -1761,7 +1862,8 @@ TestResult runLanguageServerTest(TestContext* context, TestInput& input)
if (!context->m_languageServerConnection)
{
- if (SLANG_FAILED(context->createLanguageServerJSONRPCConnection(context->m_languageServerConnection)))
+ if (SLANG_FAILED(context->createLanguageServerJSONRPCConnection(
+ context->m_languageServerConnection)))
{
return TestResult::Fail;
}
@@ -1779,7 +1881,9 @@ TestResult runLanguageServerTest(TestContext* context, TestInput& input)
wsFolder.uri = URI::fromLocalFilePath(Path::getParentDirectory(fullPath).getUnownedSlice()).uri;
initParams.workspaceFolders.add(wsFolder);
if (SLANG_FAILED(connection->sendCall(
- LanguageServerProtocol::InitializeParams::methodName, &initParams, JSONValue::makeInt(0))))
+ LanguageServerProtocol::InitializeParams::methodName,
+ &initParams,
+ JSONValue::makeInt(0))))
{
return TestResult::Fail;
}
@@ -1815,23 +1919,23 @@ TestResult runLanguageServerTest(TestContext* context, TestInput& input)
auto waitForNonDiagnosticResponse = [&]() -> SlangResult
{
repeat:
- if (SLANG_FAILED(connection->waitForResult(-1)))
- return SLANG_FAIL;
- if (connection->getMessageType() == JSONRPCMessageType::Call)
- {
- JSONRPCCall call;
- connection->getRPC(&call);
- if (call.method == "textDocument/publishDiagnostics")
+ if (SLANG_FAILED(connection->waitForResult(-1)))
+ return SLANG_FAIL;
+ if (connection->getMessageType() == JSONRPCMessageType::Call)
{
- diagnosticsReceived = true;
- LanguageServerProtocol::PublishDiagnosticsParams arg;
- if (SLANG_FAILED(connection->getMessage(&arg)))
- return SLANG_FAIL;
- diagnostics.add(arg);
- goto repeat;
+ JSONRPCCall call;
+ connection->getRPC(&call);
+ if (call.method == "textDocument/publishDiagnostics")
+ {
+ diagnosticsReceived = true;
+ LanguageServerProtocol::PublishDiagnosticsParams arg;
+ if (SLANG_FAILED(connection->getMessage(&arg)))
+ return SLANG_FAIL;
+ diagnostics.add(arg);
+ goto repeat;
+ }
}
- }
- return SLANG_OK;
+ return SLANG_OK;
};
List<UnownedStringSlice> lines;
@@ -2062,23 +2166,24 @@ TestResult runLanguageServerTest(TestContext* context, TestInput& input)
TestResult runSimpleTest(TestContext* context, TestInput& input)
{
- // need to execute the stand-alone Slang compiler on the file, and compare its output to what we expect
+ // need to execute the stand-alone Slang compiler on the file, and compare its output to what we
+ // expect
auto outputStem = input.outputStem;
CommandLine cmdLine;
-
+
if (input.testOptions->command != "SIMPLE_EX")
{
cmdLine.addArg(input.filePath);
}
- for( auto arg : input.testOptions->args )
+ for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
- // If we can't set up for simple compilation, it's because some external resource isn't available
- // such as NVAPI headers. In that case we just ignore the test.
+ // If we can't set up for simple compilation, it's because some external resource isn't
+ // available such as NVAPI headers. In that case we just ignore the test.
if (SLANG_FAILED(_initSlangCompiler(context, cmdLine)))
{
return TestResult::Ignored;
@@ -2099,7 +2204,8 @@ TestResult runSimpleTest(TestContext* context, TestInput& input)
const Index targetIndex = args.indexOf("-target");
if (targetIndex != Index(-1) && targetIndex + 1 < args.getCount())
{
- target = TypeTextUtil::findCompileTargetFromName(args[targetIndex + 1].getUnownedSlice());
+ target =
+ TypeTextUtil::findCompileTargetFromName(args[targetIndex + 1].getUnownedSlice());
}
}
@@ -2122,12 +2228,13 @@ TestResult runSimpleTest(TestContext* context, TestInput& input)
actualOutput,
false,
"result code = 0\nstandard error = {\n}\nstandard output = {\n}\n",
- [&input](auto e, auto a){return _areResultsEqual(input.testOptions->type, e, a);});
+ [&input](auto e, auto a) { return _areResultsEqual(input.testOptions->type, e, a); });
}
TestResult runSimpleLineTest(TestContext* context, TestInput& input)
{
- // need to execute the stand-alone Slang compiler on the file, and compare its output to what we expect
+ // need to execute the stand-alone Slang compiler on the file, and compare its output to what we
+ // expect
auto outputStem = input.outputStem;
CommandLine cmdLine;
@@ -2150,7 +2257,10 @@ TestResult runSimpleLineTest(TestContext* context, TestInput& input)
// Parse all the diagnostics so we can extract line numbers
auto diagnostics = ArtifactDiagnostics::create();
- if (SLANG_FAILED(ParseDiagnosticUtil::parseDiagnostics(exeRes.standardError.getUnownedSlice(), diagnostics)) || diagnostics->getCount() <= 0)
+ if (SLANG_FAILED(ParseDiagnosticUtil::parseDiagnostics(
+ exeRes.standardError.getUnownedSlice(),
+ diagnostics)) ||
+ diagnostics->getCount() <= 0)
{
// Write out the diagnostics which couldn't be parsed.
@@ -2181,7 +2291,8 @@ TestResult runCompile(TestContext* context, TestInput& input)
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
- StringEscapeHandler* escapeHandler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Space);
+ StringEscapeHandler* escapeHandler =
+ StringEscapeUtil::getHandler(StringEscapeUtil::Style::Space);
for (auto arg : input.testOptions->args)
{
@@ -2231,11 +2342,16 @@ TestResult runSimpleCompareCommandLineTest(TestContext* context, TestInput& inpu
return runSimpleTest(context, workInput);
}
-static SlangResult _parseJSON(const UnownedStringSlice& slice, DiagnosticSink* sink, JSONContainer* container, JSONValue& outValue)
+static SlangResult _parseJSON(
+ const UnownedStringSlice& slice,
+ DiagnosticSink* sink,
+ JSONContainer* container,
+ JSONValue& outValue)
{
SourceManager* sourceManager = sink->getSourceManager();
- SourceFile* sourceFile = sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), slice);
+ SourceFile* sourceFile =
+ sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), slice);
SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc());
JSONLexer lexer;
@@ -2245,7 +2361,7 @@ static SlangResult _parseJSON(const UnownedStringSlice& slice, DiagnosticSink* s
JSONParser parser;
SLANG_RETURN_ON_FAIL(parser.parse(&lexer, sourceView, &builder, sink));
-
+
outValue = builder.getRootValue();
return SLANG_OK;
}
@@ -2259,11 +2375,11 @@ TestResult runReflectionTest(TestContext* context, TestInput& input)
bool isCPUTest = input.testOptions->command.startsWith("CPU_");
CommandLine cmdLine;
-
+
cmdLine.setExecutableLocation(ExecutableLocation(options.binDir, "slang-reflection-test"));
cmdLine.addArg(filePath);
- for( auto arg : input.testOptions->args )
+ for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
@@ -2289,11 +2405,12 @@ TestResult runReflectionTest(TestContext* context, TestInput& input)
// Extrac the stand
ParseDiagnosticUtil::OutputInfo outputInfo;
- if (SLANG_SUCCEEDED(ParseDiagnosticUtil::parseOutputInfo(actualOutput.getUnownedSlice(), outputInfo)))
+ if (SLANG_SUCCEEDED(
+ ParseDiagnosticUtil::parseOutputInfo(actualOutput.getUnownedSlice(), outputInfo)))
{
const auto toolReturnCode = ToolReturnCode(outputInfo.resultCode);
- // The output should be JSON.
+ // The output should be JSON.
// Parse it to check that it is valid json
if (toolReturnCode == ToolReturnCode::Success)
{
@@ -2306,11 +2423,13 @@ TestResult runReflectionTest(TestContext* context, TestInput& input)
sink.init(&sourceManager, nullptr);
JSONValue value;
- if (SLANG_FAILED(_parseJSON(outputInfo.stdOut.getUnownedSlice(), &sink, &container, value)))
+ if (SLANG_FAILED(
+ _parseJSON(outputInfo.stdOut.getUnownedSlice(), &sink, &container, value)))
{
// Unable to parse as JSON
- context->getTestReporter()->messageFormat(TestMessageType::RunError,
+ context->getTestReporter()->messageFormat(
+ TestMessageType::RunError,
"Unable to parse reflection JSON '%s'\n",
input.outputStem.getBuffer());
@@ -2327,7 +2446,7 @@ TestResult runReflectionTest(TestContext* context, TestInput& input)
static String _calcSummary(IArtifactDiagnostics* inDiagnostics)
{
auto diagnostics = cloneInterface(inDiagnostics);
-
+
// We only want to analyze errors for now
diagnostics->removeBySeverity(ArtifactDiagnostic::Severity::Info);
diagnostics->removeBySeverity(ArtifactDiagnostic::Severity::Warning);
@@ -2346,7 +2465,8 @@ static TestResult runCPPCompilerCompile(TestContext* context, TestInput& input)
return TestResult::Ignored;
}
- // need to execute the stand-alone Slang compiler on the file, and compare its output to what we expect
+ // need to execute the stand-alone Slang compiler on the file, and compare its output to what we
+ // expect
auto outputStem = input.outputStem;
@@ -2423,15 +2543,22 @@ static TestResult runCPPCompilerSharedLibrary(TestContext* context, TestInput& i
// Compile this source
ComPtr<IArtifact> sourceArtifact;
- // If set, we store the artifact in memory without a name.
+ // If set, we store the artifact in memory without a name.
bool checkMemory = false;
if (checkMemory)
{
- helper->createArtifact(ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage), "", sourceArtifact.writeRef());
+ helper->createArtifact(
+ ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage),
+ "",
+ sourceArtifact.writeRef());
ComPtr<IOSFileArtifactRepresentation> fileRep;
// Let's just add a blob with the contents
- helper->createOSFileArtifactRepresentation(IOSFileArtifactRepresentation::Kind::Reference, asCharSlice(filePath.getUnownedSlice()), nullptr, fileRep.writeRef());
+ helper->createOSFileArtifactRepresentation(
+ IOSFileArtifactRepresentation::Kind::Reference,
+ asCharSlice(filePath.getUnownedSlice()),
+ nullptr,
+ fileRep.writeRef());
ComPtr<ICastable> castable;
fileRep->createRepresentation(ISlangBlob::getTypeGuid(), castable.writeRef());
@@ -2440,10 +2567,13 @@ static TestResult runCPPCompilerSharedLibrary(TestContext* context, TestInput& i
}
else
{
- helper->createOSFileArtifact(ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage), asCharSlice(filePath.getUnownedSlice()), sourceArtifact.writeRef());
+ helper->createOSFileArtifact(
+ ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage),
+ asCharSlice(filePath.getUnownedSlice()),
+ sourceArtifact.writeRef());
}
- TerminatedCharSlice includePaths[] = { TerminatedCharSlice(".") };
+ TerminatedCharSlice includePaths[] = {TerminatedCharSlice(".")};
options.sourceArtifacts = makeSlice(sourceArtifact.readRef(), 1);
options.includePaths = makeSlice(includePaths, SLANG_COUNT_OF(includePaths));
@@ -2469,12 +2599,14 @@ static TestResult runCPPCompilerSharedLibrary(TestContext* context, TestInput& i
{
// Read the expected
String expectedOutput;
-
+
String expectedOutputPath = outputStem + ".expected";
Slang::File::readAllText(expectedOutputPath, expectedOutput);
-
- // Compare if they are the same
- if (!StringUtil::areLinesEqual(actualOutput.getUnownedSlice(), expectedOutput.getUnownedSlice()))
+
+ // Compare if they are the same
+ if (!StringUtil::areLinesEqual(
+ actualOutput.getUnownedSlice(),
+ expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
@@ -2484,7 +2616,8 @@ static TestResult runCPPCompilerSharedLibrary(TestContext* context, TestInput& i
else
{
SharedLibrary::Handle handle;
- if (SLANG_FAILED(SharedLibrary::loadWithPlatformPath(sharedLibraryPath.getBuffer(), handle)))
+ if (SLANG_FAILED(
+ SharedLibrary::loadWithPlatformPath(sharedLibraryPath.getBuffer(), handle)))
{
return TestResult::Fail;
}
@@ -2495,9 +2628,9 @@ static TestResult runCPPCompilerSharedLibrary(TestContext* context, TestInput& i
char buffer[128] = "";
int value = 0;
- typedef int(*TestFunc)(int intValue, const char* textValue, char* outTextValue);
+ typedef int (*TestFunc)(int intValue, const char* textValue, char* outTextValue);
- // We could capture output if we passed in a ISlangWriter - but for that to work we'd need a
+ // We could capture output if we passed in a ISlangWriter - but for that to work we'd need a
TestFunc testFunc = (TestFunc)SharedLibrary::findSymbolAddressByName(handle, "test");
if (testFunc)
{
@@ -2544,7 +2677,7 @@ static TestResult runCPPCompilerExecute(TestContext* context, TestInput& input)
// Make the module name the same as the source file
String ext = Path::getPathExt(filePath);
String modulePath = _calcModulePath(input);
-
+
// Remove the binary..
String moduleExePath;
{
@@ -2562,12 +2695,15 @@ static TestResult runCPPCompilerExecute(TestContext* context, TestInput& input)
options.sourceLanguage = (ext == "c") ? SLANG_SOURCE_LANGUAGE_C : SLANG_SOURCE_LANGUAGE_CPP;
- TerminatedCharSlice filePaths[] = { SliceUtil::asTerminatedCharSlice(filePath) };
+ TerminatedCharSlice filePaths[] = {SliceUtil::asTerminatedCharSlice(filePath)};
auto helper = DefaultArtifactHelper::getSingleton();
ComPtr<IArtifact> sourceArtifact;
- helper->createOSFileArtifact(ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage), asCharSlice(filePath.getUnownedSlice()), sourceArtifact.writeRef());
+ helper->createOSFileArtifact(
+ ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage),
+ asCharSlice(filePath.getUnownedSlice()),
+ sourceArtifact.writeRef());
// Compile this source
options.sourceArtifacts = makeSlice(sourceArtifact.readRef(), 1);
@@ -2590,7 +2726,7 @@ static TestResult runCPPCompilerExecute(TestContext* context, TestInput& input)
}
else
{
- // Execute the binary and see what we get
+ // Execute the binary and see what we get
CommandLine cmdLine;
ExecutableLocation exe;
@@ -2615,18 +2751,20 @@ static TestResult runCPPCompilerExecute(TestContext* context, TestInput& input)
{
// Read the expected
String expectedOutput;
-
+
String expectedOutputPath = outputStem + ".expected";
Slang::File::readAllText(expectedOutputPath, expectedOutput);
-
- // Compare if they are the same
- if (!StringUtil::areLinesEqual(actualOutput.getUnownedSlice(), expectedOutput.getUnownedSlice()))
+
+ // Compare if they are the same
+ if (!StringUtil::areLinesEqual(
+ actualOutput.getUnownedSlice(),
+ expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
}
}
-
+
return TestResult::Pass;
}
@@ -2634,7 +2772,10 @@ static TestResult runCPPCompilerExecute(TestContext* context, TestInput& input)
// Returns TestResult::Fail if we can't write the expected output debug file
// Otherwise return TestResult::Pass and if we are not just collecting
// requirements, writes the output into the `expectedOutput` parameter
-static TestResult generateExpectedOutput(TestContext* const context, const TestInput& input, String& expectedOutput)
+static TestResult generateExpectedOutput(
+ TestContext* const context,
+ const TestInput& input,
+ String& expectedOutput)
{
auto filePath = input.filePath;
auto outputStem = input.outputStem;
@@ -2648,7 +2789,8 @@ static TestResult generateExpectedOutput(TestContext* const context, const TestI
const Index targetIndex = args.indexOf("-target");
if (targetIndex != Index(-1) && targetIndex + 1 < args.getCount())
{
- const SlangCompileTarget target = TypeTextUtil::findCompileTargetFromName(args[targetIndex + 1].getUnownedSlice());
+ const SlangCompileTarget target =
+ TypeTextUtil::findCompileTargetFromName(args[targetIndex + 1].getUnownedSlice());
// Check the session supports it. If not we ignore it
if (SLANG_FAILED(spSessionCheckCompileTargetSupport(context->getSession(), target)))
@@ -2658,23 +2800,23 @@ static TestResult generateExpectedOutput(TestContext* const context, const TestI
switch (target)
{
- case SLANG_DXIL:
- case SLANG_DXIL_ASM:
+ case SLANG_DXIL:
+ case SLANG_DXIL_ASM:
{
expectedCmdLine.addArg(filePath + ".hlsl");
expectedCmdLine.addArg("-pass-through");
expectedCmdLine.addArg("dxc");
break;
}
- case SLANG_DXBC:
- case SLANG_DXBC_ASM:
+ case SLANG_DXBC:
+ case SLANG_DXBC_ASM:
{
expectedCmdLine.addArg(filePath + ".hlsl");
expectedCmdLine.addArg("-pass-through");
expectedCmdLine.addArg("fxc");
break;
}
- default:
+ default:
{
expectedCmdLine.addArg(filePath + ".glsl");
expectedCmdLine.addArg("-emit-spirv-via-glsl");
@@ -2691,7 +2833,8 @@ static TestResult generateExpectedOutput(TestContext* const context, const TestI
}
ExecuteResult expectedExeRes;
- TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, expectedCmdLine, expectedExeRes));
+ TEST_RETURN_ON_DONE(
+ spawnAndWait(context, outputStem, input.spawnType, expectedCmdLine, expectedExeRes));
if (context->isCollectingRequirements())
{
@@ -2716,7 +2859,10 @@ static TestResult generateExpectedOutput(TestContext* const context, const TestI
// Returns TestResult::Fail if compilation fails
// Otherwise return TestResult::Pass and if we are not just collecting
// requirements, writes the output into the `expectedOutput` parameter
-TestResult generateActualOutput(TestContext* const context, const TestInput& input, String& actualOutput)
+TestResult generateActualOutput(
+ TestContext* const context,
+ const TestInput& input,
+ String& actualOutput)
{
auto filePath = input.filePath;
@@ -2727,13 +2873,14 @@ TestResult generateActualOutput(TestContext* const context, const TestInput& inp
const auto& args = input.testOptions->args;
- for( auto arg : input.testOptions->args )
+ for (auto arg : input.testOptions->args)
{
actualCmdLine.addArg(arg);
}
ExecuteResult actualExeRes;
- TEST_RETURN_ON_DONE(spawnAndWait(context, input.outputStem, input.spawnType, actualCmdLine, actualExeRes));
+ TEST_RETURN_ON_DONE(
+ spawnAndWait(context, input.outputStem, input.spawnType, actualCmdLine, actualExeRes));
// Early out if we're just collecting requirements
if (context->isCollectingRequirements())
@@ -2747,7 +2894,7 @@ TestResult generateActualOutput(TestContext* const context, const TestInput& inp
// to catch situations where, e.g., command-line options parsing
// caused the same error in both the Slang and glslang cases.
//
- if(actualExeRes.resultCode != 0 )
+ if (actualExeRes.resultCode != 0)
{
return TestResult::Fail;
}
@@ -2767,7 +2914,7 @@ TestResult runCrossCompilerTest(TestContext* context, TestInput& input)
const bool isFileCheckTest = input.testOptions->getFileCheckPrefix(fileCheckPrefix);
String actualOutput;
- if(TestResult r = generateActualOutput(context, input, actualOutput); r != TestResult::Pass)
+ if (TestResult r = generateActualOutput(context, input, actualOutput); r != TestResult::Pass)
{
return r;
}
@@ -2775,9 +2922,10 @@ TestResult runCrossCompilerTest(TestContext* context, TestInput& input)
// Only generate the expected output if this is a comparison against some
// known-good glsl/hlsl input
String expectedOutput;
- if(!isFileCheckTest)
+ if (!isFileCheckTest)
{
- if(TestResult r = generateExpectedOutput(context, input, expectedOutput); r != TestResult::Pass)
+ if (TestResult r = generateExpectedOutput(context, input, expectedOutput);
+ r != TestResult::Pass)
{
return r;
}
@@ -2791,7 +2939,7 @@ TestResult runCrossCompilerTest(TestContext* context, TestInput& input)
TestResult result = TestResult::Pass;
- if(isFileCheckTest)
+ if (isFileCheckTest)
{
result = _fileCheckTest(*context, input.filePath, fileCheckPrefix, actualOutput);
// TODO: It might be a good idea to sanity check any expected output
@@ -2802,7 +2950,9 @@ TestResult runCrossCompilerTest(TestContext* context, TestInput& input)
}
else
{
- if (!StringUtil::areLinesEqual(actualOutput.getUnownedSlice(), expectedOutput.getUnownedSlice()))
+ if (!StringUtil::areLinesEqual(
+ actualOutput.getUnownedSlice(),
+ expectedOutput.getUnownedSlice()))
{
result = TestResult::Fail;
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
@@ -2835,7 +2985,7 @@ TestResult generateHLSLBaseline(
cmdLine.addArg(filePath999);
- for( auto arg : input.testOptions->args )
+ for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
@@ -2855,7 +3005,7 @@ TestResult generateHLSLBaseline(
String expectedOutput = getOutput(exeRes);
String expectedOutputPath = outputStem + ".expected";
-
+
if (SLANG_FAILED(Slang::File::writeAllText(expectedOutputPath, expectedOutput)))
{
return TestResult::Fail;
@@ -2864,9 +3014,7 @@ TestResult generateHLSLBaseline(
return TestResult::Pass;
}
-TestResult generateHLSLBaseline(
- TestContext* context,
- TestInput& input)
+TestResult generateHLSLBaseline(TestContext* context, TestInput& input)
{
return generateHLSLBaseline(context, input, "dxbc-assembly", "fxc");
}
@@ -2886,14 +3034,15 @@ static TestResult _runHLSLComparisonTest(
// Generate the expected output using standard HLSL compiler
generateHLSLBaseline(context, input, targetFormat, passThroughName);
- // need to execute the stand-alone Slang compiler on the file, and compare its output to what we expect
+ // need to execute the stand-alone Slang compiler on the file, and compare its output to what we
+ // expect
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
cmdLine.addArg(filePath999);
- for( auto arg : input.testOptions->args )
+ for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
@@ -2917,10 +3066,10 @@ static TestResult _runHLSLComparisonTest(
// wrote to stderr.
ExecuteResult::ResultCode resultCode = exeRes.resultCode;
-
+
String standardOutput = exeRes.standardOutput;
String standardError = exeRes.standardError;
-
+
// We construct a single output string that captures the results
StringBuilder actualOutputBuilder;
actualOutputBuilder.append("result code = ");
@@ -2939,21 +3088,18 @@ static TestResult _runHLSLComparisonTest(
return _validateOutput(context, input, actualOutput, resultCode != 0);
}
-static TestResult runDXBCComparisonTest(
- TestContext* context,
- TestInput& input)
+static TestResult runDXBCComparisonTest(TestContext* context, TestInput& input)
{
return _runHLSLComparisonTest(context, input, "dxbc-assembly", "fxc");
}
-static TestResult runDXILComparisonTest(
- TestContext* context,
- TestInput& input)
+static TestResult runDXILComparisonTest(TestContext* context, TestInput& input)
{
return _runHLSLComparisonTest(context, input, "dxil-assembly", "dxc");
}
-TestResult doGLSLComparisonTestRun(TestContext* context,
+TestResult doGLSLComparisonTestRun(
+ TestContext* context,
TestInput& input,
char const* langDefine,
char const* passThrough,
@@ -2968,13 +3114,13 @@ TestResult doGLSLComparisonTestRun(TestContext* context,
cmdLine.addArg(filePath999);
- if( langDefine )
+ if (langDefine)
{
cmdLine.addArg("-D");
cmdLine.addArg(langDefine);
}
- if( passThrough )
+ if (passThrough)
{
cmdLine.addArg("-pass-through");
cmdLine.addArg(passThrough);
@@ -2983,7 +3129,7 @@ TestResult doGLSLComparisonTestRun(TestContext* context,
cmdLine.addArg("-target");
cmdLine.addArg("spirv-assembly");
- for( auto arg : input.testOptions->args )
+ for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
@@ -3027,8 +3173,15 @@ TestResult runGLSLComparisonTest(TestContext* context, TestInput& input)
String expectedOutput;
String actualOutput;
- TestResult hlslResult = doGLSLComparisonTestRun(context, input, "__GLSL__", "glslang", ".expected", &expectedOutput);
- TestResult slangResult = doGLSLComparisonTestRun(context, input, "__SLANG__", nullptr, ".actual", &actualOutput);
+ TestResult hlslResult = doGLSLComparisonTestRun(
+ context,
+ input,
+ "__GLSL__",
+ "glslang",
+ ".expected",
+ &expectedOutput);
+ TestResult slangResult =
+ doGLSLComparisonTestRun(context, input, "__SLANG__", nullptr, ".actual", &actualOutput);
if (context->isCollectingRequirements())
{
@@ -3036,19 +3189,22 @@ TestResult runGLSLComparisonTest(TestContext* context, TestInput& input)
}
// If either is ignored, the whole test is
- if (hlslResult == TestResult::Ignored ||
- slangResult == TestResult::Ignored)
+ if (hlslResult == TestResult::Ignored || slangResult == TestResult::Ignored)
{
return TestResult::Ignored;
}
Slang::File::writeAllText(outputStem + ".expected", expectedOutput);
- Slang::File::writeAllText(outputStem + ".actual", actualOutput);
+ Slang::File::writeAllText(outputStem + ".actual", actualOutput);
- if( hlslResult == TestResult::Fail ) return TestResult::Fail;
- if( slangResult == TestResult::Fail ) return TestResult::Fail;
+ if (hlslResult == TestResult::Fail)
+ return TestResult::Fail;
+ if (slangResult == TestResult::Fail)
+ return TestResult::Fail;
- if (!StringUtil::areLinesEqual(actualOutput.getUnownedSlice(), expectedOutput.getUnownedSlice()))
+ if (!StringUtil::areLinesEqual(
+ actualOutput.getUnownedSlice(),
+ expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
@@ -3099,7 +3255,7 @@ TestResult runPerformanceProfile(TestContext* context, TestInput& input)
CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(context->options.binDir, "render-test"));
-
+
cmdLine.addArg(input.filePath);
cmdLine.addArg("-performance-profile");
@@ -3138,7 +3294,7 @@ static double _textToDouble(const UnownedStringSlice& slice)
const Index maxSize = 80;
char buffer[maxSize + 1];
- size = (size > maxSize) ? maxSize : size;
+ size = (size > maxSize) ? maxSize : size;
memcpy(buffer, slice.begin(), size);
buffer[size] = 0;
@@ -3164,7 +3320,10 @@ static void _calcLines(const UnownedStringSlice& slice, List<UnownedStringSlice>
}
}
-static SlangResult _compareWithType(const UnownedStringSlice& actual, const UnownedStringSlice& ref, double differenceThreshold = 0.0001)
+static SlangResult _compareWithType(
+ const UnownedStringSlice& actual,
+ const UnownedStringSlice& ref,
+ double differenceThreshold = 0.0001)
{
typedef slang::TypeReflection::ScalarType ScalarType;
@@ -3214,7 +3373,7 @@ static SlangResult _compareWithType(const UnownedStringSlice& actual, const Unow
switch (scalarType)
{
- default:
+ default:
{
if (lineActual.trim() != lineRef.trim())
{
@@ -3222,11 +3381,11 @@ static SlangResult _compareWithType(const UnownedStringSlice& actual, const Unow
}
break;
}
- case ScalarType::Float16:
- case ScalarType::Float32:
- case ScalarType::Float64:
+ case ScalarType::Float16:
+ case ScalarType::Float32:
+ case ScalarType::Float64:
{
-
+
// Compare as double
double valueA = _textToDouble(lineActual);
double valueB = _textToDouble(lineRef);
@@ -3243,23 +3402,28 @@ static SlangResult _compareWithType(const UnownedStringSlice& actual, const Unow
return SLANG_OK;
}
-TestResult runComputeComparisonImpl(TestContext* context, TestInput& input, const char *const* langOpts, size_t numLangOpts)
+TestResult runComputeComparisonImpl(
+ TestContext* context,
+ TestInput& input,
+ const char* const* langOpts,
+ size_t numLangOpts)
{
- // TODO: delete any existing files at the output path(s) to avoid stale outputs leading to a false pass
- auto filePath999 = input.filePath;
- auto outputStem = input.outputStem;
+ // TODO: delete any existing files at the output path(s) to avoid stale outputs leading to a
+ // false pass
+ auto filePath999 = input.filePath;
+ auto outputStem = input.outputStem;
- CommandLine cmdLine;
+ CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(context->options.binDir, "render-test"));
cmdLine.addArg(filePath999);
_addRenderTestOptions(context->options, cmdLine);
- for (auto arg : input.testOptions->args)
- {
+ for (auto arg : input.testOptions->args)
+ {
cmdLine.addArg(arg);
- }
+ }
for (int i = 0; i < int(numLangOpts); ++i)
{
@@ -3271,12 +3435,13 @@ TestResult runComputeComparisonImpl(TestContext* context, TestInput& input, cons
if (context->isExecuting())
{
- // clear the stale actual output file first. This will allow us to detect error if render-test fails and outputs nothing.
+ // clear the stale actual output file first. This will allow us to detect error if
+ // render-test fails and outputs nothing.
File::writeAllText(actualOutputFile, "");
}
ExecuteResult exeRes;
- TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
+ TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
@@ -3291,8 +3456,8 @@ TestResult runComputeComparisonImpl(TestContext* context, TestInput& input, cons
actualOutput,
false,
"result code = 0\nstandard error = {\n}\nstandard output = {\n}\n");
-
- // check against reference output
+
+ // check against reference output
String actualOutputContent;
if (SLANG_FAILED(File::readAllText(actualOutputFile, actualOutputContent)))
{
@@ -3300,50 +3465,58 @@ TestResult runComputeComparisonImpl(TestContext* context, TestInput& input, cons
TestMessageType::RunError,
"Unable to read render-test output: %s\n",
actualOutput.getBuffer());
- return TestResult::Fail;
+ return TestResult::Fail;
}
String fileCheckPrefix;
- auto bufferResult = input.testOptions->getFileCheckBufferPrefix(fileCheckPrefix)
- ? _fileCheckTest(*context, input.filePath, fileCheckPrefix, actualOutputContent)
- : _fileComparisonTest(
- *context,
- input,
- nullptr,
- ".expected.txt",
- actualOutputContent,
- [](const auto& a, const auto& e){
- return SLANG_SUCCEEDED(_compareWithType(a.getUnownedSlice(), e.getUnownedSlice()));
- });
+ auto bufferResult =
+ input.testOptions->getFileCheckBufferPrefix(fileCheckPrefix)
+ ? _fileCheckTest(*context, input.filePath, fileCheckPrefix, actualOutputContent)
+ : _fileComparisonTest(
+ *context,
+ input,
+ nullptr,
+ ".expected.txt",
+ actualOutputContent,
+ [](const auto& a, const auto& e) {
+ return SLANG_SUCCEEDED(
+ _compareWithType(a.getUnownedSlice(), e.getUnownedSlice()));
+ });
return std::max(compileResult, bufferResult);
}
TestResult runSlangComputeComparisonTest(TestContext* context, TestInput& input)
{
- const char* langOpts[] = { "-slang", "-compute" };
- return runComputeComparisonImpl(context, input, langOpts, SLANG_COUNT_OF(langOpts));
+ const char* langOpts[] = {"-slang", "-compute"};
+ return runComputeComparisonImpl(context, input, langOpts, SLANG_COUNT_OF(langOpts));
}
TestResult runSlangComputeComparisonTestEx(TestContext* context, TestInput& input)
{
- return runComputeComparisonImpl(context, input, nullptr, 0);
+ return runComputeComparisonImpl(context, input, nullptr, 0);
}
TestResult runHLSLComputeTest(TestContext* context, TestInput& input)
{
- const char* langOpts[] = { "--hlsl-rewrite", "-compute" };
+ const char* langOpts[] = {"--hlsl-rewrite", "-compute"};
return runComputeComparisonImpl(context, input, langOpts, SLANG_COUNT_OF(langOpts));
}
TestResult runSlangRenderComputeComparisonTest(TestContext* context, TestInput& input)
{
- const char* langOpts[] = { "-slang", "-gcompute" };
+ const char* langOpts[] = {"-slang", "-gcompute"};
return runComputeComparisonImpl(context, input, langOpts, SLANG_COUNT_OF(langOpts));
}
-TestResult doRenderComparisonTestRun(TestContext* context, TestInput& input, char const* langOption, char const* outputKind, String* outOutput)
+TestResult doRenderComparisonTestRun(
+ TestContext* context,
+ TestInput& input,
+ char const* langOption,
+ char const* outputKind,
+ String* outOutput)
{
- // TODO: delete any existing files at the output path(s) to avoid stale outputs leading to a false pass
+ // TODO: delete any existing files at the output path(s) to avoid stale outputs leading to a
+ // false pass
auto filePath = input.filePath;
auto outputStem = input.outputStem;
@@ -3355,7 +3528,7 @@ TestResult doRenderComparisonTestRun(TestContext* context, TestInput& input, cha
_addRenderTestOptions(context->options, cmdLine);
- for( auto arg : input.testOptions->args )
+ for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
@@ -3376,7 +3549,7 @@ TestResult doRenderComparisonTestRun(TestContext* context, TestInput& input, cha
String standardOutput = exeRes.standardOutput;
String standardError = exeRes.standardError;
-
+
// We construct a single output string that captures the results
StringBuilder outputBuilder;
outputBuilder.append("result code = ");
@@ -3400,23 +3573,23 @@ class STBImage
public:
typedef STBImage ThisType;
- /// Reset back to default initialized state (frees any image set)
+ /// Reset back to default initialized state (frees any image set)
void reset();
- /// True if rhs has same size and amount of channels
+ /// True if rhs has same size and amount of channels
bool isComparable(const ThisType& rhs) const;
- /// The width in pixels
+ /// The width in pixels
int getWidth() const { return m_width; }
- /// The height in pixels
+ /// The height in pixels
int getHeight() const { return m_height; }
- /// The number of channels (typically held as bytes in order)
+ /// The number of channels (typically held as bytes in order)
int getNumChannels() const { return m_numChannels; }
- /// Get the contained pixels, nullptr if nothing loaded
+ /// Get the contained pixels, nullptr if nothing loaded
const unsigned char* getPixels() const { return m_pixels; }
unsigned char* getPixels() { return m_pixels; }
- /// Read an image with filename. SLANG_OK on success
+ /// Read an image with filename. SLANG_OK on success
SlangResult read(const char* filename);
~STBImage() { reset(); }
@@ -3453,8 +3626,8 @@ SlangResult STBImage::read(const char* filename)
bool STBImage::isComparable(const ThisType& rhs) const
{
- return (this == &rhs) ||
- (m_width == rhs.m_width && m_height == rhs.m_height && m_numChannels == rhs.m_numChannels);
+ return (this == &rhs) || (m_width == rhs.m_width && m_height == rhs.m_height &&
+ m_numChannels == rhs.m_numChannels);
}
@@ -3474,20 +3647,30 @@ TestResult doImageComparison(TestContext* context, String const& filePath)
STBImage expectedImage;
if (SLANG_FAILED(expectedImage.read(expectedPath.getBuffer())))
{
- reporter->messageFormat(TestMessageType::RunError, "Unable to load image ;%s'", expectedPath.getBuffer());
+ reporter->messageFormat(
+ TestMessageType::RunError,
+ "Unable to load image ;%s'",
+ expectedPath.getBuffer());
return TestResult::Fail;
}
STBImage actualImage;
if (SLANG_FAILED(actualImage.read(actualPath.getBuffer())))
{
- reporter->messageFormat(TestMessageType::RunError, "Unable to load image ;%s'", actualPath.getBuffer());
+ reporter->messageFormat(
+ TestMessageType::RunError,
+ "Unable to load image ;%s'",
+ actualPath.getBuffer());
return TestResult::Fail;
}
if (!expectedImage.isComparable(actualImage))
{
- reporter->messageFormat(TestMessageType::TestFailure, "Images are different sizes '%s' '%s'", actualPath.getBuffer(), expectedPath.getBuffer());
+ reporter->messageFormat(
+ TestMessageType::TestFailure,
+ "Images are different sizes '%s' '%s'",
+ actualPath.getBuffer(),
+ expectedPath.getBuffer());
return TestResult::Fail;
}
@@ -3508,7 +3691,8 @@ TestResult doImageComparison(TestContext* context, String const& filePath)
int actualVal = actualPixels[i];
int absoluteDiff = actualVal - expectedVal;
- if (absoluteDiff < 0) absoluteDiff = -absoluteDiff;
+ if (absoluteDiff < 0)
+ absoluteDiff = -absoluteDiff;
if (absoluteDiff < kAbsoluteDiffCutoff)
{
@@ -3519,7 +3703,8 @@ TestResult doImageComparison(TestContext* context, String const& filePath)
float relativeDiff = 0.0f;
if (expectedVal != 0)
{
- relativeDiff = fabsf(float(actualVal) - float(expectedVal)) / float(expectedVal);
+ relativeDiff =
+ fabsf(float(actualVal) - float(expectedVal)) / float(expectedVal);
if (relativeDiff < kRelativeDiffCutoff)
{
@@ -3535,8 +3720,13 @@ TestResult doImageComparison(TestContext* context, String const& filePath)
const int x = i / numChannels;
const int channelIndex = i % numChannels;
- reporter->messageFormat(TestMessageType::TestFailure, "image compare failure at (%d,%d) channel %d. expected %d got %d (absolute error: %d, relative error: %f)\n",
- x, y, channelIndex,
+ reporter->messageFormat(
+ TestMessageType::TestFailure,
+ "image compare failure at (%d,%d) channel %d. expected %d got %d (absolute "
+ "error: %d, relative error: %f)\n",
+ x,
+ y,
+ channelIndex,
expectedVal,
actualVal,
absoluteDiff,
@@ -3547,7 +3737,7 @@ TestResult doImageComparison(TestContext* context, String const& filePath)
}
expectedPixels += rowSize;
- actualPixels += rowSize;
+ actualPixels += rowSize;
}
}
@@ -3561,7 +3751,7 @@ TestResult runHLSLRenderComparisonTestImpl(
char const* actualArg)
{
String _fileCheckPrefix;
- if(input.testOptions->getFileCheckPrefix(_fileCheckPrefix))
+ if (input.testOptions->getFileCheckPrefix(_fileCheckPrefix))
{
context->getTestReporter()->message(
TestMessageType::RunError,
@@ -3575,12 +3765,14 @@ TestResult runHLSLRenderComparisonTestImpl(
String expectedOutput;
String actualOutput;
- TestResult hlslResult = doRenderComparisonTestRun(context, input, expectedArg, ".expected", &expectedOutput);
+ TestResult hlslResult =
+ doRenderComparisonTestRun(context, input, expectedArg, ".expected", &expectedOutput);
if (hlslResult != TestResult::Pass)
{
return hlslResult;
}
- TestResult slangResult = doRenderComparisonTestRun(context, input, actualArg, ".actual", &actualOutput);
+ TestResult slangResult =
+ doRenderComparisonTestRun(context, input, actualArg, ".actual", &actualOutput);
if (slangResult != TestResult::Pass)
{
return slangResult;
@@ -3592,12 +3784,16 @@ TestResult runHLSLRenderComparisonTestImpl(
}
Slang::File::writeAllText(outputStem + ".expected", expectedOutput);
- Slang::File::writeAllText(outputStem + ".actual", actualOutput);
+ Slang::File::writeAllText(outputStem + ".actual", actualOutput);
- if( hlslResult == TestResult::Fail ) return TestResult::Fail;
- if( slangResult == TestResult::Fail ) return TestResult::Fail;
+ if (hlslResult == TestResult::Fail)
+ return TestResult::Fail;
+ if (slangResult == TestResult::Fail)
+ return TestResult::Fail;
- if (!StringUtil::areLinesEqual(actualOutput.getUnownedSlice(), expectedOutput.getUnownedSlice()))
+ if (!StringUtil::areLinesEqual(
+ actualOutput.getUnownedSlice(),
+ expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
@@ -3607,7 +3803,7 @@ TestResult runHLSLRenderComparisonTestImpl(
// Next do an image comparison on the expected output images!
TestResult imageCompareResult = doImageComparison(context, outputStem);
- if(imageCompareResult != TestResult::Pass)
+ if (imageCompareResult != TestResult::Pass)
return imageCompareResult;
return TestResult::Pass;
@@ -3636,39 +3832,37 @@ TestResult skipTest(TestContext* /* context */, TestInput& /*input*/)
// based on command name, dispatch to an appropriate callback
struct TestCommandInfo
{
- char const* name;
- TestCallback callback;
- RenderApiFlags requiredRenderApiFlags; ///< An RenderApi types that are needed to run the tests
+ char const* name;
+ TestCallback callback;
+ RenderApiFlags requiredRenderApiFlags; ///< An RenderApi types that are needed to run the tests
};
-static const TestCommandInfo s_testCommandInfos[] =
-{
- { "SIMPLE", &runSimpleTest, 0 },
- { "SIMPLE_EX", &runSimpleTest, 0 },
- { "SIMPLE_LINE", &runSimpleLineTest, 0 },
- { "REFLECTION", &runReflectionTest, 0 },
- { "CPU_REFLECTION", &runReflectionTest, 0 },
- { "COMMAND_LINE_SIMPLE", &runSimpleCompareCommandLineTest, 0 },
- { "COMPARE_HLSL", &runDXBCComparisonTest, 0 },
- { "COMPARE_DXIL", &runDXILComparisonTest, 0 },
- { "COMPARE_HLSL_RENDER", &runHLSLRenderComparisonTest, 0 },
- { "COMPARE_HLSL_CROSS_COMPILE_RENDER", &runHLSLCrossCompileRenderComparisonTest, 0 },
- { "COMPARE_HLSL_GLSL_RENDER", &runHLSLAndGLSLRenderComparisonTest, 0 },
- { "COMPARE_COMPUTE", &runSlangComputeComparisonTest, 0 },
- { "COMPARE_COMPUTE_EX", &runSlangComputeComparisonTestEx, 0 },
- { "HLSL_COMPUTE", &runHLSLComputeTest, 0 },
- { "COMPARE_RENDER_COMPUTE", &runSlangRenderComputeComparisonTest, 0 },
- { "COMPARE_GLSL", &runGLSLComparisonTest, 0 },
- { "CROSS_COMPILE", &runCrossCompilerTest, 0 },
- { "CPP_COMPILER_EXECUTE", &runCPPCompilerExecute, RenderApiFlag::CPU},
- { "CPP_COMPILER_SHARED_LIBRARY", &runCPPCompilerSharedLibrary, RenderApiFlag::CPU},
- { "CPP_COMPILER_COMPILE", &runCPPCompilerCompile, RenderApiFlag::CPU},
- { "PERFORMANCE_PROFILE", &runPerformanceProfile, 0 },
- { "COMPILE", &runCompile, 0 },
- { "DOC", &runDocTest, 0 },
- { "LANG_SERVER", &runLanguageServerTest, 0},
- { "EXECUTABLE", &runExecutableTest, RenderApiFlag::CPU}
-};
+static const TestCommandInfo s_testCommandInfos[] = {
+ {"SIMPLE", &runSimpleTest, 0},
+ {"SIMPLE_EX", &runSimpleTest, 0},
+ {"SIMPLE_LINE", &runSimpleLineTest, 0},
+ {"REFLECTION", &runReflectionTest, 0},
+ {"CPU_REFLECTION", &runReflectionTest, 0},
+ {"COMMAND_LINE_SIMPLE", &runSimpleCompareCommandLineTest, 0},
+ {"COMPARE_HLSL", &runDXBCComparisonTest, 0},
+ {"COMPARE_DXIL", &runDXILComparisonTest, 0},
+ {"COMPARE_HLSL_RENDER", &runHLSLRenderComparisonTest, 0},
+ {"COMPARE_HLSL_CROSS_COMPILE_RENDER", &runHLSLCrossCompileRenderComparisonTest, 0},
+ {"COMPARE_HLSL_GLSL_RENDER", &runHLSLAndGLSLRenderComparisonTest, 0},
+ {"COMPARE_COMPUTE", &runSlangComputeComparisonTest, 0},
+ {"COMPARE_COMPUTE_EX", &runSlangComputeComparisonTestEx, 0},
+ {"HLSL_COMPUTE", &runHLSLComputeTest, 0},
+ {"COMPARE_RENDER_COMPUTE", &runSlangRenderComputeComparisonTest, 0},
+ {"COMPARE_GLSL", &runGLSLComparisonTest, 0},
+ {"CROSS_COMPILE", &runCrossCompilerTest, 0},
+ {"CPP_COMPILER_EXECUTE", &runCPPCompilerExecute, RenderApiFlag::CPU},
+ {"CPP_COMPILER_SHARED_LIBRARY", &runCPPCompilerSharedLibrary, RenderApiFlag::CPU},
+ {"CPP_COMPILER_COMPILE", &runCPPCompilerCompile, RenderApiFlag::CPU},
+ {"PERFORMANCE_PROFILE", &runPerformanceProfile, 0},
+ {"COMPILE", &runCompile, 0},
+ {"DOC", &runDocTest, 0},
+ {"LANG_SERVER", &runLanguageServerTest, 0},
+ {"EXECUTABLE", &runExecutableTest, RenderApiFlag::CPU}};
const TestCommandInfo* _findTestCommandInfoByCommand(const UnownedStringSlice& name)
{
@@ -3689,11 +3883,11 @@ static RenderApiFlags _getRequiredRenderApisByCommand(const UnownedStringSlice&
}
TestResult runTest(
- TestContext* context,
- String const& filePath,
- String const& outputStem,
- String const& testName,
- TestOptions const& testOptions)
+ TestContext* context,
+ String const& filePath,
+ String const& outputStem,
+ String const& testName,
+ TestOptions const& testOptions)
{
// If we are collecting requirements and it's diagnostic test, we always run
// (ie no requirements need to be captured - effectively it has 'no requirements')
@@ -3719,14 +3913,12 @@ TestResult runTest(
return TestResult::Fail;
}
-bool testCategoryMatches(
- TestCategory* sub,
- TestCategory* sup)
+bool testCategoryMatches(TestCategory* sub, TestCategory* sup)
{
auto ss = sub;
- while(ss)
+ while (ss)
{
- if(ss == sup)
+ if (ss == sup)
return true;
ss = ss->parent;
@@ -3735,32 +3927,30 @@ bool testCategoryMatches(
}
bool testCategoryMatches(
- TestCategory* categoryToMatch,
+ TestCategory* categoryToMatch,
const Dictionary<TestCategory*, TestCategory*>& categorySet)
{
- for( const auto& [_, category] : categorySet )
+ for (const auto& [_, category] : categorySet)
{
- if(testCategoryMatches(categoryToMatch, category))
+ if (testCategoryMatches(categoryToMatch, category))
return true;
}
return false;
}
-bool testPassesCategoryMask(
- TestContext* context,
- TestOptions const& test)
+bool testPassesCategoryMask(TestContext* context, TestOptions const& test)
{
// Don't include a test we should filter out
- for( auto testCategory : test.categories )
+ for (auto testCategory : test.categories)
{
- if(testCategoryMatches(testCategory, context->options.excludeCategories))
+ if (testCategoryMatches(testCategory, context->options.excludeCategories))
return false;
}
// Otherwise include any test the user asked for
- for( auto testCategory : test.categories )
+ for (auto testCategory : test.categories)
{
- if(testCategoryMatches(testCategory, context->options.includeCategories))
+ if (testCategoryMatches(testCategory, context->options.includeCategories))
return true;
}
@@ -3768,10 +3958,14 @@ bool testPassesCategoryMask(
return false;
}
-static void _calcSynthesizedTests(TestContext* context, RenderApiType synthRenderApiType, const List<TestDetails>& srcTests, List<TestDetails>& ioSynthTests)
+static void _calcSynthesizedTests(
+ TestContext* context,
+ RenderApiType synthRenderApiType,
+ const List<TestDetails>& srcTests,
+ List<TestDetails>& ioSynthTests)
{
// Add the explicit parameter
- for (const auto& srcTest: srcTests)
+ for (const auto& srcTest : srcTests)
{
const auto& requirements = srcTest.requirements;
@@ -3793,19 +3987,20 @@ static void _calcSynthesizedTests(TestContext* context, RenderApiType synthRende
{
//
const auto& language = srcTest.options.args[index + 1];
- SlangSourceLanguage sourceLanguage = TypeTextUtil::findSourceLanguage(language.getUnownedSlice());
+ SlangSourceLanguage sourceLanguage =
+ TypeTextUtil::findSourceLanguage(language.getUnownedSlice());
bool isCrossCompile = true;
switch (sourceLanguage)
{
- case SLANG_SOURCE_LANGUAGE_GLSL:
- case SLANG_SOURCE_LANGUAGE_C:
- case SLANG_SOURCE_LANGUAGE_CPP:
+ case SLANG_SOURCE_LANGUAGE_GLSL:
+ case SLANG_SOURCE_LANGUAGE_C:
+ case SLANG_SOURCE_LANGUAGE_CPP:
{
isCrossCompile = false;
}
- default: break;
+ default: break;
}
if (!isCrossCompile)
@@ -3816,9 +4011,9 @@ static void _calcSynthesizedTests(TestContext* context, RenderApiType synthRende
}
else
{
- // TODO(JS): Arguably we should synthesize from explicit tests. In principal we can remove the explicit api apply another
- // although that may not always work.
- // If it doesn't use any render API or only uses CPU, we don't synthesize
+ // TODO(JS): Arguably we should synthesize from explicit tests. In principal we can
+ // remove the explicit api apply another although that may not always work. If it
+ // doesn't use any render API or only uses CPU, we don't synthesize
if (requirements.usedRenderApiFlags == 0 ||
requirements.usedRenderApiFlags == RenderApiFlag::CPU ||
requirements.explicitRenderApi != RenderApiType::Unknown)
@@ -3831,7 +4026,7 @@ static void _calcSynthesizedTests(TestContext* context, RenderApiType synthRende
TestOptions& synthOptions = synthTestDetails.options;
// If there's a category associated with this render api, add it to the synthesized test
- if(auto c = context->categorySet.find(RenderApiUtil::getApiName(synthRenderApiType)))
+ if (auto c = context->categorySet.find(RenderApiUtil::getApiName(synthRenderApiType)))
{
synthOptions.categories.add(c);
}
@@ -3864,7 +4059,7 @@ static void _calcSynthesizedTests(TestContext* context, RenderApiType synthRende
}
// Work out the info about this tests
- context->setTestRequirements(& synthTestDetails.requirements);
+ context->setTestRequirements(&synthTestDetails.requirements);
runTest(context, "", "", "", synthOptions);
context->setTestRequirements(nullptr);
@@ -3884,14 +4079,16 @@ static bool _canIgnore(TestContext* context, const TestDetails& details)
const auto& requirements = details.requirements;
- // Check if it's possible in principal to run this test with the render api flags used by this test
+ // Check if it's possible in principal to run this test with the render api flags used by this
+ // test
if (!context->canRunTestWithRenderApiFlags(requirements.usedRenderApiFlags))
{
return true;
}
// Are all the required backends available?
- if (((requirements.usedBackendFlags & context->availableBackendFlags) != requirements.usedBackendFlags))
+ if (((requirements.usedBackendFlags & context->availableBackendFlags) !=
+ requirements.usedBackendFlags))
{
return true;
}
@@ -3903,10 +4100,12 @@ static bool _canIgnore(TestContext* context, const TestDetails& details)
}
// Work out what render api flags are actually available, lazily
- const RenderApiFlags availableRenderApiFlags = requirements.usedRenderApiFlags ? _getAvailableRenderApiFlags(context) : 0;
+ const RenderApiFlags availableRenderApiFlags =
+ requirements.usedRenderApiFlags ? _getAvailableRenderApiFlags(context) : 0;
// Are all the required rendering apis available?
- if ((requirements.usedRenderApiFlags & availableRenderApiFlags) != requirements.usedRenderApiFlags)
+ if ((requirements.usedRenderApiFlags & availableRenderApiFlags) !=
+ requirements.usedRenderApiFlags)
{
return true;
}
@@ -3914,13 +4113,11 @@ static bool _canIgnore(TestContext* context, const TestDetails& details)
return false;
}
-static SlangResult _runTestsOnFile(
- TestContext* context,
- String filePath)
+static SlangResult _runTestsOnFile(TestContext* context, String filePath)
{
// Gather a list of tests to run
FileTestList testList;
-
+
SLANG_RETURN_ON_FAIL(_gatherTestsForFile(&context->categorySet, filePath, &testList));
if (testList.tests.getCount() == 0)
@@ -3930,7 +4127,7 @@ static SlangResult _runTestsOnFile(
}
// Note cases where a test file exists, but we found nothing to run
- if( testList.tests.getCount() == 0 )
+ if (testList.tests.getCount() == 0)
{
context->getTestReporter()->addTest(filePath, TestResult::Ignored);
return SLANG_OK;
@@ -3949,16 +4146,19 @@ static SlangResult _runTestsOnFile(
context->setTestRequirements(&requirements);
runTest(context, filePath, filePath, filePath, testDetails.options);
- //
+ //
apiUsedFlags |= requirements.usedRenderApiFlags;
- explictUsedApiFlags |= (requirements.explicitRenderApi != RenderApiType::Unknown) ? (RenderApiFlags(1) << int(requirements.explicitRenderApi)) : 0;
+ explictUsedApiFlags |= (requirements.explicitRenderApi != RenderApiType::Unknown)
+ ? (RenderApiFlags(1) << int(requirements.explicitRenderApi))
+ : 0;
}
context->setTestRequirements(nullptr);
}
SLANG_ASSERT((apiUsedFlags & explictUsedApiFlags) == explictUsedApiFlags);
- const RenderApiFlags availableRenderApiFlags = apiUsedFlags ? _getAvailableRenderApiFlags(context) : 0;
+ const RenderApiFlags availableRenderApiFlags =
+ apiUsedFlags ? _getAvailableRenderApiFlags(context) : 0;
// If synthesized tests are wanted look into adding them
if (context->options.synthesizedTestApis && availableRenderApiFlags)
@@ -3966,9 +4166,10 @@ static SlangResult _runTestsOnFile(
List<TestDetails> synthesizedTests;
// What render options do we want to synthesize
- RenderApiFlags missingApis = (~apiUsedFlags) & (context->options.synthesizedTestApis & availableRenderApiFlags);
+ RenderApiFlags missingApis =
+ (~apiUsedFlags) & (context->options.synthesizedTestApis & availableRenderApiFlags);
- //const Index numInitialTests = testList.tests.getCount();
+ // const Index numInitialTests = testList.tests.getCount();
while (missingApis)
{
@@ -3978,7 +4179,7 @@ static SlangResult _runTestsOnFile(
const RenderApiType synthRenderApiType = RenderApiType(index);
_calcSynthesizedTests(context, synthRenderApiType, testList.tests, synthesizedTests);
-
+
// Disable the bit
missingApis &= ~(RenderApiFlags(1) << index);
}
@@ -3989,12 +4190,12 @@ static SlangResult _runTestsOnFile(
// We have found a test to run!
int subTestCount = 0;
- for( auto& testDetails : testList.tests )
+ for (auto& testDetails : testList.tests)
{
int subTestIndex = subTestCount++;
// Check that the test passes our current category mask
- if(!testPassesCategoryMask(context, testDetails.options))
+ if (!testPassesCategoryMask(context, testDetails.options))
{
continue;
}
@@ -4056,8 +4257,8 @@ static SlangResult _runTestsOnFile(
else
{
testResult = runTest(context, filePath, outputStem, testName, testDetails.options);
- if (testResult == TestResult::Fail
- && !context->getTestReporter()->m_expectedFailureList.contains(testName))
+ if (testResult == TestResult::Fail &&
+ !context->getTestReporter()->m_expectedFailureList.contains(testName))
{
RefPtr<FileTestInfoImpl> fileTestInfo = new FileTestInfoImpl();
fileTestInfo->filePath = filePath;
@@ -4076,16 +4277,14 @@ static SlangResult _runTestsOnFile(
// Could determine if to continue or not here... based on result
- }
+ }
}
return SLANG_OK;
}
-static bool endsWithAllowedExtension(
- TestContext* /*context*/,
- String filePath)
+static bool endsWithAllowedExtension(TestContext* /*context*/, String filePath)
{
char const* allowedExtensions[] = {
".slang",
@@ -4106,33 +4305,31 @@ static bool endsWithAllowedExtension(
".c",
".cpp",
".cu",
- };
+ };
- for( auto allowedExtension : allowedExtensions)
+ for (auto allowedExtension : allowedExtensions)
{
- if(filePath.endsWith(allowedExtension))
+ if (filePath.endsWith(allowedExtension))
return true;
}
return false;
}
-static bool shouldRunTest(
- TestContext* context,
- String filePath)
+static bool shouldRunTest(TestContext* context, String filePath)
{
- if(!endsWithAllowedExtension(context, filePath))
+ if (!endsWithAllowedExtension(context, filePath))
return false;
- if(!context->options.testPrefixes.getCount())
+ if (!context->options.testPrefixes.getCount())
{
return true;
}
// If we have prefixes, it has to match one of them
- for(auto& p : context->options.testPrefixes)
+ for (auto& p : context->options.testPrefixes)
{
- if(filePath.startsWith(p))
+ if (filePath.startsWith(p))
{
return true;
}
@@ -4193,9 +4390,7 @@ void runTestsInParallel(TestContext* context, int count, const F& f)
context->setTestReporter(originalReporter);
}
-void runTestsInDirectory(
- TestContext* context,
- String directoryPath)
+void runTestsInDirectory(TestContext* context, String directoryPath)
{
List<String> files;
getFilesInDirectory(directoryPath, files);
@@ -4209,7 +4404,8 @@ void runTestsInDirectory(
{
TestReporter::TestScope scope(context->getTestReporter(), file);
context->getTestReporter()->message(
- TestMessageType::RunError, "slang-test: unable to parse test");
+ TestMessageType::RunError,
+ "slang-test: unable to parse test");
context->getTestReporter()->addResult(TestResult::Fail);
}
@@ -4223,9 +4419,7 @@ void runTestsInDirectory(
switch (context->options.defaultSpawnType)
{
case SpawnType::UseFullyIsolatedTestServer:
- case SpawnType::UseTestServer:
- useMultiThread = true;
- break;
+ case SpawnType::UseTestServer: useMultiThread = true; break;
}
if (context->options.serverCount == 1)
{
@@ -4240,17 +4434,16 @@ void runTestsInDirectory(
}
else
{
- runTestsInParallel(context, (int)files.getCount(), [&](int index)
- {
- processFile(files[index]);
- });
+ runTestsInParallel(
+ context,
+ (int)files.getCount(),
+ [&](int index) { processFile(files[index]); });
}
}
static void _disableCPPBackends(TestContext* context)
{
- const SlangPassThrough cppPassThrus[] =
- {
+ const SlangPassThrough cppPassThrus[] = {
SLANG_PASS_THROUGH_GENERIC_C_CPP,
SLANG_PASS_THROUGH_VISUAL_STUDIO,
SLANG_PASS_THROUGH_CLANG,
@@ -4274,14 +4467,18 @@ static TestResult _asTestResult(ToolReturnCode retCode)
{
switch (retCode)
{
- default: return TestResult::Fail;
- case ToolReturnCode::Success: return TestResult::Pass;
- case ToolReturnCode::Ignored: return TestResult::Ignored;
+ default: return TestResult::Fail;
+ case ToolReturnCode::Success: return TestResult::Pass;
+ case ToolReturnCode::Ignored: return TestResult::Ignored;
}
}
- /// Loads a DLL containing unit test functions and run them one by one.
-static SlangResult runUnitTestModule(TestContext* context, TestOptions& testOptions, SpawnType spawnType, const char* moduleName)
+/// Loads a DLL containing unit test functions and run them one by one.
+static SlangResult runUnitTestModule(
+ TestContext* context,
+ TestOptions& testOptions,
+ SpawnType spawnType,
+ const char* moduleName)
{
ISlangSharedLibraryLoader* loader = DefaultSharedLibraryLoader::getSingleton();
ComPtr<ISlangSharedLibrary> moduleLibrary;
@@ -4330,7 +4527,7 @@ static SlangResult runUnitTestModule(TestContext* context, TestOptions& testOpti
{
if (testPassesCategoryMask(context, testOptions))
{
- tests.add(TestItem{ testFunc, testName, command });
+ tests.add(TestItem{testFunc, testName, command});
}
}
}
@@ -4353,10 +4550,16 @@ static SlangResult runUnitTestModule(TestContext* context, TestOptions& testOpti
TestReporter::TestScope scopeTest(reporter, options.command);
ExecuteResult exeRes;
- SlangResult rpcRes = _executeRPC(context, spawnType, TestServerProtocol::ExecuteUnitTestArgs::g_methodName, &args, exeRes);
+ SlangResult rpcRes = _executeRPC(
+ context,
+ spawnType,
+ TestServerProtocol::ExecuteUnitTestArgs::g_methodName,
+ &args,
+ exeRes);
const auto testResult = _asTestResult(ToolReturnCode(exeRes.resultCode));
- // If the test fails, output any output - which might give information about individual tests that have failed.
+ // If the test fails, output any output - which might give information about
+ // individual tests that have failed.
if (SLANG_FAILED(rpcRes) || testResult == TestResult::Fail)
{
String output = getOutput(exeRes);
@@ -4371,7 +4574,7 @@ static SlangResult runUnitTestModule(TestContext* context, TestOptions& testOpti
TestReporter::TestScope scopeTest(reporter, options.command);
// TODO(JS): Problem here could be exception not handled properly across
- // shared library boundary.
+ // shared library boundary.
testModule->setTestReporter(reporter);
try
{
@@ -4379,15 +4582,16 @@ static SlangResult runUnitTestModule(TestContext* context, TestOptions& testOpti
}
catch (...)
{
- reporter->message(TestMessageType::TestFailure, "Exception was thrown during execution");
+ reporter->message(
+ TestMessageType::TestFailure,
+ "Exception was thrown during execution");
reporter->addResult(TestResult::Fail);
}
}
};
bool useMultiThread = false;
- if (spawnType == SpawnType::UseTestServer ||
- spawnType == SpawnType::UseFullyIsolatedTestServer)
+ if (spawnType == SpawnType::UseTestServer || spawnType == SpawnType::UseFullyIsolatedTestServer)
{
if (context->options.serverCount > 1)
{
@@ -4397,10 +4601,10 @@ static SlangResult runUnitTestModule(TestContext* context, TestOptions& testOpti
if (useMultiThread)
{
- runTestsInParallel(context, (int)tests.getCount(), [&](int index)
- {
- runUnitTest(tests[index]);
- });
+ runTestsInParallel(
+ context,
+ (int)tests.getCount(),
+ [&](int index) { runUnitTest(tests[index]); });
}
else
{
@@ -4431,7 +4635,7 @@ SlangResult innerMain(int argc, char** argv)
auto quickTestCategory = categorySet.add("quick", fullTestCategory);
auto smokeTestCategory = categorySet.add("smoke", quickTestCategory);
auto renderTestCategory = categorySet.add("render", fullTestCategory);
- /*auto computeTestCategory = */categorySet.add("compute", fullTestCategory);
+ /*auto computeTestCategory = */ categorySet.add("compute", fullTestCategory);
auto vulkanTestCategory = categorySet.add("vulkan", fullTestCategory);
auto unitTestCategory = categorySet.add("unit-test", fullTestCategory);
auto cudaTestCategory = categorySet.add("cuda", fullTestCategory);
@@ -4463,7 +4667,7 @@ SlangResult innerMain(int argc, char** argv)
categorySet.defaultCategory = fullTestCategory;
// All following values are initialized to '0', so null.
- TestCategory* passThroughCategories[SLANG_PASS_THROUGH_COUNT_OF] = { nullptr };
+ TestCategory* passThroughCategories[SLANG_PASS_THROUGH_COUNT_OF] = {nullptr};
// Work out what backends/pass-thrus are available
{
@@ -4502,9 +4706,12 @@ SlangResult innerMain(int argc, char** argv)
{
SlangSession* session = context.getSession();
-
- const bool hasLlvm = SLANG_SUCCEEDED(session->checkPassThroughSupport(SLANG_PASS_THROUGH_LLVM));
- const auto hostCallableCompiler = session->getDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_SHADER_HOST_CALLABLE);
+
+ const bool hasLlvm =
+ SLANG_SUCCEEDED(session->checkPassThroughSupport(SLANG_PASS_THROUGH_LLVM));
+ const auto hostCallableCompiler = session->getDownstreamCompilerForTransition(
+ SLANG_CPP_SOURCE,
+ SLANG_SHADER_HOST_CALLABLE);
if (hasLlvm && hostCallableCompiler == SLANG_PASS_THROUGH_LLVM && SLANG_PROCESSOR_X86)
{
@@ -4513,7 +4720,8 @@ SlangResult innerMain(int argc, char** argv)
}
else
{
- // Special category to mark a test only works for targets that work correctly with double (ie not x86/llvm)
+ // Special category to mark a test only works for targets that work correctly with
+ // double (ie not x86/llvm)
categorySet.add("war-double-host-callable", fullTestCategory);
}
}
@@ -4526,7 +4734,8 @@ SlangResult innerMain(int argc, char** argv)
context.setInnerMainFunc("slangc", &SlangCTool::innerMain);
}
- SLANG_RETURN_ON_FAIL(Options::parse(argc, argv, &categorySet, StdWriters::getError(), &context.options));
+ SLANG_RETURN_ON_FAIL(
+ Options::parse(argc, argv, &categorySet, StdWriters::getError(), &context.options));
Options& options = context.options;
@@ -4534,20 +4743,21 @@ SlangResult innerMain(int argc, char** argv)
// Set up the prelude/s
TestToolUtil::setSessionDefaultPreludeFromExePath(argv[0], context.getSession());
-
+
if (options.outputMode == TestOutputMode::TeamCity)
{
- // On TeamCity CI there is an issue with unix/linux targets where test system may be different from the build system
- // That we rely on having compilation tools present such that on x64 systems we can build x86 binaries, and that appears to
- // not always be the case.
- // For now we only allow CPP backends to run on x86_64 targets
-#if SLANG_UNIX_FAMILY && !SLANG_PROCESSOR_X86_64
+ // On TeamCity CI there is an issue with unix/linux targets where test system may be
+ // different from the build system That we rely on having compilation tools present such
+ // that on x64 systems we can build x86 binaries, and that appears to not always be the
+ // case. For now we only allow CPP backends to run on x86_64 targets
+#if SLANG_UNIX_FAMILY && !SLANG_PROCESSOR_X86_64
_disableCPPBackends(&context);
#endif
}
#if SLANG_PROCESSOR_X86
- // Disable d3d12 tests on x86 right now since dxc for 32-bit windows doesn't seem to recognize sm_6_6.
+ // Disable d3d12 tests on x86 right now since dxc for 32-bit windows doesn't seem to recognize
+ // sm_6_6.
_disableD3D12Backend(&context);
#endif
@@ -4557,7 +4767,9 @@ SlangResult innerMain(int argc, char** argv)
auto func = context.getInnerMainFunc(options.binDir, options.subCommand);
if (!func)
{
- StdWriters::getError().print("error: Unable to launch tool '%s'\n", options.subCommand.getBuffer());
+ StdWriters::getError().print(
+ "error: Unable to launch tool '%s'\n",
+ options.subCommand.getBuffer());
return SLANG_FAIL;
}
@@ -4570,16 +4782,20 @@ SlangResult innerMain(int argc, char** argv)
args[i] = srcArgs[i].getBuffer();
}
- return func(StdWriters::getSingleton(), context.getSession(), int(args.getCount()), args.getBuffer());
+ return func(
+ StdWriters::getSingleton(),
+ context.getSession(),
+ int(args.getCount()),
+ args.getBuffer());
}
- if( options.includeCategories.getCount() == 0 )
+ if (options.includeCategories.getCount() == 0)
{
options.includeCategories.add(fullTestCategory, fullTestCategory);
}
// Don't include OptiX tests unless the client has explicit opted into them.
- if( !options.includeCategories.containsKey(optixTestCategory) )
+ if (!options.includeCategories.containsKey(optixTestCategory))
{
options.excludeCategories.add(optixTestCategory, optixTestCategory);
}
@@ -4587,7 +4803,7 @@ SlangResult innerMain(int argc, char** argv)
// Exclude rendering tests when building under AppVeyor.
//
// TODO: this is very ad hoc, and we should do something cleaner.
- if( options.outputMode == TestOutputMode::AppVeyor )
+ if (options.outputMode == TestOutputMode::AppVeyor)
{
options.excludeCategories.add(renderTestCategory, renderTestCategory);
options.excludeCategories.add(vulkanTestCategory, vulkanTestCategory);
@@ -4612,10 +4828,10 @@ SlangResult innerMain(int argc, char** argv)
runTestsInDirectory(&context, "tests/");
}
- // Run the unit tests (these are internal C++ tests - not specified via files in a directory)
- // They are registered with SLANG_UNIT_TEST macro
+ // Run the unit tests (these are internal C++ tests - not specified via files in a
+ // directory) They are registered with SLANG_UNIT_TEST macro
+ //
//
- //
if (context.canRunUnitTests())
{
TestReporter::SuiteScope suiteScope(&reporter, "unit tests");
@@ -4636,7 +4852,7 @@ SlangResult innerMain(int argc, char** argv)
testOptions.categories.add(unitTestCategory);
runUnitTestModule(&context, testOptions, spawnType, "gfx-unit-test-tool");
}
-
+
TestReporter::set(nullptr);
}
@@ -4652,7 +4868,12 @@ SlangResult innerMain(int argc, char** argv)
FileTestInfoImpl* fileTestInfo = static_cast<FileTestInfoImpl*>(test.Ptr());
TestReporter::SuiteScope suiteScope(&reporter, "tests");
TestReporter::TestScope scope(&reporter, fileTestInfo->testName);
- auto newResult = runTest(&context, fileTestInfo->filePath, fileTestInfo->outputStem, fileTestInfo->testName, fileTestInfo->options);
+ auto newResult = runTest(
+ &context,
+ fileTestInfo->filePath,
+ fileTestInfo->outputStem,
+ fileTestInfo->testName,
+ fileTestInfo->options);
reporter.addResult(newResult);
}
}
@@ -4684,4 +4905,3 @@ int main(int argc, char** argv)
#endif
return SLANG_SUCCEEDED(res) ? 0 : 1;
}
-
diff --git a/tools/slang-test/slangc-tool.cpp b/tools/slang-test/slangc-tool.cpp
index ff44c0db6..d8ae2aa11 100644
--- a/tools/slang-test/slangc-tool.cpp
+++ b/tools/slang-test/slangc-tool.cpp
@@ -2,12 +2,16 @@
#include "slangc-tool.h"
#include "../../source/core/slang-exception.h"
-#include "../../source/core/slang-test-tool-util.h"
#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-test-tool-util.h"
using namespace Slang;
-SlangResult SlangCTool::innerMain(StdWriters* stdWriters, slang::IGlobalSession* sharedSession, int argc, const char*const* argv)
+SlangResult SlangCTool::innerMain(
+ StdWriters* stdWriters,
+ slang::IGlobalSession* sharedSession,
+ int argc,
+ const char* const* argv)
{
StdWriters::setSingleton(stdWriters);
@@ -16,10 +20,12 @@ SlangResult SlangCTool::innerMain(StdWriters* stdWriters, slang::IGlobalSession*
// The sharedSession always has a pre-loaded core module.
// This differed test checks if the command line has an option to setup the core module.
- // If so we *don't* use the sharedSession, and create a new session without the core module just for this compilation.
+ // If so we *don't* use the sharedSession, and create a new session without the core module just
+ // for this compilation.
if (TestToolUtil::hasDeferredCoreModule(Index(argc - 1), argv + 1))
{
- SLANG_RETURN_ON_FAIL(slang_createGlobalSessionWithoutCoreModule(SLANG_API_VERSION, session.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ slang_createGlobalSessionWithoutCoreModule(SLANG_API_VERSION, session.writeRef()));
}
ComPtr<slang::ICompileRequest> compileRequest;
@@ -47,11 +53,13 @@ SlangResult SlangCTool::innerMain(StdWriters* stdWriters, slang::IGlobalSession*
try
#endif
{
- // Run the compiler (this will produce any diagnostics through SLANG_WRITER_TARGET_TYPE_DIAGNOSTIC).
+ // Run the compiler (this will produce any diagnostics through
+ // SLANG_WRITER_TARGET_TYPE_DIAGNOSTIC).
compileRes = compileRequest->compile();
// If the compilation failed, then get out of here...
- // Turn into an internal Result -> such that return code can be used to vary result to match previous behavior
+ // Turn into an internal Result -> such that return code can be used to vary result to match
+ // previous behavior
compileRes = SLANG_FAILED(compileRes) ? SLANG_E_INTERNAL_FAIL : compileRes;
}
#ifndef _DEBUG
diff --git a/tools/slang-test/slangc-tool.h b/tools/slang-test/slangc-tool.h
index a1fcaa71b..0bbcd22f5 100644
--- a/tools/slang-test/slangc-tool.h
+++ b/tools/slang-test/slangc-tool.h
@@ -5,11 +5,15 @@
#include "../../source/core/slang-std-writers.h"
-/* The slangc 'tool' interface, such that slangc like functionality is available directly without invoking slangc command line tool, or
-need for a dll/shared library. */
+/* The slangc 'tool' interface, such that slangc like functionality is available directly without
+invoking slangc command line tool, or need for a dll/shared library. */
struct SlangCTool
{
- static SlangResult innerMain(Slang::StdWriters* stdWriters, SlangSession* session, int argc, const char*const* argv);
+ static SlangResult innerMain(
+ Slang::StdWriters* stdWriters,
+ SlangSession* session,
+ int argc,
+ const char* const* argv);
};
#endif // SLANGC_TOOL_H_INCLUDED
diff --git a/tools/slang-test/test-context.cpp b/tools/slang-test/test-context.cpp
index ed25831e3..bb9870dad 100644
--- a/tools/slang-test/test-context.cpp
+++ b/tools/slang-test/test-context.cpp
@@ -1,12 +1,11 @@
// test-context.cpp
#include "test-context.h"
+#include "../../source/compiler-core/slang-language-server-protocol.h"
#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-shared-library.h"
-
+#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-test-tool-util.h"
-#include "../../source/compiler-core/slang-language-server-protocol.h"
#include <stdio.h>
#include <stdlib.h>
@@ -15,18 +14,22 @@ using namespace Slang;
thread_local int slangTestThreadIndex = 0;
-TestContext::TestContext()
+TestContext::TestContext()
{
m_session = nullptr;
/// if we are testing on arm, debug, we may want to increase the connection timeout
#if (SLANG_PROCESSOR_ARM || SLANG_PROCESSOR_ARM_64) && defined(_DEBUG)
- // 10 mins(!). This seems to be the order of time needed for timeout on a CI ARM test system on debug
+ // 10 mins(!). This seems to be the order of time needed for timeout on a CI ARM test system on
+ // debug
connectionTimeOutInMs = 1000 * 60 * 10;
#endif
}
-void TestContext::setThreadIndex(int index) { slangTestThreadIndex = index; }
+void TestContext::setThreadIndex(int index)
+{
+ slangTestThreadIndex = index;
+}
void TestContext::setMaxTestRunnerThreadCount(int count)
{
@@ -62,7 +65,7 @@ TestReporter* TestContext::getTestReporter()
SlangResult TestContext::locateFileCheck()
{
DefaultSharedLibraryLoader* loader = DefaultSharedLibraryLoader::getSingleton();
-
+
SLANG_RETURN_ON_FAIL(loader->loadSharedLibrary("slang-llvm", m_fileCheckLibrary.writeRef()));
if (!m_fileCheckLibrary)
@@ -71,8 +74,9 @@ SlangResult TestContext::locateFileCheck()
}
using CreateFileCheckFunc = SlangResult (*)(const SlangUUID&, void**);
- auto fn = reinterpret_cast<CreateFileCheckFunc>(m_fileCheckLibrary->findFuncByName("createLLVMFileCheck_V1"));
- if(!fn)
+ auto fn = reinterpret_cast<CreateFileCheckFunc>(
+ m_fileCheckLibrary->findFuncByName("createLLVMFileCheck_V1"));
+ if (!fn)
{
return SLANG_FAIL;
}
@@ -130,7 +134,8 @@ TestContext::InnerMainFunc TestContext::getInnerMainFunc(const String& dirPath,
SharedLibraryTool tool = {};
- if (SLANG_SUCCEEDED(loader->loadPlatformSharedLibrary(path.begin(), tool.m_sharedLibrary.writeRef())))
+ if (SLANG_SUCCEEDED(
+ loader->loadPlatformSharedLibrary(path.begin(), tool.m_sharedLibrary.writeRef())))
{
tool.m_func = (InnerMainFunc)tool.m_sharedLibrary->findFuncByName("innerMain");
}
@@ -162,7 +167,7 @@ DownstreamCompilerSet* TestContext::getCompilerSet()
{
compilerSet = new DownstreamCompilerSet;
- DownstreamCompilerLocatorFunc locators[int(SLANG_PASS_THROUGH_COUNT_OF)] = { nullptr };
+ DownstreamCompilerLocatorFunc locators[int(SLANG_PASS_THROUGH_COUNT_OF)] = {nullptr};
DownstreamCompilerUtil::setDefaultLocators(locators);
for (Index i = 0; i < Index(SLANG_PASS_THROUGH_COUNT_OF); ++i)
@@ -186,17 +191,23 @@ SlangResult TestContext::_createJSONRPCConnection(RefPtr<JSONRPCConnection>& out
{
CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(exeDirectoryPath, "test-server"));
- SLANG_RETURN_ON_FAIL(Process::create(cmdLine, Process::Flag::AttachDebugger | Process::Flag::DisableStdErrRedirection, process));
+ SLANG_RETURN_ON_FAIL(Process::create(
+ cmdLine,
+ Process::Flag::AttachDebugger | Process::Flag::DisableStdErrRedirection,
+ process));
}
Stream* writeStream = process->getStream(StdStreamType::In);
- RefPtr<BufferedReadStream> readStream(new BufferedReadStream(process->getStream(StdStreamType::Out)));
- RefPtr<BufferedReadStream> readErrStream(new BufferedReadStream(process->getStream(StdStreamType::ErrorOut)));
+ RefPtr<BufferedReadStream> readStream(
+ new BufferedReadStream(process->getStream(StdStreamType::Out)));
+ RefPtr<BufferedReadStream> readErrStream(
+ new BufferedReadStream(process->getStream(StdStreamType::ErrorOut)));
RefPtr<HTTPPacketConnection> connection = new HTTPPacketConnection(readStream, writeStream);
RefPtr<JSONRPCConnection> rpcConnection = new JSONRPCConnection;
- SLANG_RETURN_ON_FAIL(rpcConnection->init(connection, JSONRPCConnection::CallStyle::Default, process));
+ SLANG_RETURN_ON_FAIL(
+ rpcConnection->init(connection, JSONRPCConnection::CallStyle::Default, process));
out = rpcConnection;
diff --git a/tools/slang-test/test-context.h b/tools/slang-test/test-context.h
index 6d45809ac..4fb014359 100644
--- a/tools/slang-test/test-context.h
+++ b/tools/slang-test/test-context.h
@@ -3,23 +3,18 @@
#ifndef TEST_CONTEXT_H_INCLUDED
#define TEST_CONTEXT_H_INCLUDED
-#include "../../source/core/slang-string-util.h"
+#include "../../source/compiler-core/slang-downstream-compiler-util.h"
+#include "../../source/compiler-core/slang-downstream-compiler.h"
+#include "../../source/compiler-core/slang-json-rpc-connection.h"
+#include "../../source/core/slang-dictionary.h"
#include "../../source/core/slang-platform.h"
+#include "../../source/core/slang-render-api-util.h"
#include "../../source/core/slang-std-writers.h"
-#include "../../source/core/slang-dictionary.h"
+#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-test-tool-util.h"
-#include "../../source/core/slang-render-api-util.h"
-
-#include "../../source/compiler-core/slang-downstream-compiler.h"
-#include "../../source/compiler-core/slang-downstream-compiler-util.h"
-
-#include "../../source/compiler-core/slang-json-rpc-connection.h"
-
-#include "slang-com-ptr.h"
-
#include "filecheck.h"
-
#include "options.h"
+#include "slang-com-ptr.h"
#include <mutex>
@@ -43,16 +38,16 @@ struct PassThroughFlag
};
/// Structure that describes requirements needs to run - such as rendering APIs or
-/// back-end availability
+/// back-end availability
struct TestRequirements
{
-
+
TestRequirements& addUsedRenderApi(Slang::RenderApiType type)
{
using namespace Slang;
if (type != RenderApiType::Unknown)
{
- usedRenderApiFlags |=RenderApiFlags(1) << int(type);
+ usedRenderApiFlags |= RenderApiFlags(1) << int(type);
}
return *this;
}
@@ -74,15 +69,17 @@ struct TestRequirements
usedRenderApiFlags |= flags;
return *this;
}
- /// True if has this render api as used
+ /// True if has this render api as used
bool isUsed(Slang::RenderApiType apiType) const
{
- return (apiType != Slang::RenderApiType::Unknown) && ((usedRenderApiFlags & (Slang::RenderApiFlags(1) << int(apiType))) != 0);
+ return (apiType != Slang::RenderApiType::Unknown) &&
+ ((usedRenderApiFlags & (Slang::RenderApiFlags(1) << int(apiType))) != 0);
}
- Slang::RenderApiType explicitRenderApi = Slang::RenderApiType::Unknown; ///< The render api explicitly specified
- PassThroughFlags usedBackendFlags = 0; ///< Used backends
- Slang::RenderApiFlags usedRenderApiFlags = 0; ///< Used render api flags (some might be implied)
+ Slang::RenderApiType explicitRenderApi =
+ Slang::RenderApiType::Unknown; ///< The render api explicitly specified
+ PassThroughFlags usedBackendFlags = 0; ///< Used backends
+ Slang::RenderApiFlags usedRenderApiFlags = 0; ///< Used render api flags (some might be implied)
};
struct FileTestInfo : public Slang::RefObject
@@ -92,7 +89,6 @@ struct FileTestInfo : public Slang::RefObject
class TestContext
{
public:
-
typedef Slang::TestToolUtil::InnerMainFunc InnerMainFunc;
/// Get the slang session
@@ -115,16 +111,21 @@ public:
bool isExecuting() const { return getTestRequirements() == nullptr; }
/// True if a render API filter is enabled
- bool isRenderApiFilterEnabled() const { return options.enabledApis != Slang::RenderApiFlag::AllOf && options.enabledApis != 0; }
+ bool isRenderApiFilterEnabled() const
+ {
+ return options.enabledApis != Slang::RenderApiFlag::AllOf && options.enabledApis != 0;
+ }
- /// True if a test with the requiredFlags can in principal run (it may not be possible if the API is not available though)
+ /// True if a test with the requiredFlags can in principal run (it may not be possible if the
+ /// API is not available though)
bool canRunTestWithRenderApiFlags(Slang::RenderApiFlags requiredFlags);
/// True if can run unit tests
bool canRunUnitTests() const { return options.apiOnly == false; }
/// Given a spawn type, return the final spawn type.
- /// In particular we want 'Default' spawn type to vary by the environment (for example running on test server on CI)
+ /// In particular we want 'Default' spawn type to vary by the environment (for example running
+ /// on test server on CI)
SpawnType getFinalSpawnType(SpawnType spawnType);
SpawnType getFinalSpawnType();
@@ -144,7 +145,7 @@ public:
Options options;
TestCategorySet categorySet;
- /// If set then tests are not run, but their requirements are set
+ /// If set then tests are not run, but their requirements are set
PassThroughFlags availableBackendFlags = 0;
Slang::RenderApiFlags availableRenderApiFlags = 0;
@@ -163,8 +164,8 @@ public:
/// NOTE! This timeout may be altered in the ctor for a specific target, the initializatoin
/// value is just the default.
///
- /// TODO(JS): We could split the core module compilation from other actions, and have timeout specific for
- /// that. To do this we could have a 'compileCoreModule' RPC method.
+ /// TODO(JS): We could split the core module compilation from other actions, and have timeout
+ /// specific for that. To do this we could have a 'compileCoreModule' RPC method.
///
/// Current default is 60 seconds.
Slang::Int connectionTimeOutInMs = 60 * 1000;
@@ -179,7 +180,7 @@ public:
std::mutex mutex;
Slang::RefPtr<Slang::JSONRPCConnection> m_languageServerConnection;
-
+
std::mutex mutexFailedFileTests;
Slang::List<Slang::RefPtr<FileTestInfo>> failedFileTests;
@@ -199,7 +200,7 @@ protected:
Slang::List<Slang::RefPtr<Slang::JSONRPCConnection>> m_jsonRpcConnections;
Slang::List<TestReporter*> m_reporters;
Slang::List<TestRequirements*> m_testRequirements = nullptr;
-
+
SlangSession* m_session;
Slang::Dictionary<Slang::String, SharedLibraryTool> m_sharedLibTools;
diff --git a/tools/slang-test/test-reporter.cpp b/tools/slang-test/test-reporter.cpp
index 3ac8d90ea..dad93e868 100644
--- a/tools/slang-test/test-reporter.cpp
+++ b/tools/slang-test/test-reporter.cpp
@@ -1,28 +1,27 @@
// test-reporter.cpp
#include "test-reporter.h"
-#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-process-util.h"
+#include "../../source/core/slang-string-util.h"
+#include <mutex>
#include <stdio.h>
#include <stdlib.h>
-#include <mutex>
-
using namespace Slang;
-/* static */TestReporter* TestReporter::s_reporter = nullptr;
+/* static */ TestReporter* TestReporter::s_reporter = nullptr;
static void appendXmlEncode(char c, StringBuilder& out)
{
switch (c)
{
- case '&': out << "&amp;"; break;
- case '<': out << "&lt;"; break;
- case '>': out << "&gt;"; break;
- case '\'': out << "&apos;"; break;
- case '"': out << "&quot;"; break;
- default: out.append(c);
+ case '&': out << "&amp;"; break;
+ case '<': out << "&lt;"; break;
+ case '>': out << "&gt;"; break;
+ case '\'': out << "&apos;"; break;
+ case '"': out << "&quot;"; break;
+ default: out.append(c);
}
}
@@ -30,9 +29,9 @@ static bool isXmlEncodeChar(char c)
{
switch (c)
{
- case '&':
- case '<':
- case '>':
+ case '&':
+ case '<':
+ case '>':
{
return true;
}
@@ -69,8 +68,8 @@ static void appendXmlEncode(const String& in, StringBuilder& out)
}
}
-TestReporter::TestReporter() :
- m_outputMode(TestOutputMode::Default)
+TestReporter::TestReporter()
+ : m_outputMode(TestOutputMode::Default)
{
m_totalTestCount = 0;
m_passedTestCount = 0;
@@ -84,7 +83,10 @@ TestReporter::TestReporter() :
m_isVerbose = false;
}
-Result TestReporter::init(TestOutputMode outputMode, const HashSet<String>& expectedFailureList, bool isSubReporter)
+Result TestReporter::init(
+ TestOutputMode outputMode,
+ const HashSet<String>& expectedFailureList,
+ bool isSubReporter)
{
m_outputMode = outputMode;
m_isSubReporter = isSubReporter;
@@ -92,20 +94,18 @@ Result TestReporter::init(TestOutputMode outputMode, const HashSet<String>& expe
return SLANG_OK;
}
-TestReporter::~TestReporter()
-{
-}
+TestReporter::~TestReporter() {}
bool TestReporter::canWriteStdError() const
{
switch (m_outputMode)
{
- case TestOutputMode::XUnit:
- case TestOutputMode::XUnit2:
+ case TestOutputMode::XUnit:
+ case TestOutputMode::XUnit2:
{
return false;
}
- default: return true;
+ default: return true;
}
}
@@ -155,7 +155,11 @@ void TestReporter::addExecutionTime(double time)
m_currentInfo.executionTime = time;
}
-void TestReporter::addResultWithLocation(TestResult result, const char* testText, const char* file, int line)
+void TestReporter::addResultWithLocation(
+ TestResult result,
+ const char* testText,
+ const char* file,
+ int line)
{
assert(m_inTest);
@@ -167,7 +171,7 @@ void TestReporter::addResultWithLocation(TestResult result, const char* testText
m_currentInfo.testResult = combine(m_currentInfo.testResult, result);
if (result != TestResult::Fail)
{
- // We don't need to output the result if it
+ // We don't need to output the result if it
return;
}
@@ -179,22 +183,31 @@ void TestReporter::addResultWithLocation(TestResult result, const char* testText
{
if (m_numFailResults == m_maxFailTestResults + 1)
{
- // It's a failure, but to show that there are more than are going to be shown, just show '...'
+ // It's a failure, but to show that there are more than are going to be shown, just
+ // show '...'
message(TestMessageType::TestFailure, "...");
}
return;
}
- }
+ }
StringBuilder buf;
- buf << testText << " - " << file << " (" << line << ")";
+ buf << testText << " - " << file << " (" << line << ")";
message(TestMessageType::TestFailure, buf);
}
-void TestReporter::addResultWithLocation(bool testSucceeded, const char* testText, const char* file, int line)
+void TestReporter::addResultWithLocation(
+ bool testSucceeded,
+ const char* testText,
+ const char* file,
+ int line)
{
- addResultWithLocation(testSucceeded ? TestResult::Pass : TestResult::Fail, testText, file, line);
+ addResultWithLocation(
+ testSucceeded ? TestResult::Pass : TestResult::Fail,
+ testText,
+ file,
+ line);
}
TestResult TestReporter::addTest(const String& testName, bool isPass)
@@ -218,7 +231,8 @@ void TestReporter::dumpOutputDifference(const String& expectedOutput, const Stri
{
StringBuilder builder;
- StringUtil::appendFormat(builder,
+ StringUtil::appendFormat(
+ builder,
"ERROR:\n"
"EXPECTED{{{\n%s}}}\n"
"ACTUAL{{{\n%s}}}\n",
@@ -233,13 +247,13 @@ static char _getTeamCityEscapeChar(char c)
{
switch (c)
{
- case '|': return '|';
- case '\'': return '\'';
- case '\n': return 'n';
- case '\r': return 'r';
- case '[': return '[';
- case ']': return ']';
- default: return 0;
+ case '|': return '|';
+ case '\'': return '\'';
+ case '\n': return 'n';
+ case '\r': return 'r';
+ case '[': return '[';
+ case ']': return ']';
+ default: return 0;
}
}
@@ -248,7 +262,7 @@ static void _appendEncodedTeamCityString(const UnownedStringSlice& in, StringBui
const char* start = in.begin();
const char* cur = start;
const char* end = in.end();
-
+
for (const char* cur = start; cur < end; cur++)
{
const char c = *cur;
@@ -265,7 +279,7 @@ static void _appendEncodedTeamCityString(const UnownedStringSlice& in, StringBui
builder.append(escapeChar);
start = cur + 1;
}
- }
+ }
// Flush the end
if (end > start)
@@ -311,24 +325,14 @@ void TestReporter::_addResult(TestInfo info)
switch (info.testResult)
{
- case TestResult::Fail:
- m_failedTestCount++;
- break;
+ case TestResult::Fail: m_failedTestCount++; break;
- case TestResult::Pass:
- m_passedTestCount++;
- break;
- case TestResult::ExpectedFail:
- m_expectedFailedTestCount++;
- break;
+ case TestResult::Pass: m_passedTestCount++; break;
+ case TestResult::ExpectedFail: m_expectedFailedTestCount++; break;
- case TestResult::Ignored:
- m_ignoredTestCount++;
- break;
+ case TestResult::Ignored: m_ignoredTestCount++; break;
- default:
- assert(!"unexpected");
- break;
+ default: assert(!"unexpected"); break;
}
m_testInfos.add(info);
@@ -338,21 +342,11 @@ void TestReporter::_addResult(TestInfo info)
char const* resultString = "UNEXPECTED";
switch (info.testResult)
{
- case TestResult::Fail:
- resultString = "FAILED";
- break;
- case TestResult::ExpectedFail:
- resultString = "failed(expected)";
- break;
- case TestResult::Pass:
- resultString = "passed";
- break;
- case TestResult::Ignored:
- resultString = "ignored";
- break;
- default:
- assert(!"unexpected");
- break;
+ case TestResult::Fail: resultString = "FAILED"; break;
+ case TestResult::ExpectedFail: resultString = "failed(expected)"; break;
+ case TestResult::Pass: resultString = "passed"; break;
+ case TestResult::Ignored: resultString = "ignored"; break;
+ default: assert(!"unexpected"); break;
}
StringBuilder buffer;
@@ -360,18 +354,22 @@ void TestReporter::_addResult(TestInfo info)
{
_appendTime(info.executionTime, buffer);
}
- printf("%s test: '%S' %s\n", resultString, info.name.toWString().begin(), buffer.getBuffer());
+ printf(
+ "%s test: '%S' %s\n",
+ resultString,
+ info.name.toWString().begin(),
+ buffer.getBuffer());
fflush(stdout);
};
switch (m_outputMode)
{
- default:
+ default:
{
defaultOutputFunc(info);
break;
}
- case TestOutputMode::TeamCity:
+ case TestOutputMode::TeamCity:
{
StringBuilder escapedTestName;
_appendEncodedTeamCityString(info.name.getUnownedSlice(), escapedTestName);
@@ -380,13 +378,18 @@ void TestReporter::_addResult(TestInfo info)
switch (info.testResult)
{
- case TestResult::Fail:
+ case TestResult::Fail:
{
if (info.message.getLength())
{
StringBuilder escapedMessage;
- _appendEncodedTeamCityString(info.message.getUnownedSlice(), escapedMessage);
- printf("##teamcity[testFailed name='%s' message='%s']\n", escapedTestName.begin(), escapedMessage.begin());
+ _appendEncodedTeamCityString(
+ info.message.getUnownedSlice(),
+ escapedMessage);
+ printf(
+ "##teamcity[testFailed name='%s' message='%s']\n",
+ escapedTestName.begin(),
+ escapedMessage.begin());
}
else
{
@@ -394,8 +397,8 @@ void TestReporter::_addResult(TestInfo info)
}
break;
}
- case TestResult::Pass:
- case TestResult::ExpectedFail:
+ case TestResult::Pass:
+ case TestResult::ExpectedFail:
{
StringBuilder message;
message << info.message;
@@ -413,18 +416,26 @@ void TestReporter::_addResult(TestInfo info)
{
StringBuilder escapedMessage;
_appendEncodedTeamCityString(message.getUnownedSlice(), escapedMessage);
- printf("##teamcity[testStdOut name='%s' out='%s']\n", escapedTestName.begin(), escapedMessage.begin());
- }
+ printf(
+ "##teamcity[testStdOut name='%s' out='%s']\n",
+ escapedTestName.begin(),
+ escapedMessage.begin());
+ }
break;
}
- case TestResult::Ignored:
+ case TestResult::Ignored:
{
if (info.message.getLength())
{
StringBuilder escapedMessage;
- _appendEncodedTeamCityString(info.message.getUnownedSlice(), escapedMessage);
-
- printf("##teamcity[testIgnored name='%s' message='%s']\n", escapedTestName.begin(), escapedMessage.begin());
+ _appendEncodedTeamCityString(
+ info.message.getUnownedSlice(),
+ escapedMessage);
+
+ printf(
+ "##teamcity[testIgnored name='%s' message='%s']\n",
+ escapedTestName.begin(),
+ escapedMessage.begin());
}
else
{
@@ -432,34 +443,30 @@ void TestReporter::_addResult(TestInfo info)
}
break;
}
- default:
- assert(!"unexpected");
- break;
+ default: assert(!"unexpected"); break;
}
printf("##teamcity[testFinished name='%s']\n", escapedTestName.begin());
fflush(stdout);
break;
}
- case TestOutputMode::XUnit2:
- case TestOutputMode::XUnit:
+ case TestOutputMode::XUnit2:
+ case TestOutputMode::XUnit:
{
// Don't output anything -> we'll output all in one go at the end
break;
}
- case TestOutputMode::AppVeyor:
+ case TestOutputMode::AppVeyor:
{
char const* resultString = "None";
switch (info.testResult)
{
- case TestResult::Fail: resultString = "Failed"; break;
- case TestResult::Pass: resultString = "Passed"; break;
- case TestResult::Ignored: resultString = "Ignored"; break;
- case TestResult::ExpectedFail: resultString = "ExpectedFail"; break;
+ case TestResult::Fail: resultString = "Failed"; break;
+ case TestResult::Pass: resultString = "Passed"; break;
+ case TestResult::Ignored: resultString = "Ignored"; break;
+ case TestResult::ExpectedFail: resultString = "ExpectedFail"; break;
- default:
- assert(!"unexpected");
- break;
+ default: assert(!"unexpected"); break;
}
// https://www.appveyor.com/docs/build-worker-api/#add-tests
@@ -487,10 +494,13 @@ void TestReporter::_addResult(TestInfo info)
ExecuteResult exeRes;
SlangResult res = ProcessUtil::execute(cmdLine, exeRes);
-
+
if (SLANG_FAILED(res))
{
- messageFormat(TestMessageType::Info, "failed to add appveyor test results for '%S'\n", info.name.toWString().begin());
+ messageFormat(
+ TestMessageType::Info,
+ "failed to add appveyor test results for '%S'\n",
+ info.name.toWString().begin());
#if 0
String cmdLineString = ProcessUtil::getCommandLineString(cmdLine);
@@ -587,7 +597,7 @@ void TestReporter::outputSummary()
switch (m_outputMode)
{
- default:
+ default:
{
if (!m_totalTestCount)
{
@@ -638,34 +648,48 @@ void TestReporter::outputSummary()
}
printf("---\n");
}
-
+
break;
}
-
- case TestOutputMode::XUnit:
+
+ case TestOutputMode::XUnit:
{
- // xUnit 1.0 format
+ // xUnit 1.0 format
printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
- printf("<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" name=\"AllTests\">\n", m_totalTestCount, m_failedTestCount, m_ignoredTestCount);
- printf(" <testsuite name=\"all\" tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" time=\"0\">\n", m_totalTestCount, m_failedTestCount, m_ignoredTestCount);
+ printf(
+ "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" "
+ "name=\"AllTests\">\n",
+ m_totalTestCount,
+ m_failedTestCount,
+ m_ignoredTestCount);
+ printf(
+ " <testsuite name=\"all\" tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
+ "errors=\"0\" time=\"0\">\n",
+ m_totalTestCount,
+ m_failedTestCount,
+ m_ignoredTestCount);
for (const auto& testInfo : m_testInfos)
{
const int numFailed = (testInfo.testResult == TestResult::Fail);
const int numIgnored = (testInfo.testResult == TestResult::Ignored);
- //int numPassed = (testInfo.testResult == TestResult::ePass);
+ // int numPassed = (testInfo.testResult == TestResult::ePass);
if (testInfo.testResult == TestResult::Pass)
{
- printf(" <testcase name=\"%s\" status=\"run\"/>\n", testInfo.name.getBuffer());
+ printf(
+ " <testcase name=\"%s\" status=\"run\"/>\n",
+ testInfo.name.getBuffer());
}
else
{
- printf(" <testcase name=\"%s\" status=\"run\">\n", testInfo.name.getBuffer());
+ printf(
+ " <testcase name=\"%s\" status=\"run\">\n",
+ testInfo.name.getBuffer());
switch (testInfo.testResult)
{
- case TestResult::Fail:
+ case TestResult::Fail:
{
StringBuilder buf;
appendXmlEncode(testInfo.message, buf);
@@ -675,12 +699,12 @@ void TestReporter::outputSummary()
printf(" </error>\n");
break;
}
- case TestResult::Ignored:
+ case TestResult::Ignored:
{
printf(" <skip>Ignored</skip>\n");
break;
}
- default: break;
+ default: break;
}
printf(" </testcase>\n");
}
@@ -690,13 +714,13 @@ void TestReporter::outputSummary()
printf("</testSuites>\n");
break;
}
- case TestOutputMode::XUnit2:
+ case TestOutputMode::XUnit2:
{
// https://xunit.github.io/docs/format-xml-v2
assert("Not currently supported");
break;
}
- case TestOutputMode::TeamCity:
+ case TestOutputMode::TeamCity:
{
// Don't output a summary
break;
@@ -710,7 +734,7 @@ void TestReporter::startSuite(const String& name)
switch (m_outputMode)
{
- case TestOutputMode::TeamCity:
+ case TestOutputMode::TeamCity:
{
if (!m_isSubReporter)
{
@@ -720,7 +744,7 @@ void TestReporter::startSuite(const String& name)
}
break;
}
- default: break;
+ default: break;
}
}
@@ -730,7 +754,7 @@ void TestReporter::endSuite()
switch (m_outputMode)
{
- case TestOutputMode::TeamCity:
+ case TestOutputMode::TeamCity:
{
if (!m_isSubReporter)
{
@@ -741,9 +765,9 @@ void TestReporter::endSuite()
}
break;
}
- default: break;
+ default: break;
}
-
+
m_suiteStack.removeLast();
}
diff --git a/tools/slang-test/test-reporter.h b/tools/slang-test/test-reporter.h
index 775732745..8e7b73c67 100644
--- a/tools/slang-test/test-reporter.h
+++ b/tools/slang-test/test-reporter.h
@@ -3,48 +3,44 @@
#ifndef TEST_REPORTER_H_INCLUDED
#define TEST_REPORTER_H_INCLUDED
-#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-dictionary.h"
#include "../../source/core/slang-platform.h"
#include "../../source/core/slang-std-writers.h"
-#include "../../source/core/slang-dictionary.h"
+#include "../../source/core/slang-string-util.h"
#include "tools/unit-test/slang-unit-test.h"
#include <mutex>
enum class TestOutputMode
{
- Default = 0, ///< Default mode is to write test results to the console
- AppVeyor, ///< For AppVeyor continuous integration
- Travis, ///< We currently don't specialize for Travis, but maybe we should.
- XUnit, ///< xUnit original format https://nose.readthedocs.io/en/latest/plugins/xunit.html
- XUnit2, ///< https://xunit.github.io/docs/format-xml-v2
- TeamCity, ///< Output suitable for teamcity
+ Default = 0, ///< Default mode is to write test results to the console
+ AppVeyor, ///< For AppVeyor continuous integration
+ Travis, ///< We currently don't specialize for Travis, but maybe we should.
+ XUnit, ///< xUnit original format https://nose.readthedocs.io/en/latest/plugins/xunit.html
+ XUnit2, ///< https://xunit.github.io/docs/format-xml-v2
+ TeamCity, ///< Output suitable for teamcity
};
class TestReporter : public ITestReporter
{
public:
-
struct TestInfo
{
TestResult testResult = TestResult::Ignored;
Slang::String name;
- Slang::String message; ///< Message that is specific for the testResult
- double executionTime = 0.0; ///< <= 0.0 if not defined. Time is in seconds.
+ Slang::String message; ///< Message that is specific for the testResult
+ double executionTime = 0.0; ///< <= 0.0 if not defined. Time is in seconds.
};
-
+
class TestScope
{
public:
- TestScope(TestReporter* reporter, const Slang::String& testName) :
- m_reporter(reporter)
+ TestScope(TestReporter* reporter, const Slang::String& testName)
+ : m_reporter(reporter)
{
reporter->startTest(testName.getBuffer());
}
- ~TestScope()
- {
- m_reporter->endTest();
- }
+ ~TestScope() { m_reporter->endTest(); }
protected:
TestReporter* m_reporter;
@@ -53,15 +49,12 @@ public:
class SuiteScope
{
public:
- SuiteScope(TestReporter* reporter, const Slang::String& suiteName) :
- m_reporter(reporter)
+ SuiteScope(TestReporter* reporter, const Slang::String& suiteName)
+ : m_reporter(reporter)
{
reporter->startSuite(suiteName);
}
- ~SuiteScope()
- {
- m_reporter->endSuite();
- }
+ ~SuiteScope() { m_reporter->endSuite(); }
protected:
TestReporter* m_reporter;
@@ -74,40 +67,54 @@ public:
virtual SLANG_NO_THROW void SLANG_MCALL startTest(const char* testName) override;
virtual SLANG_NO_THROW void SLANG_MCALL addResult(TestResult result) override;
- virtual SLANG_NO_THROW void SLANG_MCALL addResultWithLocation(TestResult result, const char* testText, const char* file, int line) override;
- virtual SLANG_NO_THROW void SLANG_MCALL addResultWithLocation(bool testSucceeded, const char* testText, const char* file, int line) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL addResultWithLocation(
+ TestResult result,
+ const char* testText,
+ const char* file,
+ int line) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL addResultWithLocation(
+ bool testSucceeded,
+ const char* testText,
+ const char* file,
+ int line) override;
virtual SLANG_NO_THROW void SLANG_MCALL addExecutionTime(double time) override;
virtual SLANG_NO_THROW void SLANG_MCALL endTest() override;
-
- /// Runs start/endTest and outputs the result
+
+ /// Runs start/endTest and outputs the result
TestResult addTest(const Slang::String& testName, bool isPass);
- /// Effectively runs start/endTest (so cannot be called inside start/endTest).
+ /// Effectively runs start/endTest (so cannot be called inside start/endTest).
void addTest(const Slang::String& testName, TestResult testResult);
- // Called for an error in the test-runner (not for an error involving a test itself).
+ // Called for an error in the test-runner (not for an error involving a test itself).
void message(TestMessageType type, const Slang::String& errorText);
SLANG_ATTR_PRINTF(3, 4)
void messageFormat(TestMessageType type, char const* message, ...);
- virtual SLANG_NO_THROW void SLANG_MCALL message(TestMessageType type, char const* message) override;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ message(TestMessageType type, char const* message) override;
- void dumpOutputDifference(const Slang::String& expectedOutput, const Slang::String& actualOutput);
+ void dumpOutputDifference(
+ const Slang::String& expectedOutput,
+ const Slang::String& actualOutput);
void consolidateWith(TestReporter* other);
- /// True if can write output directly to stderr
+ /// True if can write output directly to stderr
bool canWriteStdError() const;
-
- /// Returns true if all run tests succeeded
+
+ /// Returns true if all run tests succeeded
bool didAllSucceed() const;
void outputSummary();
- SlangResult init(TestOutputMode outputMode, const Slang::HashSet<Slang::String>& expectedFailureList, bool isSubReporter = false);
+ SlangResult init(
+ TestOutputMode outputMode,
+ const Slang::HashSet<Slang::String>& expectedFailureList,
+ bool isSubReporter = false);
- /// Ctor
+ /// Ctor
TestReporter();
- /// Dtor
+ /// Dtor
~TestReporter();
static TestResult combine(TestResult a, TestResult b) { return (a > b) ? a : b; }
@@ -125,7 +132,7 @@ public:
int m_ignoredTestCount;
int m_expectedFailedTestCount;
- int m_maxFailTestResults; ///< Maximum amount of results per test. If 0 it's infinite.
+ int m_maxFailTestResults; ///< Maximum amount of results per test. If 0 it's infinite.
TestOutputMode m_outputMode = TestOutputMode::Default;
bool m_dumpOutputOnFailure;
@@ -133,10 +140,10 @@ public:
bool m_hideIgnored = false;
bool m_isSubReporter = false;
Slang::HashSet<Slang::String> m_expectedFailureList;
+
protected:
-
void _addResult(TestInfo info);
-
+
Slang::StringBuilder m_currentMessage;
TestInfo m_currentInfo;
int m_numCurrentResults;
@@ -150,4 +157,3 @@ protected:
};
#endif // TEST_REPORTER_H_INCLUDED
-
diff --git a/tools/slang-unit-test/unit-test-byte-encode.cpp b/tools/slang-unit-test/unit-test-byte-encode.cpp
index 38bd5561d..36b9f91d8 100644
--- a/tools/slang-unit-test/unit-test-byte-encode.cpp
+++ b/tools/slang-unit-test/unit-test-byte-encode.cpp
@@ -1,15 +1,13 @@
// unit-test-byte-encode.cpp
#include "../../source/core/slang-byte-encode-util.h"
+#include "../../source/core/slang-list.h"
+#include "../../source/core/slang-random-generator.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "../../source/core/slang-random-generator.h"
-#include "../../source/core/slang-list.h"
-
using namespace Slang;
static void checkUInt32(uint32_t value)
@@ -91,28 +89,38 @@ SLANG_UNIT_TEST(byteEncode)
{
const int v = ByteEncodeUtil::calcMsb8(uint32_t((randGen.nextInt32() & 0xf) | 1));
- // Make the commonality of different numbers that bytes are most common, then shorts etc..
+ // Make the commonality of different numbers that bytes are most common, then shorts
+ // etc..
uint32_t mask;
switch (v)
{
- case 0: mask = 0xffffffff; break;
- case 1: mask = 0x00ffffff; break;
- case 2: mask = 0x0000ffff; break;
- case 3: mask = 0x000000ff; break;
+ case 0: mask = 0xffffffff; break;
+ case 1: mask = 0x00ffffff; break;
+ case 2: mask = 0x0000ffff; break;
+ case 3: mask = 0x000000ff; break;
}
initialBuffer[i] = randGen.nextInt32() & mask;
}
-
- size_t numEncodeBytes = ByteEncodeUtil::encodeLiteUInt32(initialBuffer.begin(), blockSize, encodedBuffer.begin());
- SLANG_CHECK(ByteEncodeUtil::calcEncodeLiteSizeUInt32(initialBuffer.begin(), blockSize) == numEncodeBytes);
+ size_t numEncodeBytes = ByteEncodeUtil::encodeLiteUInt32(
+ initialBuffer.begin(),
+ blockSize,
+ encodedBuffer.begin());
+
+ SLANG_CHECK(
+ ByteEncodeUtil::calcEncodeLiteSizeUInt32(initialBuffer.begin(), blockSize) ==
+ numEncodeBytes);
+
+ size_t numEncodeBytes2 = ByteEncodeUtil::decodeLiteUInt32(
+ encodedBuffer.begin(),
+ blockSize,
+ decodeBuffer.begin());
- size_t numEncodeBytes2 = ByteEncodeUtil::decodeLiteUInt32(encodedBuffer.begin(), blockSize, decodeBuffer.begin());
-
SLANG_CHECK(numEncodeBytes2 == numEncodeBytes);
-
- SLANG_CHECK(memcmp(decodeBuffer.begin(), initialBuffer.begin(), sizeof(uint32_t) * blockSize) == 0);
+
+ SLANG_CHECK(
+ memcmp(decodeBuffer.begin(), initialBuffer.begin(), sizeof(uint32_t) * blockSize) == 0);
}
{
@@ -134,6 +142,5 @@ SLANG_UNIT_TEST(byteEncode)
checkUInt32(uint32_t(i));
}
#endif
- }
-
+ }
}
diff --git a/tools/slang-unit-test/unit-test-com-host-callable.cpp b/tools/slang-unit-test/unit-test-com-host-callable.cpp
index 29bc91739..7fcc033b4 100644
--- a/tools/slang-unit-test/unit-test-com-host-callable.cpp
+++ b/tools/slang-unit-test/unit-test-com-host-callable.cpp
@@ -1,27 +1,25 @@
// unit-test-com-host-callable.cpp
#include "../../source/core/slang-byte-encode-util.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang.h"
+#include "../../source/core/slang-list.h"
#include "slang-com-helper.h"
#include "slang-com-ptr.h"
+#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
-#include "../../source/core/slang-list.h"
+#include <stdio.h>
+#include <stdlib.h>
-namespace { // anonymous
+namespace
+{ // anonymous
// Slang namespace is used for elements support code (like core) which we use here
// for ComPtr<> and TestToolUtil
using namespace Slang;
-// For the moment we have to explicitly write the Slang COM interface in C++ code. It *MUST* match
+// For the moment we have to explicitly write the Slang COM interface in C++ code. It *MUST* match
// the interface in the slang source
-// As it stands all interfaces need to derive from ISlangUnknown (or IUnknown).
+// As it stands all interfaces need to derive from ISlangUnknown (or IUnknown).
class IDoThings : public ISlangUnknown
{
public:
@@ -50,20 +48,34 @@ class DoThings : public IDoThings
{
public:
// We don't need queryInterface for this impl, or ref counting
- virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE { return SLANG_E_NOT_IMPLEMENTED; }
+ virtual SLANG_NO_THROW SlangResult SLANG_MCALL
+ queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE
+ {
+ return SLANG_E_NOT_IMPLEMENTED;
+ }
virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return 1; }
virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return 1; }
// IDoThings
- virtual SLANG_NO_THROW int SLANG_MCALL doThing(int a, int b) SLANG_OVERRIDE { return a + b + 1; }
- virtual SLANG_NO_THROW int SLANG_MCALL calcHash(const char* in) SLANG_OVERRIDE { return (int)_calcHash(in); }
+ virtual SLANG_NO_THROW int SLANG_MCALL doThing(int a, int b) SLANG_OVERRIDE
+ {
+ return a + b + 1;
+ }
+ virtual SLANG_NO_THROW int SLANG_MCALL calcHash(const char* in) SLANG_OVERRIDE
+ {
+ return (int)_calcHash(in);
+ }
};
class CountGood : public ICountGood
{
public:
// We don't need queryInterface for this impl, or ref counting
- virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE { return SLANG_E_NOT_IMPLEMENTED; }
+ virtual SLANG_NO_THROW SlangResult SLANG_MCALL
+ queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE
+ {
+ return SLANG_E_NOT_IMPLEMENTED;
+ }
virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return 1; }
virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return 1; }
@@ -75,44 +87,50 @@ public:
struct ComTestContext
{
- ComTestContext(UnitTestContext* context):
- m_unitTestContext(context)
+ ComTestContext(UnitTestContext* context)
+ : m_unitTestContext(context)
{
slang::IGlobalSession* slangSession = m_unitTestContext->slangGlobalSession;
- m_defaultCppCompiler = slangSession->getDefaultDownstreamCompiler(SLANG_SOURCE_LANGUAGE_CPP);
-
- m_hostHostCallableCompiler = slangSession->getDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_HOST_HOST_CALLABLE);
- m_shaderHostCallableCompiler = slangSession->getDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_SHADER_HOST_CALLABLE);
+ m_defaultCppCompiler =
+ slangSession->getDefaultDownstreamCompiler(SLANG_SOURCE_LANGUAGE_CPP);
+ m_hostHostCallableCompiler = slangSession->getDownstreamCompilerForTransition(
+ SLANG_CPP_SOURCE,
+ SLANG_HOST_HOST_CALLABLE);
+ m_shaderHostCallableCompiler = slangSession->getDownstreamCompilerForTransition(
+ SLANG_CPP_SOURCE,
+ SLANG_SHADER_HOST_CALLABLE);
}
SlangResult runTests()
{
slang::IGlobalSession* slangSession = m_unitTestContext->slangGlobalSession;
- // TODO(JS):
- // Care is needed around this in normal testing. `slang-llvm` is whatever was asked for for when premake was built
- // when the target is specified. Otherwise it is the `default` which is typically 64 bit during development.
+ // TODO(JS):
+ // Care is needed around this in normal testing. `slang-llvm` is whatever was asked for for
+ // when premake was built when the target is specified. Otherwise it is the `default` which
+ // is typically 64 bit during development.
//
- // On CI we should be okay, because it should download the correct `slang-llvm` for the build (as it packages up with it).
- // But for normal development, that can easily not be the case (for example changing to 32 bit build in VS is a problem).
+ // On CI we should be okay, because it should download the correct `slang-llvm` for the
+ // build (as it packages up with it). But for normal development, that can easily not be the
+ // case (for example changing to 32 bit build in VS is a problem).
//
- // Make sure to run
+ // Make sure to run
//
// ```
// premake --arch=x86 --deps=true
// ```
//
// for the actual target/arch(!)
-
- const bool hasLlvm = SLANG_SUCCEEDED(slangSession->checkPassThroughSupport(SLANG_PASS_THROUGH_LLVM));
+
+ const bool hasLlvm =
+ SLANG_SUCCEEDED(slangSession->checkPassThroughSupport(SLANG_PASS_THROUGH_LLVM));
SlangPassThrough cppCompiler = SLANG_PASS_THROUGH_NONE;
{
- const SlangPassThrough cppCompilers[] =
- {
+ const SlangPassThrough cppCompilers[] = {
SLANG_PASS_THROUGH_VISUAL_STUDIO,
SLANG_PASS_THROUGH_GCC,
SLANG_PASS_THROUGH_CLANG,
@@ -132,9 +150,15 @@ struct ComTestContext
if (cppCompiler != SLANG_PASS_THROUGH_NONE)
{
slangSession->setDefaultDownstreamCompiler(SLANG_SOURCE_LANGUAGE_CPP, cppCompiler);
-
- slangSession->setDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_SHADER_HOST_CALLABLE, cppCompiler);
- slangSession->setDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_HOST_HOST_CALLABLE, cppCompiler);
+
+ slangSession->setDownstreamCompilerForTransition(
+ SLANG_CPP_SOURCE,
+ SLANG_SHADER_HOST_CALLABLE,
+ cppCompiler);
+ slangSession->setDownstreamCompilerForTransition(
+ SLANG_CPP_SOURCE,
+ SLANG_HOST_HOST_CALLABLE,
+ cppCompiler);
SLANG_RETURN_ON_FAIL(_runTest());
}
@@ -157,14 +181,17 @@ struct ComTestContext
slang::IGlobalSession* slangSession = m_unitTestContext->slangGlobalSession;
slangSession->setDefaultDownstreamCompiler(SLANG_SOURCE_LANGUAGE_CPP, m_defaultCppCompiler);
- slangSession->setDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_SHADER_HOST_CALLABLE, m_shaderHostCallableCompiler);
- slangSession->setDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_HOST_HOST_CALLABLE, m_hostHostCallableCompiler);
+ slangSession->setDownstreamCompilerForTransition(
+ SLANG_CPP_SOURCE,
+ SLANG_SHADER_HOST_CALLABLE,
+ m_shaderHostCallableCompiler);
+ slangSession->setDownstreamCompilerForTransition(
+ SLANG_CPP_SOURCE,
+ SLANG_HOST_HOST_CALLABLE,
+ m_hostHostCallableCompiler);
}
- ~ComTestContext()
- {
- _reset();
- }
+ ~ComTestContext() { _reset(); }
SlangResult _runTest();
@@ -186,9 +213,9 @@ SlangResult ComTestContext::_runTest()
SLANG_ALLOW_DEPRECATED_END
// We want to compile to 'HOST_CALLABLE' here such that we can execute the Slang code.
- //
- // Note that it is possible to use HOST_HOST_CALLABLE, but this currently only works with 'regular' C++ compilers
- // not with `slang-llvm`.
+ //
+ // Note that it is possible to use HOST_HOST_CALLABLE, but this currently only works with
+ // 'regular' C++ compilers not with `slang-llvm`.
const int targetIndex = request->addCodeGenTarget(SLANG_SHADER_HOST_CALLABLE);
// Set the target flag to indicate that we want to compile all into a library.
@@ -198,10 +225,13 @@ SlangResult ComTestContext::_runTest()
request->setDebugInfoLevel(SLANG_DEBUG_INFO_LEVEL_STANDARD);
// Add the translation unit
- const int translationUnitIndex = request->addTranslationUnit(SLANG_SOURCE_LANGUAGE_SLANG, nullptr);
+ const int translationUnitIndex =
+ request->addTranslationUnit(SLANG_SOURCE_LANGUAGE_SLANG, nullptr);
// Set the source file for the translation unit
- request->addTranslationUnitSourceFile(translationUnitIndex, "tools/slang-unit-test/unit-test-com-host-callable.slang");
+ request->addTranslationUnitSourceFile(
+ translationUnitIndex,
+ "tools/slang-unit-test/unit-test-com-host-callable.slang");
const SlangResult compileRes = request->compile();
@@ -214,8 +244,8 @@ SlangResult ComTestContext::_runTest()
printf("%s", diagnostics);
}
- // Get the 'shared library' (note that this doesn't necessarily have to be implemented as a shared library
- // it's just an interface to executable code).
+ // Get the 'shared library' (note that this doesn't necessarily have to be implemented as a
+ // shared library it's just an interface to executable code).
ComPtr<ISlangSharedLibrary> sharedLibrary;
SLANG_RETURN_ON_FAIL(request->getTargetHostCallable(0, sharedLibrary.writeRef()));
@@ -305,7 +335,7 @@ SlangResult ComTestContext::_runTest()
for (Index i = 0; i < 10; ++i)
{
SLANG_CHECK(*counterPtr == &counter);
-
+
const auto v = nextCount();
SLANG_CHECK(v == i);
}
@@ -314,7 +344,7 @@ SlangResult ComTestContext::_runTest()
return SLANG_OK;
}
-} // anonymous
+} // namespace
SLANG_UNIT_TEST(comHostCallable)
{
@@ -322,9 +352,9 @@ SLANG_UNIT_TEST(comHostCallable)
// TODO(JS):
// We can't currently run this test reliably on targets other than windows
// Visual Studio DownstreamCompiler has support for 32 bit builds
- // Other targets generally build for the native environment which is almost always 64 bit,
+ // Other targets generally build for the native environment which is almost always 64 bit,
// and it requires other features to build/test 32 bit binaries on such systems.
- //
+ //
// So we disable for any 32 bit non MS target for now
return;
#endif
@@ -332,6 +362,6 @@ SLANG_UNIT_TEST(comHostCallable)
ComTestContext context(unitTestContext);
const auto result = context.runTests();
-
+
SLANG_CHECK(SLANG_SUCCEEDED(result));
}
diff --git a/tools/slang-unit-test/unit-test-command-line-args.cpp b/tools/slang-unit-test/unit-test-command-line-args.cpp
index a4dc8a16c..febbeaddb 100644
--- a/tools/slang-unit-test/unit-test-command-line-args.cpp
+++ b/tools/slang-unit-test/unit-test-command-line-args.cpp
@@ -1,7 +1,6 @@
// unit-test-command-line-args.cpp
#include "../../source/compiler-core/slang-command-line-args.h"
-
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
@@ -17,9 +16,8 @@ SLANG_UNIT_TEST(commandLineArgs)
DownstreamArgs downstreamArgs(context);
DiagnosticSink sink(context->getSourceManager(), nullptr);
-
- const char* inArgs[] =
- {
+
+ const char* inArgs[] = {
"-Xa...",
"-blah",
"10",
@@ -28,13 +26,10 @@ SLANG_UNIT_TEST(commandLineArgs)
args.setArgs(inArgs, SLANG_COUNT_OF(inArgs));
- SLANG_CHECK(SLANG_SUCCEEDED(downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink)));
+ SLANG_CHECK(SLANG_SUCCEEDED(
+ downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink)));
- const char* aArgs[] =
- {
- "-blah",
- "10"
- };
+ const char* aArgs[] = {"-blah", "10"};
SLANG_CHECK(downstreamArgs.getArgsByName("a").hasArgs(aArgs, SLANG_COUNT_OF(aArgs)));
SLANG_CHECK(args.getArgCount() == 0 && sink.getErrorCount() == 0);
@@ -47,8 +42,7 @@ SLANG_UNIT_TEST(commandLineArgs)
DiagnosticSink sink(context->getSourceManager(), nullptr);
- const char* inArgs[] =
- {
+ const char* inArgs[] = {
"-Xa...",
"-blah",
"10",
@@ -56,13 +50,10 @@ SLANG_UNIT_TEST(commandLineArgs)
args.setArgs(inArgs, SLANG_COUNT_OF(inArgs));
- SLANG_CHECK(SLANG_SUCCEEDED(downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink)));
+ SLANG_CHECK(SLANG_SUCCEEDED(
+ downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink)));
- const char* aArgs[] =
- {
- "-blah",
- "10"
- };
+ const char* aArgs[] = {"-blah", "10"};
SLANG_CHECK(downstreamArgs.getArgsByName("a").hasArgs(aArgs, SLANG_COUNT_OF(aArgs)));
SLANG_CHECK(args.getArgCount() == 0 && sink.getErrorCount() == 0);
@@ -76,8 +67,7 @@ SLANG_UNIT_TEST(commandLineArgs)
DiagnosticSink sink(context->getSourceManager(), nullptr);
- const char* inArgs[] =
- {
+ const char* inArgs[] = {
"-something",
"andAnother",
"-Xa...",
@@ -93,24 +83,16 @@ SLANG_UNIT_TEST(commandLineArgs)
args.setArgs(inArgs, SLANG_COUNT_OF(inArgs));
- SLANG_CHECK(SLANG_SUCCEEDED(downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink)));
+ SLANG_CHECK(SLANG_SUCCEEDED(
+ downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink)));
- const char* aArgs[] =
- {
- "-blah",
- "-Xb...",
- "-hey",
- "-X.",
- "10"
- };
+ const char* aArgs[] = {"-blah", "-Xb...", "-hey", "-X.", "10"};
- const char* cArgs[] =
- {
+ const char* cArgs[] = {
"somethingForC",
};
- const char* mainArgs[] =
- {
+ const char* mainArgs[] = {
"-something",
"andAnother",
};
@@ -120,6 +102,4 @@ SLANG_UNIT_TEST(commandLineArgs)
SLANG_CHECK(args.hasArgs(mainArgs, SLANG_COUNT_OF(mainArgs)) && sink.getErrorCount() == 0);
}
-
}
-
diff --git a/tools/slang-unit-test/unit-test-compression.cpp b/tools/slang-unit-test/unit-test-compression.cpp
index 486a252b2..28f18997f 100644
--- a/tools/slang-unit-test/unit-test-compression.cpp
+++ b/tools/slang-unit-test/unit-test-compression.cpp
@@ -1,8 +1,7 @@
// unit-compression.cpp
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "../../source/core/slang-lz4-compression-system.h"
#include "../../source/core/slang-deflate-compression-system.h"
+#include "../../source/core/slang-lz4-compression-system.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
@@ -10,9 +9,9 @@ static ICompressionSystem* _getCompressionSystem(CompressionSystemType type)
{
switch (type)
{
- case CompressionSystemType::Deflate: return DeflateCompressionSystem::getSingleton(); break;
- case CompressionSystemType::LZ4: return LZ4CompressionSystem::getSingleton(); break;
- default: break;
+ case CompressionSystemType::Deflate: return DeflateCompressionSystem::getSingleton(); break;
+ case CompressionSystemType::LZ4: return LZ4CompressionSystem::getSingleton(); break;
+ default: break;
}
return nullptr;
}
@@ -23,7 +22,7 @@ SLANG_UNIT_TEST(compression)
for (Index i = 0; i < Count(CompressionSystemType::CountOf); ++i)
{
ICompressionSystem* system = _getCompressionSystem(CompressionSystemType(i));
-
+
if (!system)
{
continue;
@@ -37,13 +36,18 @@ SLANG_UNIT_TEST(compression)
// Use the default style
CompressionStyle style;
- SLANG_CHECK(SLANG_SUCCEEDED(system->compress(&style, src, srcSize, compressedBlob.writeRef())));
-
+ SLANG_CHECK(
+ SLANG_SUCCEEDED(system->compress(&style, src, srcSize, compressedBlob.writeRef())));
+
// Now lets decompress
List<char> decompressedData;
decompressedData.setCount(srcSize);
- SLANG_CHECK(SLANG_SUCCEEDED(system->decompress(compressedBlob->getBufferPointer(), compressedBlob->getBufferSize(), srcSize, decompressedData.getBuffer())));
+ SLANG_CHECK(SLANG_SUCCEEDED(system->decompress(
+ compressedBlob->getBufferPointer(),
+ compressedBlob->getBufferSize(),
+ srcSize,
+ decompressedData.getBuffer())));
SLANG_CHECK(::memcmp(src, decompressedData.getBuffer(), srcSize) == 0);
}
}
diff --git a/tools/slang-unit-test/unit-test-crypto.cpp b/tools/slang-unit-test/unit-test-crypto.cpp
index adb7b2218..244f7135b 100644
--- a/tools/slang-unit-test/unit-test-crypto.cpp
+++ b/tools/slang-unit-test/unit-test-crypto.cpp
@@ -1,7 +1,6 @@
// unit-test-sha1.cpp
-#include "tools/unit-test/slang-unit-test.h"
-
#include "../../source/core/slang-crypto.h"
+#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
@@ -29,7 +28,7 @@ SLANG_UNIT_TEST(crypto)
SLANG_CHECK(Digest("0123456789abcdef").toString() == "0123456789abcdef");
Slang::ComPtr<ISlangBlob> blob = Digest("0123456789abcdef").toBlob();
- const uint8_t check[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
+ const uint8_t check[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
SLANG_CHECK(blob->getBufferSize() == 8);
SLANG_CHECK(::memcmp(blob->getBufferPointer(), check, 8) == 0);
@@ -48,7 +47,8 @@ SLANG_UNIT_TEST(crypto)
// One call to update()
{
MD5 sha1;
- const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
+ const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
+ "tempor incididunt ut labore et dolore magna aliqua.");
sha1.update(str.getBuffer(), str.getLength());
auto digest = sha1.finalize();
SLANG_CHECK(digest.toString() == "818c6e601a24f72750da0f6c9b8ebe28");
@@ -57,8 +57,10 @@ SLANG_UNIT_TEST(crypto)
// Two calls to update()
{
MD5 sha1;
- const String str1("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
- const String str2("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.");
+ const String str1("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
+ "tempor incididunt ut labore et dolore magna aliqua.");
+ const String str2("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi "
+ "ut aliquip ex ea commodo consequat.");
sha1.update(str1.getBuffer(), str1.getLength());
sha1.update(str2.getBuffer(), str2.getLength());
auto digest = sha1.finalize();
@@ -68,9 +70,12 @@ SLANG_UNIT_TEST(crypto)
// compute()
{
SLANG_CHECK(MD5::compute(nullptr, 0).toString() == "d41d8cd98f00b204e9800998ecf8427e");
- const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
- SLANG_CHECK(MD5::compute(str.getBuffer(), str.getLength()).toString() == "818c6e601a24f72750da0f6c9b8ebe28");
- }
+ const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
+ "tempor incididunt ut labore et dolore magna aliqua.");
+ SLANG_CHECK(
+ MD5::compute(str.getBuffer(), str.getLength()).toString() ==
+ "818c6e601a24f72750da0f6c9b8ebe28");
+ }
// SHA1
@@ -84,7 +89,8 @@ SLANG_UNIT_TEST(crypto)
// One call to update()
{
SHA1 sha1;
- const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
+ const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
+ "tempor incididunt ut labore et dolore magna aliqua.");
sha1.update(str.getBuffer(), str.getLength());
auto digest = sha1.finalize();
SLANG_CHECK(digest.toString() == "cca0871ecbe200379f0a1e4b46de177e2d62e655");
@@ -93,8 +99,10 @@ SLANG_UNIT_TEST(crypto)
// Two calls to update()
{
SHA1 sha1;
- const String str1("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
- const String str2("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.");
+ const String str1("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
+ "tempor incididunt ut labore et dolore magna aliqua.");
+ const String str2("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi "
+ "ut aliquip ex ea commodo consequat.");
sha1.update(str1.getBuffer(), str1.getLength());
sha1.update(str2.getBuffer(), str2.getLength());
auto digest = sha1.finalize();
@@ -103,9 +111,13 @@ SLANG_UNIT_TEST(crypto)
// compute()
{
- SLANG_CHECK(SHA1::compute(nullptr, 0).toString() == "da39a3ee5e6b4b0d3255bfef95601890afd80709");
- const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
- SLANG_CHECK(SHA1::compute(str.getBuffer(), str.getLength()).toString() == "cca0871ecbe200379f0a1e4b46de177e2d62e655");
+ SLANG_CHECK(
+ SHA1::compute(nullptr, 0).toString() == "da39a3ee5e6b4b0d3255bfef95601890afd80709");
+ const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
+ "tempor incididunt ut labore et dolore magna aliqua.");
+ SLANG_CHECK(
+ SHA1::compute(str.getBuffer(), str.getLength()).toString() ==
+ "cca0871ecbe200379f0a1e4b46de177e2d62e655");
}
// DigestBuider
@@ -169,5 +181,5 @@ SLANG_UNIT_TEST(crypto)
auto digest = builder.finalize();
SLANG_CHECK(digest.toString() == "4ae71336e44bf9bf79d2752e234818a5");
- }
+ }
}
diff --git a/tools/slang-unit-test/unit-test-decl-tree-reflection.cpp b/tools/slang-unit-test/unit-test-decl-tree-reflection.cpp
index 89579c585..cbe0eb80b 100644
--- a/tools/slang-unit-test/unit-test-decl-tree-reflection.cpp
+++ b/tools/slang-unit-test/unit-test-decl-tree-reflection.cpp
@@ -1,15 +1,14 @@
// unit-test-translation-unit-import.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
static String getTypeFullName(slang::TypeReflection* type)
@@ -27,7 +26,8 @@ static void printRefl(slang::DeclReflection* refl, unsigned int level = 0)
{
std::cout << " ";
}
- std::cout<< "[" << names[(unsigned int)refl->getKind()] << "] (" << refl->getChildrenCount() << ")" << std::endl;
+ std::cout << "[" << names[(unsigned int)refl->getKind()] << "] (" << refl->getChildrenCount()
+ << ")" << std::endl;
for (auto* child : refl->getChildren())
{
@@ -101,16 +101,28 @@ SLANG_UNIT_TEST(declTreeReflection)
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef());
+ auto module = session->loadModuleFromSourceString(
+ "m",
+ "m.slang",
+ userSourceBody,
+ diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IEntryPoint> entryPoint;
- module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef());
+ module->findAndCheckEntryPoint(
+ "fragMain",
+ SLANG_STAGE_FRAGMENT,
+ entryPoint.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(entryPoint != nullptr);
ComPtr<slang::IComponentType> compositeProgram;
- slang::IComponentType* components[] = { module, entryPoint.get() };
- session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef());
+ slang::IComponentType* components[] = {module, entryPoint.get()};
+ session->createCompositeComponentType(
+ components,
+ 2,
+ compositeProgram.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(compositeProgram != nullptr);
auto moduleDeclReflection = module->getModuleReflection();
@@ -137,7 +149,9 @@ SLANG_UNIT_TEST(declTreeReflection)
// Second declaration should be a function
auto secondDecl = moduleDeclReflection->getChild(1);
SLANG_CHECK(secondDecl->getKind() == slang::DeclReflection::Kind::Func);
- SLANG_CHECK(secondDecl->getChildrenCount() == 2); // Parameter declarations are children (return type is not)
+ SLANG_CHECK(
+ secondDecl->getChildrenCount() ==
+ 2); // Parameter declarations are children (return type is not)
{
auto funcReflection = secondDecl->asFunction();
@@ -147,7 +161,9 @@ SLANG_UNIT_TEST(declTreeReflection)
SLANG_CHECK(funcReflection->getParameterCount() == 2);
SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(0)->getName()) == "x");
SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == "float");
- SLANG_CHECK(funcReflection->getParameterByIndex(0)->findModifier(slang::Modifier::NoDiff) != nullptr);
+ SLANG_CHECK(
+ funcReflection->getParameterByIndex(0)->findModifier(slang::Modifier::NoDiff) !=
+ nullptr);
SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(1)->getName()) == "y");
SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(1)->getType()) == "int");
@@ -161,13 +177,15 @@ SLANG_UNIT_TEST(declTreeReflection)
auto result = userAttribute->getArgumentValueInt(0, &val);
SLANG_CHECK(result == SLANG_OK);
SLANG_CHECK(val == 1024);
- SLANG_CHECK(funcReflection->findUserAttributeByName(globalSession.get(), "MyFuncProperty") == userAttribute);
+ SLANG_CHECK(
+ funcReflection->findUserAttributeByName(globalSession.get(), "MyFuncProperty") ==
+ userAttribute);
}
// Third declaration should also be a function
auto thirdDecl = moduleDeclReflection->getChild(2);
SLANG_CHECK(thirdDecl->getKind() == slang::DeclReflection::Kind::Func);
- SLANG_CHECK(thirdDecl->getChildrenCount() == 1);
+ SLANG_CHECK(thirdDecl->getChildrenCount() == 1);
{
auto funcReflection = thirdDecl->asFunction();
@@ -175,7 +193,9 @@ SLANG_UNIT_TEST(declTreeReflection)
SLANG_CHECK(UnownedStringSlice(funcReflection->getName()) == "fragMain");
SLANG_CHECK(funcReflection->getParameterCount() == 1);
SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(0)->getName()) == "pos");
- SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == "vector<float,4>");
+ SLANG_CHECK(
+ getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) ==
+ "vector<float,4>");
}
// Sixth declaration should be a generic struct
@@ -187,9 +207,11 @@ SLANG_UNIT_TEST(declTreeReflection)
SLANG_CHECK(UnownedStringSlice(typeParamT->getName()) == "T");
auto typeParamTConstraintCount = genericReflection->getTypeParameterConstraintCount(typeParamT);
SLANG_CHECK(typeParamTConstraintCount == 2);
- auto typeParamTConstraintType1 = genericReflection->getTypeParameterConstraintType(typeParamT, 0);
+ auto typeParamTConstraintType1 =
+ genericReflection->getTypeParameterConstraintType(typeParamT, 0);
SLANG_CHECK(getTypeFullName(typeParamTConstraintType1) == "IArithmetic");
- auto typeParamTConstraintType2 = genericReflection->getTypeParameterConstraintType(typeParamT, 1);
+ auto typeParamTConstraintType2 =
+ genericReflection->getTypeParameterConstraintType(typeParamT, 1);
SLANG_CHECK(getTypeFullName(typeParamTConstraintType2) == "IFloat");
auto innerStruct = genericReflection->getInnerDecl();
@@ -205,7 +227,7 @@ SLANG_UNIT_TEST(declTreeReflection)
{
auto type = compositeProgram->getLayout()->findTypeByName("MyType");
SLANG_CHECK(type != nullptr);
- //SLANG_CHECK(type->getKind() == slang::DeclReflection::Kind::Struct);
+ // SLANG_CHECK(type->getKind() == slang::DeclReflection::Kind::Struct);
SLANG_CHECK(UnownedStringSlice(type->getName()) == "MyType");
auto funcReflection = compositeProgram->getLayout()->findFunctionByNameInType(type, "f");
SLANG_CHECK(funcReflection != nullptr);
@@ -220,7 +242,7 @@ SLANG_UNIT_TEST(declTreeReflection)
{
auto type = compositeProgram->getLayout()->findTypeByName("MyGenericType<half>");
SLANG_CHECK(type != nullptr);
- //SLANG_CHECK(type->getKind() == slang::DeclReflection::Kind::Struct);
+ // SLANG_CHECK(type->getKind() == slang::DeclReflection::Kind::Struct);
SLANG_CHECK(getTypeFullName(type) == "MyGenericType<half>");
auto funcReflection = compositeProgram->getLayout()->findFunctionByNameInType(type, "g");
SLANG_CHECK(funcReflection != nullptr);
@@ -242,85 +264,98 @@ SLANG_UNIT_TEST(declTreeReflection)
SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == "float");
SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(1)->getName()) == "y");
SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(1)->getType()) == "half");
-
+
// Access parent generic container from a specialized method.
auto specializationInfo = funcReflection->getGenericContainer();
SLANG_CHECK(specializationInfo != nullptr);
SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "h");
- SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
+ SLANG_CHECK(
+ specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
// Check type parameters
SLANG_CHECK(specializationInfo->getTypeParameterCount() == 1);
auto typeParam = specializationInfo->getTypeParameter(0);
SLANG_CHECK(UnownedStringSlice(typeParam->getName()) == "U"); // generic name
- SLANG_CHECK(getTypeFullName(specializationInfo->getConcreteType(typeParam)) == "float"); // specialized type name under the context in which the generic is obtained
+ SLANG_CHECK(
+ getTypeFullName(specializationInfo->getConcreteType(typeParam)) ==
+ "float"); // specialized type name under the context in which the generic is obtained
SLANG_CHECK(specializationInfo->getTypeParameterConstraintCount(typeParam) == 0);
// Go up another level to the generic struct
specializationInfo = specializationInfo->getOuterGenericContainer();
SLANG_CHECK(specializationInfo != nullptr);
SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "MyGenericType");
- SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
+ SLANG_CHECK(
+ specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
// Check type parameters
SLANG_CHECK(specializationInfo->getTypeParameterCount() == 1);
typeParam = specializationInfo->getTypeParameter(0);
SLANG_CHECK(UnownedStringSlice(typeParam->getName()) == "T"); // generic name
- SLANG_CHECK(getTypeFullName(specializationInfo->getConcreteType(typeParam)) == "half"); // specialized type name under the context in which the generic is obtained
+ SLANG_CHECK(
+ getTypeFullName(specializationInfo->getConcreteType(typeParam)) ==
+ "half"); // specialized type name under the context in which the generic is obtained
SLANG_CHECK(specializationInfo->getTypeParameterConstraintCount(typeParam) == 2);
// Query 'j' on the type 'half'
funcReflection = compositeProgram->getLayout()->findFunctionByNameInType(type, "j<10>");
SLANG_CHECK(funcReflection != nullptr);
SLANG_CHECK(UnownedStringSlice(funcReflection->getName()) == "j");
-
+
// Check the generic parameters
specializationInfo = funcReflection->getGenericContainer();
SLANG_CHECK(specializationInfo != nullptr);
SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "j");
- SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
+ SLANG_CHECK(
+ specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
SLANG_CHECK(specializationInfo->getValueParameterCount() == 1);
auto valueParam = specializationInfo->getValueParameter(0);
SLANG_CHECK(UnownedStringSlice(valueParam->getName()) == "N"); // generic name
SLANG_CHECK(specializationInfo->getConcreteIntVal(valueParam) == 10);
}
-
+
// Check specializeGeneric() and applySpecializations()
{
auto unspecializedType = compositeProgram->getLayout()->findTypeByName("MyGenericType");
SLANG_CHECK(unspecializedType != nullptr);
auto halfType = compositeProgram->getLayout()->findTypeByName("half");
SLANG_CHECK(halfType != nullptr);
-
+
slang::GenericReflection* genericContainer = unspecializedType->getGenericContainer();
SLANG_CHECK(genericContainer != nullptr);
- //auto typeParamT = genericContainer->getTypeParameter(0);
-
+ // auto typeParamT = genericContainer->getTypeParameter(0);
+
List<slang::GenericArgType> argTypes;
List<slang::GenericArgReflection> args;
argTypes.add(slang::GenericArgType::SLANG_GENERIC_ARG_TYPE);
args.add({halfType});
auto specializedContainer = compositeProgram->getLayout()->specializeGeneric(
- genericContainer, argTypes.getCount(), argTypes.getBuffer(), args.getBuffer(), nullptr);
-
+ genericContainer,
+ argTypes.getCount(),
+ argTypes.getBuffer(),
+ args.getBuffer(),
+ nullptr);
+
SLANG_CHECK(specializedContainer != nullptr);
auto specializedType = unspecializedType->applySpecializations(specializedContainer);
SLANG_CHECK(specializedType != nullptr);
SLANG_CHECK(getTypeFullName(specializedType) == "MyGenericType<half>");
-
}
- // Check specializeGeneric() and applySpecializations() on multiple levels (generic function nested in a generic struct)
+ // Check specializeGeneric() and applySpecializations() on multiple levels (generic function
+ // nested in a generic struct)
{
auto unspecializedType = compositeProgram->getLayout()->findTypeByName("MyGenericType");
- auto unspecializedFunc = compositeProgram->getLayout()->findFunctionByNameInType(unspecializedType, "j");
+ auto unspecializedFunc =
+ compositeProgram->getLayout()->findFunctionByNameInType(unspecializedType, "j");
SLANG_CHECK(unspecializedFunc != nullptr);
auto halfType = compositeProgram->getLayout()->findTypeByName("half");
SLANG_CHECK(halfType != nullptr);
-
+
slang::GenericReflection* genericFuncContainer = unspecializedFunc->getGenericContainer();
SLANG_CHECK(genericFuncContainer != nullptr);
- slang::GenericReflection* genericStructContainer = genericFuncContainer->getOuterGenericContainer();
+ slang::GenericReflection* genericStructContainer =
+ genericFuncContainer->getOuterGenericContainer();
SLANG_CHECK(genericStructContainer != nullptr);
// Specialize the outer container with half
@@ -329,11 +364,16 @@ SLANG_UNIT_TEST(declTreeReflection)
argTypes.add(slang::GenericArgType::SLANG_GENERIC_ARG_TYPE);
args.add({halfType});
auto specializedStructContainer = compositeProgram->getLayout()->specializeGeneric(
- genericStructContainer, argTypes.getCount(), argTypes.getBuffer(), args.getBuffer(), nullptr);
+ genericStructContainer,
+ argTypes.getCount(),
+ argTypes.getBuffer(),
+ args.getBuffer(),
+ nullptr);
SLANG_CHECK(specializedStructContainer != nullptr);
// apply T=half. N is still left unspecialized.
- genericFuncContainer = genericFuncContainer->applySpecializations(specializedStructContainer);
+ genericFuncContainer =
+ genericFuncContainer->applySpecializations(specializedStructContainer);
// Specialize the inner container with 10 separately..
argTypes.clear();
@@ -345,16 +385,21 @@ SLANG_UNIT_TEST(declTreeReflection)
args.add(argN);
auto specializedFuncContainer = compositeProgram->getLayout()->specializeGeneric(
- genericFuncContainer, argTypes.getCount(), argTypes.getBuffer(), args.getBuffer(), nullptr);
+ genericFuncContainer,
+ argTypes.getCount(),
+ argTypes.getBuffer(),
+ args.getBuffer(),
+ nullptr);
auto specializedFunc = unspecializedFunc->applySpecializations(specializedFuncContainer);
SLANG_CHECK(specializedFunc != nullptr);
-
+
// ------ check the specialized function
auto specializationInfo = specializedFunc->getGenericContainer();
SLANG_CHECK(specializationInfo != nullptr);
SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "j");
- SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
+ SLANG_CHECK(
+ specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
SLANG_CHECK(specializationInfo->getValueParameterCount() == 1);
auto valueParam = specializationInfo->getValueParameter(0);
SLANG_CHECK(UnownedStringSlice(valueParam->getName()) == "N"); // generic name
@@ -364,7 +409,8 @@ SLANG_UNIT_TEST(declTreeReflection)
specializationInfo = specializationInfo->getOuterGenericContainer();
SLANG_CHECK(specializationInfo != nullptr);
SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "MyGenericType");
- SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
+ SLANG_CHECK(
+ specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic);
// Check type parameters
SLANG_CHECK(specializationInfo->getTypeParameterCount() == 1);
auto typeParam = specializationInfo->getTypeParameter(0);
@@ -399,15 +445,16 @@ SLANG_UNIT_TEST(declTreeReflection)
argTypes.add(floatType);
argTypes.add(uintType);
- slang::FunctionReflection* specializedFoo = unspecializedFoo->specializeWithArgTypes(argTypes.getCount(), argTypes.getBuffer());
+ slang::FunctionReflection* specializedFoo =
+ unspecializedFoo->specializeWithArgTypes(argTypes.getCount(), argTypes.getBuffer());
SLANG_CHECK(specializedFoo != nullptr);
-
+
SLANG_CHECK(getTypeFullName(specializedFoo->getReturnType()) == "float");
SLANG_CHECK(specializedFoo->getParameterCount() == 2);
SLANG_CHECK(UnownedStringSlice(specializedFoo->getParameterByIndex(0)->getName()) == "t");
SLANG_CHECK(getTypeFullName(specializedFoo->getParameterByIndex(0)->getType()) == "float");
-
+
SLANG_CHECK(UnownedStringSlice(specializedFoo->getParameterByIndex(1)->getName()) == "u");
SLANG_CHECK(getTypeFullName(specializedFoo->getParameterByIndex(1)->getType()) == "uint");
}
@@ -417,7 +464,8 @@ SLANG_UNIT_TEST(declTreeReflection)
auto specializedType = compositeProgram->getLayout()->findTypeByName("MyGenericType<half>");
SLANG_CHECK(specializedType != nullptr);
- auto unspecializedMethod = compositeProgram->getLayout()->findFunctionByNameInType(specializedType, "h");
+ auto unspecializedMethod =
+ compositeProgram->getLayout()->findFunctionByNameInType(specializedType, "h");
SLANG_CHECK(unspecializedMethod != nullptr);
// Specialize the method with float
@@ -431,13 +479,12 @@ SLANG_UNIT_TEST(declTreeReflection)
argTypes.add(floatType);
argTypes.add(halfType);
- auto specializedMethodWithFloat = unspecializedMethod->specializeWithArgTypes(
- argTypes.getCount(),
- argTypes.getBuffer());
+ auto specializedMethodWithFloat =
+ unspecializedMethod->specializeWithArgTypes(argTypes.getCount(), argTypes.getBuffer());
SLANG_CHECK(specializedMethodWithFloat != nullptr);
SLANG_CHECK(getTypeFullName(specializedMethodWithFloat->getReturnType()) == "float");
}
-
+
// Check iterators
{
unsigned int count = 0;
@@ -448,32 +495,35 @@ SLANG_UNIT_TEST(declTreeReflection)
SLANG_CHECK(count == 9);
count = 0;
- for (auto* child : moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Func>())
+ for (auto* child :
+ moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Func>())
{
count++;
}
SLANG_CHECK(count == 3);
count = 0;
- for (auto* child : moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Struct>())
+ for (auto* child :
+ moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Struct>())
{
count++;
}
SLANG_CHECK(count == 2);
count = 0;
- for (auto* child : moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Generic>())
+ for (auto* child :
+ moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Generic>())
{
count++;
}
SLANG_CHECK(count == 2);
count = 0;
- for (auto* child : moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Namespace>())
+ for (auto* child :
+ moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Namespace>())
{
count++;
}
SLANG_CHECK(count == 1);
}
}
-
diff --git a/tools/slang-unit-test/unit-test-default-matrix-layout.cpp b/tools/slang-unit-test/unit-test-default-matrix-layout.cpp
index 540036650..406432321 100644
--- a/tools/slang-unit-test/unit-test-default-matrix-layout.cpp
+++ b/tools/slang-unit-test/unit-test-default-matrix-layout.cpp
@@ -1,24 +1,23 @@
// unit-test-default-matrix-layout.cpp
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "slang.h"
+#include "../../source/core/slang-list.h"
#include "slang-com-helper.h"
#include "slang-com-ptr.h"
+#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
-#include "../../source/core/slang-list.h"
+#include <stdio.h>
+#include <stdlib.h>
-namespace {
+namespace
+{
using namespace Slang;
struct DefaultMatrixLayoutTestContext
{
- DefaultMatrixLayoutTestContext(UnitTestContext* context):
- m_unitTestContext(context)
+ DefaultMatrixLayoutTestContext(UnitTestContext* context)
+ : m_unitTestContext(context)
{
slang::IGlobalSession* slangSession = m_unitTestContext->slangGlobalSession;
}
@@ -36,7 +35,9 @@ struct DefaultMatrixLayoutTestContext
sessionDesc.defaultMatrixLayoutMode = SLANG_MATRIX_LAYOUT_COLUMN_MAJOR;
SLANG_RETURN_ON_FAIL(slangSession->createSession(sessionDesc, session.writeRef()));
- auto module = session->loadModuleFromSourceString("mymodule", "mymodule.slang",
+ auto module = session->loadModuleFromSourceString(
+ "mymodule",
+ "mymodule.slang",
R"(
RWStructuredBuffer<float> output;
[numthreads(1,1,1)] [shader("compute")]
@@ -53,9 +54,10 @@ struct DefaultMatrixLayoutTestContext
if (!entryPoint)
return SLANG_FAIL;
- slang::IComponentType* components[] = { module, entryPoint.get() };
+ slang::IComponentType* components[] = {module, entryPoint.get()};
ComPtr<slang::IComponentType> composedProgram;
- SLANG_RETURN_ON_FAIL(session->createCompositeComponentType(components, 2, composedProgram.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ session->createCompositeComponentType(components, 2, composedProgram.writeRef()));
ComPtr<slang::IComponentType> linkedProgram;
SLANG_RETURN_ON_FAIL(composedProgram->link(linkedProgram.writeRef()));
@@ -72,13 +74,13 @@ struct DefaultMatrixLayoutTestContext
UnitTestContext* m_unitTestContext;
};
-} // anonymous
+} // namespace
SLANG_UNIT_TEST(defaultMatrixLayout)
{
DefaultMatrixLayoutTestContext context(unitTestContext);
const auto result = context.runTests();
-
+
SLANG_CHECK(SLANG_SUCCEEDED(result));
}
diff --git a/tools/slang-unit-test/unit-test-fcpw-compile.cpp b/tools/slang-unit-test/unit-test-fcpw-compile.cpp
index 5e57ea55c..e36052b65 100644
--- a/tools/slang-unit-test/unit-test-fcpw-compile.cpp
+++ b/tools/slang-unit-test/unit-test-fcpw-compile.cpp
@@ -1,15 +1,14 @@
// unit-test-fcpw-compile.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
// A test that uses the COM API to load and compile the FCPW library written by
@@ -35,7 +34,8 @@ SLANG_UNIT_TEST(fcpwCompile)
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModule("tests/fcpw/bvh-traversal.cs.slang", diagnosticBlob.writeRef());
+ auto module =
+ session->loadModule("tests/fcpw/bvh-traversal.cs.slang", diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IEntryPoint> entryPoint;
@@ -43,8 +43,12 @@ SLANG_UNIT_TEST(fcpwCompile)
SLANG_CHECK(entryPoint != nullptr);
ComPtr<slang::IComponentType> compositeProgram;
- slang::IComponentType* components[] = { module, entryPoint.get() };
- session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef());
+ slang::IComponentType* components[] = {module, entryPoint.get()};
+ session->createCompositeComponentType(
+ components,
+ 2,
+ compositeProgram.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(compositeProgram != nullptr);
ComPtr<slang::IComponentType> linkedProgram;
@@ -56,4 +60,3 @@ SLANG_UNIT_TEST(fcpwCompile)
SLANG_CHECK(code != nullptr);
SLANG_CHECK(code->getBufferSize() != 0);
}
-
diff --git a/tools/slang-unit-test/unit-test-file-system.cpp b/tools/slang-unit-test/unit-test-file-system.cpp
index 05892b10b..46061e2d8 100644
--- a/tools/slang-unit-test/unit-test-file-system.cpp
+++ b/tools/slang-unit-test/unit-test-file-system.cpp
@@ -1,530 +1,572 @@
// unit-test-file-system.cpp
+#include "../../source/core/slang-castable.h"
+#include "../../source/core/slang-deflate-compression-system.h"
#include "../../source/core/slang-file-system.h"
-
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-lz4-compression-system.h"
+#include "../../source/core/slang-memory-file-system.h"
#include "../../source/core/slang-riff-file-system.h"
#include "../../source/core/slang-zip-file-system.h"
-
-#include "../../source/core/slang-memory-file-system.h"
-
-#include "../../source/core/slang-deflate-compression-system.h"
-#include "../../source/core/slang-lz4-compression-system.h"
-#include "../../source/core/slang-castable.h"
-
-#include "../../source/core/slang-io.h"
-
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
-namespace { // anonymous
+namespace
+{ // anonymous
enum class FileSystemType
{
- Zip,
- RiffUncompressed,
- RiffDeflate,
- RiffLZ4,
- Memory,
- Relative,
- CountOf,
+ Zip,
+ RiffUncompressed,
+ RiffDeflate,
+ RiffLZ4,
+ Memory,
+ Relative,
+ CountOf,
};
-struct Entry
+struct Entry
{
- typedef Entry ThisType;
+ typedef Entry ThisType;
- bool operator<(const ThisType& rhs) const { return path < rhs.path; }
- bool operator==(const ThisType& rhs) const { return path == rhs.path && type == rhs.type; }
- bool operator!=(const ThisType& rhs) const { return !(*this == rhs); }
+ bool operator<(const ThisType& rhs) const { return path < rhs.path; }
+ bool operator==(const ThisType& rhs) const { return path == rhs.path && type == rhs.type; }
+ bool operator!=(const ThisType& rhs) const { return !(*this == rhs); }
- SlangPathType type;
- String path;
+ SlangPathType type;
+ String path;
};
-} // anonymous
+} // namespace
-static SlangResult _checkFile(ISlangFileSystemExt* fileSystem, const char* path, const UnownedStringSlice& contentsSlice)
+static SlangResult _checkFile(
+ ISlangFileSystemExt* fileSystem,
+ const char* path,
+ const UnownedStringSlice& contentsSlice)
{
- SlangPathType pathType;
- SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType));
-
- if (pathType != SLANG_PATH_TYPE_FILE)
- {
- return SLANG_FAIL;
- }
-
- ComPtr<ISlangBlob> blob;
- SLANG_RETURN_ON_FAIL(fileSystem->loadFile(path, blob.writeRef()));
-
- if (blob->getBufferSize() != contentsSlice.getLength())
- {
- return SLANG_FAIL;
- }
- if (contentsSlice != UnownedStringSlice((const char*)blob->getBufferPointer(), blob->getBufferSize()))
- {
- return SLANG_FAIL;
- }
- return SLANG_OK;
+ SlangPathType pathType;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType));
+
+ if (pathType != SLANG_PATH_TYPE_FILE)
+ {
+ return SLANG_FAIL;
+ }
+
+ ComPtr<ISlangBlob> blob;
+ SLANG_RETURN_ON_FAIL(fileSystem->loadFile(path, blob.writeRef()));
+
+ if (blob->getBufferSize() != contentsSlice.getLength())
+ {
+ return SLANG_FAIL;
+ }
+ if (contentsSlice !=
+ UnownedStringSlice((const char*)blob->getBufferPointer(), blob->getBufferSize()))
+ {
+ return SLANG_FAIL;
+ }
+ return SLANG_OK;
}
-static SlangResult _checkFile(ISlangMutableFileSystem* fileSystem, const char* path, const char* contents)
+static SlangResult _checkFile(
+ ISlangMutableFileSystem* fileSystem,
+ const char* path,
+ const char* contents)
{
- return _checkFile(fileSystem, path, UnownedStringSlice(contents));
+ return _checkFile(fileSystem, path, UnownedStringSlice(contents));
}
static SlangResult _checkDirectoryExists(ISlangFileSystemExt* fileSystem, const char* path)
{
- SlangPathType pathType;
- SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType));
-
- if (pathType != SLANG_PATH_TYPE_DIRECTORY)
- {
- return SLANG_FAIL;
- }
- return SLANG_OK;
+ SlangPathType pathType;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType));
+
+ if (pathType != SLANG_PATH_TYPE_DIRECTORY)
+ {
+ return SLANG_FAIL;
+ }
+ return SLANG_OK;
}
-static SlangResult _createAndCheckFile(ISlangMutableFileSystem* fileSystem, const char* path, const char* contents)
+static SlangResult _createAndCheckFile(
+ ISlangMutableFileSystem* fileSystem,
+ const char* path,
+ const char* contents)
{
- UnownedStringSlice contentsSlice(contents);
+ UnownedStringSlice contentsSlice(contents);
- SLANG_RETURN_ON_FAIL(fileSystem->saveFile(path, contentsSlice.begin(), contentsSlice.getLength()));
- SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, path, contentsSlice));
+ SLANG_RETURN_ON_FAIL(
+ fileSystem->saveFile(path, contentsSlice.begin(), contentsSlice.getLength()));
+ SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, path, contentsSlice));
- // Delete it
- SLANG_RETURN_ON_FAIL(fileSystem->remove(path));
+ // Delete it
+ SLANG_RETURN_ON_FAIL(fileSystem->remove(path));
- // Check it's gone
- SlangPathType pathType;
- if (SLANG_SUCCEEDED(fileSystem->getPathType(path, &pathType)))
- {
- return SLANG_FAIL;
- }
+ // Check it's gone
+ SlangPathType pathType;
+ if (SLANG_SUCCEEDED(fileSystem->getPathType(path, &pathType)))
+ {
+ return SLANG_FAIL;
+ }
- // Save as a blob
- ComPtr<ISlangBlob> blob = RawBlob::create(contentsSlice.begin(), contentsSlice.getLength());
+ // Save as a blob
+ ComPtr<ISlangBlob> blob = RawBlob::create(contentsSlice.begin(), contentsSlice.getLength());
- SLANG_RETURN_ON_FAIL(fileSystem->saveFileBlob(path, blob));
- SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, path, contentsSlice));
+ SLANG_RETURN_ON_FAIL(fileSystem->saveFileBlob(path, blob));
+ SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, path, contentsSlice));
- return SLANG_OK;
+ return SLANG_OK;
}
static bool _areEqual(ISlangBlob* a, ISlangBlob* b)
{
- if (a == b)
- {
- return true;
- }
- if ((!a || !b) || (a->getBufferSize() != b->getBufferSize()))
- {
- return false;
- }
-
- return ::memcmp(a->getBufferPointer(), b->getBufferPointer(), a->getBufferSize()) == 0;
+ if (a == b)
+ {
+ return true;
+ }
+ if ((!a || !b) || (a->getBufferSize() != b->getBufferSize()))
+ {
+ return false;
+ }
+
+ return ::memcmp(a->getBufferPointer(), b->getBufferPointer(), a->getBufferSize()) == 0;
}
-static SlangResult _checkCanonical(ISlangMutableFileSystem* fileSystem, const char*const* paths, Count count)
+static SlangResult _checkCanonical(
+ ISlangMutableFileSystem* fileSystem,
+ const char* const* paths,
+ Count count)
{
- if (count <= 0)
- {
- return SLANG_FAIL;
- }
-
- // The path has to exist to something for canonicalization to be relied upon
- SlangPathType pathType;
- SLANG_RETURN_ON_FAIL(fileSystem->getPathType(paths[0], &pathType));
-
- String canonicalPath;
- {
- ComPtr<ISlangBlob> blob;
- SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Canonical, paths[0], blob.writeRef()));
- canonicalPath = StringUtil::getString(blob);
- }
-
- // The canonicalized path must point to the same thing
- SlangPathType canonicalPathType;
- SLANG_RETURN_ON_FAIL(fileSystem->getPathType(canonicalPath.getBuffer(), &canonicalPathType));
-
- if (canonicalPathType != pathType)
- {
- return SLANG_FAIL;
- }
-
- // If they are the file, being hte same file, they must hold the same data...
- if (pathType == SLANG_PATH_TYPE_FILE)
- {
- ComPtr<ISlangBlob> blob;
- ComPtr<ISlangBlob> canonicalPathBlob;
- SLANG_RETURN_ON_FAIL(fileSystem->loadFile(paths[0], blob.writeRef()));
- SLANG_RETURN_ON_FAIL(fileSystem->loadFile(canonicalPath.getBuffer(), canonicalPathBlob.writeRef()));
-
- if (!_areEqual(blob, canonicalPathBlob))
- {
- return SLANG_FAIL;
- }
- }
-
- for (Index i = 1; i < count; ++i)
- {
- ComPtr<ISlangBlob> blob;
- SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Canonical, paths[i], blob.writeRef()));
- const auto checkPath = StringUtil::getString(blob);
-
- if (checkPath != canonicalPath)
- {
- return SLANG_FAIL;
- }
- }
-
- return SLANG_OK;
+ if (count <= 0)
+ {
+ return SLANG_FAIL;
+ }
+
+ // The path has to exist to something for canonicalization to be relied upon
+ SlangPathType pathType;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPathType(paths[0], &pathType));
+
+ String canonicalPath;
+ {
+ ComPtr<ISlangBlob> blob;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Canonical, paths[0], blob.writeRef()));
+ canonicalPath = StringUtil::getString(blob);
+ }
+
+ // The canonicalized path must point to the same thing
+ SlangPathType canonicalPathType;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPathType(canonicalPath.getBuffer(), &canonicalPathType));
+
+ if (canonicalPathType != pathType)
+ {
+ return SLANG_FAIL;
+ }
+
+ // If they are the file, being hte same file, they must hold the same data...
+ if (pathType == SLANG_PATH_TYPE_FILE)
+ {
+ ComPtr<ISlangBlob> blob;
+ ComPtr<ISlangBlob> canonicalPathBlob;
+ SLANG_RETURN_ON_FAIL(fileSystem->loadFile(paths[0], blob.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ fileSystem->loadFile(canonicalPath.getBuffer(), canonicalPathBlob.writeRef()));
+
+ if (!_areEqual(blob, canonicalPathBlob))
+ {
+ return SLANG_FAIL;
+ }
+ }
+
+ for (Index i = 1; i < count; ++i)
+ {
+ ComPtr<ISlangBlob> blob;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Canonical, paths[i], blob.writeRef()));
+ const auto checkPath = StringUtil::getString(blob);
+
+ if (checkPath != canonicalPath)
+ {
+ return SLANG_FAIL;
+ }
+ }
+
+ return SLANG_OK;
}
static SlangResult _createAndCheckDirectory(ISlangMutableFileSystem* fileSystem, const char* path)
{
- SLANG_RETURN_ON_FAIL(fileSystem->createDirectory(path));
+ SLANG_RETURN_ON_FAIL(fileSystem->createDirectory(path));
- SlangPathType pathType;
- SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType));
+ SlangPathType pathType;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType));
- if (pathType != SLANG_PATH_TYPE_DIRECTORY)
- {
- return SLANG_FAIL;
- }
+ if (pathType != SLANG_PATH_TYPE_DIRECTORY)
+ {
+ return SLANG_FAIL;
+ }
- return SLANG_OK;
+ return SLANG_OK;
}
static void _entryCallback(SlangPathType pathType, const char* name, void* userData)
{
- List<Entry>& out = *(List<Entry>*)userData;
- out.add(Entry{pathType, name});
+ List<Entry>& out = *(List<Entry>*)userData;
+ out.add(Entry{pathType, name});
}
-static SlangResult _enumeratePath(ISlangFileSystemExt* fileSystem, const char* path, const ConstArrayView<Entry>& entries)
+static SlangResult _enumeratePath(
+ ISlangFileSystemExt* fileSystem,
+ const char* path,
+ const ConstArrayView<Entry>& entries)
{
- List<Entry> contents;
-
- SLANG_RETURN_ON_FAIL(fileSystem->enumeratePathContents(path, _entryCallback, (void*)&contents));
-
- contents.sort();
-
- if (contents.getArrayView() != entries)
- {
- return SLANG_FAIL;
- }
-
- return SLANG_OK;
+ List<Entry> contents;
+
+ SLANG_RETURN_ON_FAIL(fileSystem->enumeratePathContents(path, _entryCallback, (void*)&contents));
+
+ contents.sort();
+
+ if (contents.getArrayView() != entries)
+ {
+ return SLANG_FAIL;
+ }
+
+ return SLANG_OK;
}
-static SlangResult _checkSimplifiedPath(ISlangFileSystemExt* fileSystem, const char* path, const char* normalPath)
+static SlangResult _checkSimplifiedPath(
+ ISlangFileSystemExt* fileSystem,
+ const char* path,
+ const char* normalPath)
{
- ComPtr<ISlangBlob> simplifiedPathBlob;
- SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Simplified, path, simplifiedPathBlob.writeRef()));
+ ComPtr<ISlangBlob> simplifiedPathBlob;
+ SLANG_RETURN_ON_FAIL(
+ fileSystem->getPath(PathKind::Simplified, path, simplifiedPathBlob.writeRef()));
- auto simplifiedPath = StringUtil::getString(simplifiedPathBlob);
+ auto simplifiedPath = StringUtil::getString(simplifiedPathBlob);
- if (simplifiedPath != normalPath)
- {
- return SLANG_FAIL;
- }
+ if (simplifiedPath != normalPath)
+ {
+ return SLANG_FAIL;
+ }
- return SLANG_OK;
+ return SLANG_OK;
}
-SlangResult _appendPathEntries(ISlangFileSystemExt* fileSystem, const char* inBasePath, List<Entry>& outEntries)
+SlangResult _appendPathEntries(
+ ISlangFileSystemExt* fileSystem,
+ const char* inBasePath,
+ List<Entry>& outEntries)
{
- const UnownedStringSlice basePath(inBasePath);
- if (basePath == toSlice(".") || basePath.getLength() == 0)
- {
- // We don't need to append path prefixes if we are at the root.
- SLANG_RETURN_ON_FAIL(fileSystem->enumeratePathContents(inBasePath, _entryCallback, (void*)&outEntries));
- }
- else
- {
- const Index startIndex = outEntries.getCount();
- SLANG_RETURN_ON_FAIL(fileSystem->enumeratePathContents(inBasePath, _entryCallback, (void*)&outEntries));
-
- const String basePathString(basePath);
-
- // we need to fix all of the added paths to make absolute
- const Count count = outEntries.getCount();
- for (Index i = startIndex; i < count; ++i)
- {
- auto& entry = outEntries[i];
- entry.path = Path::combine(basePathString, entry.path);
- }
- }
-
- return SLANG_OK;
+ const UnownedStringSlice basePath(inBasePath);
+ if (basePath == toSlice(".") || basePath.getLength() == 0)
+ {
+ // We don't need to append path prefixes if we are at the root.
+ SLANG_RETURN_ON_FAIL(
+ fileSystem->enumeratePathContents(inBasePath, _entryCallback, (void*)&outEntries));
+ }
+ else
+ {
+ const Index startIndex = outEntries.getCount();
+ SLANG_RETURN_ON_FAIL(
+ fileSystem->enumeratePathContents(inBasePath, _entryCallback, (void*)&outEntries));
+
+ const String basePathString(basePath);
+
+ // we need to fix all of the added paths to make absolute
+ const Count count = outEntries.getCount();
+ for (Index i = startIndex; i < count; ++i)
+ {
+ auto& entry = outEntries[i];
+ entry.path = Path::combine(basePathString, entry.path);
+ }
+ }
+
+ return SLANG_OK;
}
-static SlangResult _getAllEntries(ISlangFileSystemExt* fileSystem, const char* inBasePath, List<Entry>& outEntries)
+static SlangResult _getAllEntries(
+ ISlangFileSystemExt* fileSystem,
+ const char* inBasePath,
+ List<Entry>& outEntries)
{
- outEntries.clear();
-
- // Simplify the base
- auto basePath = Path::simplify(inBasePath);
-
- _appendPathEntries(fileSystem, basePath.getBuffer(), outEntries);
-
- for (Index i = 0; i < outEntries.getCount(); ++i)
- {
- // We need to make a copy as outEntries is mutated
- const Entry entry = outEntries[i];
- if (entry.type == SLANG_PATH_TYPE_DIRECTORY)
- {
- _appendPathEntries(fileSystem, entry.path.getBuffer(), outEntries);
- }
- }
-
- // Sort to remove issues with traversal ordering
- outEntries.sort();
- return SLANG_OK;
+ outEntries.clear();
+
+ // Simplify the base
+ auto basePath = Path::simplify(inBasePath);
+
+ _appendPathEntries(fileSystem, basePath.getBuffer(), outEntries);
+
+ for (Index i = 0; i < outEntries.getCount(); ++i)
+ {
+ // We need to make a copy as outEntries is mutated
+ const Entry entry = outEntries[i];
+ if (entry.type == SLANG_PATH_TYPE_DIRECTORY)
+ {
+ _appendPathEntries(fileSystem, entry.path.getBuffer(), outEntries);
+ }
+ }
+
+ // Sort to remove issues with traversal ordering
+ outEntries.sort();
+ return SLANG_OK;
}
static SlangResult _checkEqual(ISlangFileSystemExt* a, ISlangFileSystemExt* b)
{
- List<Entry> aEntries, bEntries;
+ List<Entry> aEntries, bEntries;
- SLANG_RETURN_ON_FAIL(_getAllEntries(a, ".", aEntries));
- SLANG_RETURN_ON_FAIL(_getAllEntries(b, ".", bEntries));
+ SLANG_RETURN_ON_FAIL(_getAllEntries(a, ".", aEntries));
+ SLANG_RETURN_ON_FAIL(_getAllEntries(b, ".", bEntries));
- if (aEntries != bEntries)
- {
- return SLANG_FAIL;
- }
+ if (aEntries != bEntries)
+ {
+ return SLANG_FAIL;
+ }
- // For all the files check the contents is the same
+ // For all the files check the contents is the same
- for (const auto& entry : aEntries)
- {
- if (entry.type != SLANG_PATH_TYPE_FILE)
- {
- continue;
- }
+ for (const auto& entry : aEntries)
+ {
+ if (entry.type != SLANG_PATH_TYPE_FILE)
+ {
+ continue;
+ }
- ComPtr<ISlangBlob> blobA, blobB;
+ ComPtr<ISlangBlob> blobA, blobB;
- SLANG_RETURN_ON_FAIL(a->loadFile(entry.path.getBuffer(), blobA.writeRef()));
- SLANG_RETURN_ON_FAIL(b->loadFile(entry.path.getBuffer(), blobB.writeRef()));
+ SLANG_RETURN_ON_FAIL(a->loadFile(entry.path.getBuffer(), blobA.writeRef()));
+ SLANG_RETURN_ON_FAIL(b->loadFile(entry.path.getBuffer(), blobB.writeRef()));
- if (blobA->getBufferSize() != blobB->getBufferSize())
- {
- return SLANG_FAIL;
- }
+ if (blobA->getBufferSize() != blobB->getBufferSize())
+ {
+ return SLANG_FAIL;
+ }
- if (::memcmp(blobA->getBufferPointer(), blobB->getBufferPointer(), blobA->getBufferSize()) != 0)
- {
- return SLANG_FAIL;
- }
- }
+ if (::memcmp(
+ blobA->getBufferPointer(),
+ blobB->getBufferPointer(),
+ blobA->getBufferSize()) != 0)
+ {
+ return SLANG_FAIL;
+ }
+ }
- return SLANG_OK;
+ return SLANG_OK;
}
-static SlangResult _createFileSystem(FileSystemType type, ComPtr<ISlangMutableFileSystem>& outFileSystem)
+static SlangResult _createFileSystem(
+ FileSystemType type,
+ ComPtr<ISlangMutableFileSystem>& outFileSystem)
{
- outFileSystem.setNull();
- switch (type)
- {
- case FileSystemType::Zip: return ZipFileSystem::create(outFileSystem);
- case FileSystemType::RiffUncompressed: outFileSystem = new RiffFileSystem(nullptr); break;
- case FileSystemType::RiffDeflate: outFileSystem = new RiffFileSystem(DeflateCompressionSystem::getSingleton()); break;
- case FileSystemType::RiffLZ4: outFileSystem = new RiffFileSystem(LZ4CompressionSystem::getSingleton()); break;
- case FileSystemType::Memory: outFileSystem = new MemoryFileSystem; break;
- case FileSystemType::Relative:
- {
- ComPtr<ISlangMutableFileSystem> memoryFileSystem(new MemoryFileSystem);
- memoryFileSystem->createDirectory("base");
-
- outFileSystem = new RelativeFileSystem(memoryFileSystem, "base");
- break;
- }
- }
-
- return outFileSystem ? SLANG_OK : SLANG_FAIL;
+ outFileSystem.setNull();
+ switch (type)
+ {
+ case FileSystemType::Zip: return ZipFileSystem::create(outFileSystem);
+ case FileSystemType::RiffUncompressed: outFileSystem = new RiffFileSystem(nullptr); break;
+ case FileSystemType::RiffDeflate:
+ outFileSystem = new RiffFileSystem(DeflateCompressionSystem::getSingleton());
+ break;
+ case FileSystemType::RiffLZ4:
+ outFileSystem = new RiffFileSystem(LZ4CompressionSystem::getSingleton());
+ break;
+ case FileSystemType::Memory: outFileSystem = new MemoryFileSystem; break;
+ case FileSystemType::Relative:
+ {
+ ComPtr<ISlangMutableFileSystem> memoryFileSystem(new MemoryFileSystem);
+ memoryFileSystem->createDirectory("base");
+
+ outFileSystem = new RelativeFileSystem(memoryFileSystem, "base");
+ break;
+ }
+ }
+
+ return outFileSystem ? SLANG_OK : SLANG_FAIL;
}
static SlangResult _testImplicitDirectory(FileSystemType type)
{
- ComPtr<ISlangMutableFileSystem> fileSystem;
- SLANG_RETURN_ON_FAIL(_createFileSystem(type, fileSystem));
+ ComPtr<ISlangMutableFileSystem> fileSystem;
+ SLANG_RETURN_ON_FAIL(_createFileSystem(type, fileSystem));
- const char contents3[] = "Some text....";
+ const char contents3[] = "Some text....";
- SLANG_RETURN_ON_FAIL(fileSystem->saveFile("implicit-path/file2.txt", contents3, SLANG_COUNT_OF(contents3)));
+ SLANG_RETURN_ON_FAIL(
+ fileSystem->saveFile("implicit-path/file2.txt", contents3, SLANG_COUNT_OF(contents3)));
- {
- SlangPathType pathType;
- SLANG_RETURN_ON_FAIL(fileSystem->getPathType("implicit-path", &pathType));
+ {
+ SlangPathType pathType;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPathType("implicit-path", &pathType));
- SLANG_CHECK(pathType == SLANG_PATH_TYPE_DIRECTORY);
+ SLANG_CHECK(pathType == SLANG_PATH_TYPE_DIRECTORY);
- auto checkEntries = [&]() -> SlangResult
- {
- List<Entry> entries;
- SLANG_RETURN_ON_FAIL(_getAllEntries(fileSystem, "implicit-path", entries));
+ auto checkEntries = [&]() -> SlangResult
+ {
+ List<Entry> entries;
+ SLANG_RETURN_ON_FAIL(_getAllEntries(fileSystem, "implicit-path", entries));
- // It contains a file
- SLANG_CHECK(entries.getCount() == 1);
+ // It contains a file
+ SLANG_CHECK(entries.getCount() == 1);
- for (const auto& entry : entries)
- {
- // All of these should exist
- SlangPathType pathType;
- SLANG_RETURN_ON_FAIL(fileSystem->getPathType(entry.path.getBuffer(), &pathType));
- }
- return SLANG_OK;
- };
+ for (const auto& entry : entries)
+ {
+ // All of these should exist
+ SlangPathType pathType;
+ SLANG_RETURN_ON_FAIL(fileSystem->getPathType(entry.path.getBuffer(), &pathType));
+ }
+ return SLANG_OK;
+ };
- SLANG_RETURN_ON_FAIL(checkEntries());
+ SLANG_RETURN_ON_FAIL(checkEntries());
- // Make an explicit path, and see whe have the same results
- fileSystem->createDirectory("implicit-path");
+ // Make an explicit path, and see whe have the same results
+ fileSystem->createDirectory("implicit-path");
- SLANG_RETURN_ON_FAIL(checkEntries());
- }
+ SLANG_RETURN_ON_FAIL(checkEntries());
+ }
- return SLANG_OK;
+ return SLANG_OK;
}
static SlangResult _test(FileSystemType type)
{
- ComPtr<ISlangMutableFileSystem> fileSystem;
- SLANG_RETURN_ON_FAIL(_createFileSystem(type, fileSystem));
-
- const auto aText = "someText";
- const auto bText = "A longer bit of text....";
- const auto d_aText = "Some more silly stuff";
- const auto d_bText = "Lets go!";
-
- SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "a", aText));
- SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "b", bText));
-
- SLANG_RETURN_ON_FAIL(_createAndCheckDirectory(fileSystem, "d"));
- SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "d/a", d_aText));
- SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "d\\b", d_bText));
-
- // Try and absolute path
- SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/a", aText));
- SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/b", bText));
- SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/d/a", d_aText));
- SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/d\\b", d_bText));
-
-
- // Check canonical on files
- {
- const char* paths[] = { "a", "/a", "./a", "d/../a", ".\\d/.\\..\\a" };
- SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths)));
- }
-
- {
- const char* paths[] = { "/d/b", "d/./b" };
- SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths)));
- }
-
- // Check canonical on directories
- {
- const char* paths[] = { ".", "/", "/d/..", "d/.." };
- SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths)));
- }
-
- {
- const char* paths[] = { "d", "./d", "/d", "/d/./../d" };
- SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths)));
- }
-
- // Lets find all the files in the directory
-
- {
- const Entry entries[] = { {SLANG_PATH_TYPE_FILE, "a" }, {SLANG_PATH_TYPE_FILE, "b" } };
- SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView(entries)));
- }
-
- {
- const Entry entries[] = { {SLANG_PATH_TYPE_FILE, "a" }, {SLANG_PATH_TYPE_FILE, "b" }, {SLANG_PATH_TYPE_DIRECTORY, "d" } };
- SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, ".", makeConstArrayView(entries)));
-
- // Let's check that / and \ works for the root directory
- SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "/", makeConstArrayView(entries)));
- SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "\\", makeConstArrayView(entries)));
- }
-
- // Check the root directory exists
- {
- SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "."));
- SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "/"));
- SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "\\"));
- }
-
- {
- SLANG_RETURN_ON_FAIL(_checkSimplifiedPath(fileSystem, "d/../a", "a"));
- }
-
-
- // If we have an archive file system check out it's behavior
- if (IArchiveFileSystem* archiveFileSystem = as<IArchiveFileSystem>(fileSystem))
- {
- // Load and check its okay
-
- ComPtr<ISlangBlob> archiveBlob;
- SLANG_RETURN_ON_FAIL(archiveFileSystem->storeArchive(false, archiveBlob.writeRef()));
-
- ComPtr<ISlangFileSystemExt> loadedFileSystem;
- SLANG_RETURN_ON_FAIL(loadArchiveFileSystem(archiveBlob->getBufferPointer(), archiveBlob->getBufferSize(), loadedFileSystem));
-
- // Check the file systems contents are the same
- SLANG_RETURN_ON_FAIL(_checkEqual(loadedFileSystem, fileSystem));
- }
-
- SLANG_RETURN_ON_FAIL(fileSystem->remove("d/a"));
- {
- const Entry entries[] = { {SLANG_PATH_TYPE_FILE, "b" } };
- SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView(entries)));
- }
- SLANG_RETURN_ON_FAIL(fileSystem->remove("d\\b"));
- {
- SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView((const Entry*)nullptr, 0)));
- }
-
- // If it's removed it can't be removed again
- SLANG_CHECK(SLANG_FAILED(fileSystem->remove("d\\b")));
-
- // Remove the directory
- SLANG_RETURN_ON_FAIL(fileSystem->remove("d"));
-
- {
- const Entry entries[] = { {SLANG_PATH_TYPE_FILE, "a" }, {SLANG_PATH_TYPE_FILE, "b" } };
- SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, ".", makeConstArrayView(entries)));
- }
-
- return SLANG_OK;
+ ComPtr<ISlangMutableFileSystem> fileSystem;
+ SLANG_RETURN_ON_FAIL(_createFileSystem(type, fileSystem));
+
+ const auto aText = "someText";
+ const auto bText = "A longer bit of text....";
+ const auto d_aText = "Some more silly stuff";
+ const auto d_bText = "Lets go!";
+
+ SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "a", aText));
+ SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "b", bText));
+
+ SLANG_RETURN_ON_FAIL(_createAndCheckDirectory(fileSystem, "d"));
+ SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "d/a", d_aText));
+ SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "d\\b", d_bText));
+
+ // Try and absolute path
+ SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/a", aText));
+ SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/b", bText));
+ SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/d/a", d_aText));
+ SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/d\\b", d_bText));
+
+
+ // Check canonical on files
+ {
+ const char* paths[] = {"a", "/a", "./a", "d/../a", ".\\d/.\\..\\a"};
+ SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths)));
+ }
+
+ {
+ const char* paths[] = {"/d/b", "d/./b"};
+ SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths)));
+ }
+
+ // Check canonical on directories
+ {
+ const char* paths[] = {".", "/", "/d/..", "d/.."};
+ SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths)));
+ }
+
+ {
+ const char* paths[] = {"d", "./d", "/d", "/d/./../d"};
+ SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths)));
+ }
+
+ // Lets find all the files in the directory
+
+ {
+ const Entry entries[] = {{SLANG_PATH_TYPE_FILE, "a"}, {SLANG_PATH_TYPE_FILE, "b"}};
+ SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView(entries)));
+ }
+
+ {
+ const Entry entries[] = {
+ {SLANG_PATH_TYPE_FILE, "a"},
+ {SLANG_PATH_TYPE_FILE, "b"},
+ {SLANG_PATH_TYPE_DIRECTORY, "d"}};
+ SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, ".", makeConstArrayView(entries)));
+
+ // Let's check that / and \ works for the root directory
+ SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "/", makeConstArrayView(entries)));
+ SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "\\", makeConstArrayView(entries)));
+ }
+
+ // Check the root directory exists
+ {
+ SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "."));
+ SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "/"));
+ SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "\\"));
+ }
+
+ {
+ SLANG_RETURN_ON_FAIL(_checkSimplifiedPath(fileSystem, "d/../a", "a"));
+ }
+
+
+ // If we have an archive file system check out it's behavior
+ if (IArchiveFileSystem* archiveFileSystem = as<IArchiveFileSystem>(fileSystem))
+ {
+ // Load and check its okay
+
+ ComPtr<ISlangBlob> archiveBlob;
+ SLANG_RETURN_ON_FAIL(archiveFileSystem->storeArchive(false, archiveBlob.writeRef()));
+
+ ComPtr<ISlangFileSystemExt> loadedFileSystem;
+ SLANG_RETURN_ON_FAIL(loadArchiveFileSystem(
+ archiveBlob->getBufferPointer(),
+ archiveBlob->getBufferSize(),
+ loadedFileSystem));
+
+ // Check the file systems contents are the same
+ SLANG_RETURN_ON_FAIL(_checkEqual(loadedFileSystem, fileSystem));
+ }
+
+ SLANG_RETURN_ON_FAIL(fileSystem->remove("d/a"));
+ {
+ const Entry entries[] = {{SLANG_PATH_TYPE_FILE, "b"}};
+ SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView(entries)));
+ }
+ SLANG_RETURN_ON_FAIL(fileSystem->remove("d\\b"));
+ {
+ SLANG_RETURN_ON_FAIL(
+ _enumeratePath(fileSystem, "d", makeConstArrayView((const Entry*)nullptr, 0)));
+ }
+
+ // If it's removed it can't be removed again
+ SLANG_CHECK(SLANG_FAILED(fileSystem->remove("d\\b")));
+
+ // Remove the directory
+ SLANG_RETURN_ON_FAIL(fileSystem->remove("d"));
+
+ {
+ const Entry entries[] = {{SLANG_PATH_TYPE_FILE, "a"}, {SLANG_PATH_TYPE_FILE, "b"}};
+ SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, ".", makeConstArrayView(entries)));
+ }
+
+ return SLANG_OK;
}
SLANG_UNIT_TEST(fileSystem)
{
- for (Index i = 0; i < Count(FileSystemType::CountOf); ++i)
- {
- const auto type = FileSystemType(i);
-
- SLANG_CHECK(SLANG_SUCCEEDED(_test(type)));
-
- // Some file system types support 'implicit directories'.
- // This means that if a file is created with a path, the directories
- // required to make that path valid are 'implicitly' created.
- //
- // Currently this behavior is supported by zip, and this test checks
- // that it is working correctly, as we require the file system to
- // behave correctly in other ways irrespectively of if the directory is
- // implicit or not.
- const bool hasImplicitDirectory = (type == FileSystemType::Zip);
- if (hasImplicitDirectory)
- {
- SLANG_CHECK(SLANG_SUCCEEDED(_testImplicitDirectory(type)));
- }
- }
+ for (Index i = 0; i < Count(FileSystemType::CountOf); ++i)
+ {
+ const auto type = FileSystemType(i);
+
+ SLANG_CHECK(SLANG_SUCCEEDED(_test(type)));
+
+ // Some file system types support 'implicit directories'.
+ // This means that if a file is created with a path, the directories
+ // required to make that path valid are 'implicitly' created.
+ //
+ // Currently this behavior is supported by zip, and this test checks
+ // that it is working correctly, as we require the file system to
+ // behave correctly in other ways irrespectively of if the directory is
+ // implicit or not.
+ const bool hasImplicitDirectory = (type == FileSystemType::Zip);
+ if (hasImplicitDirectory)
+ {
+ SLANG_CHECK(SLANG_SUCCEEDED(_testImplicitDirectory(type)));
+ }
+ }
}
-
diff --git a/tools/slang-unit-test/unit-test-find-check-entrypoint.cpp b/tools/slang-unit-test/unit-test-find-check-entrypoint.cpp
index 122f26ddd..717b937d1 100644
--- a/tools/slang-unit-test/unit-test-find-check-entrypoint.cpp
+++ b/tools/slang-unit-test/unit-test-find-check-entrypoint.cpp
@@ -1,18 +1,17 @@
// unit-test-translation-unit-import.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
-// Test that the IModule::findAndCheckEntryPoint API supports discovering
+// Test that the IModule::findAndCheckEntryPoint API supports discovering
// entrypoints without a [shader] attribute.
SLANG_UNIT_TEST(findAndCheckEntryPoint)
@@ -39,16 +38,28 @@ SLANG_UNIT_TEST(findAndCheckEntryPoint)
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef());
+ auto module = session->loadModuleFromSourceString(
+ "m",
+ "m.slang",
+ userSourceBody,
+ diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IEntryPoint> entryPoint;
- module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef());
+ module->findAndCheckEntryPoint(
+ "fragMain",
+ SLANG_STAGE_FRAGMENT,
+ entryPoint.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(entryPoint != nullptr);
ComPtr<slang::IComponentType> compositeProgram;
- slang::IComponentType* components[] = { module, entryPoint.get() };
- session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef());
+ slang::IComponentType* components[] = {module, entryPoint.get()};
+ session->createCompositeComponentType(
+ components,
+ 2,
+ compositeProgram.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(compositeProgram != nullptr);
ComPtr<slang::IComponentType> linkedProgram;
@@ -60,4 +71,3 @@ SLANG_UNIT_TEST(findAndCheckEntryPoint)
SLANG_CHECK(code != nullptr);
SLANG_CHECK(code->getBufferSize() != 0);
}
-
diff --git a/tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp b/tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp
index addada5b6..6cf2ffd17 100644
--- a/tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp
+++ b/tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp
@@ -1,15 +1,14 @@
// unit-test-find-entrypoint-nested.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
// Test that the IModule::findAndCheckEntryPoint API works with modules that
@@ -52,16 +51,28 @@ SLANG_UNIT_TEST(findEntryPointNested)
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef());
+ auto module = session->loadModuleFromSourceString(
+ "m",
+ "m.slang",
+ userSourceBody,
+ diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IEntryPoint> entryPoint;
- module->findAndCheckEntryPoint("outer", SLANG_STAGE_RAY_GENERATION, entryPoint.writeRef(), diagnosticBlob.writeRef());
+ module->findAndCheckEntryPoint(
+ "outer",
+ SLANG_STAGE_RAY_GENERATION,
+ entryPoint.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(entryPoint != nullptr);
ComPtr<slang::IComponentType> compositeProgram;
- slang::IComponentType* components[] = { module, entryPoint.get() };
- session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef());
+ slang::IComponentType* components[] = {module, entryPoint.get()};
+ session->createCompositeComponentType(
+ components,
+ 2,
+ compositeProgram.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(compositeProgram != nullptr);
ComPtr<slang::IComponentType> linkedProgram;
@@ -73,4 +84,3 @@ SLANG_UNIT_TEST(findEntryPointNested)
SLANG_CHECK(code != nullptr);
SLANG_CHECK(code->getBufferSize() != 0);
}
-
diff --git a/tools/slang-unit-test/unit-test-find-type-by-name.cpp b/tools/slang-unit-test/unit-test-find-type-by-name.cpp
index ee6ba3516..a42b08ade 100644
--- a/tools/slang-unit-test/unit-test-find-type-by-name.cpp
+++ b/tools/slang-unit-test/unit-test-find-type-by-name.cpp
@@ -1,21 +1,19 @@
// unit-test-find-type-by-name.cpp
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-
using namespace Slang;
SLANG_UNIT_TEST(findTypeByName)
{
- const char* testSource =
- "struct TestStruct {"
- " int member0;"
- " Texture2D texture1;"
- "};";
+ const char* testSource = "struct TestStruct {"
+ " int member0;"
+ " Texture2D texture1;"
+ "};";
auto session = spCreateSession();
auto request = spCreateCompileRequest(session);
spAddCodeGenTarget(request, SLANG_DXBC);
@@ -44,7 +42,8 @@ SLANG_UNIT_TEST(findTypeByName)
auto paramBlockElementType = paramBlockType->getElementType();
SLANG_CHECK_ABORT(paramBlockElementType != nullptr);
auto paramBlockElementTypeName = paramBlockElementType->getName();
- SLANG_CHECK_ABORT(paramBlockElementTypeName && strcmp(paramBlockElementTypeName, "TestStruct") == 0);
+ SLANG_CHECK_ABORT(
+ paramBlockElementTypeName && strcmp(paramBlockElementTypeName, "TestStruct") == 0);
};
testBody();
@@ -52,4 +51,3 @@ SLANG_UNIT_TEST(findTypeByName)
spDestroyCompileRequest(request);
spDestroySession(session);
}
-
diff --git a/tools/slang-unit-test/unit-test-free-list.cpp b/tools/slang-unit-test/unit-test-free-list.cpp
index d6c8b47a7..80cd01dc1 100644
--- a/tools/slang-unit-test/unit-test-free-list.cpp
+++ b/tools/slang-unit-test/unit-test-free-list.cpp
@@ -1,15 +1,13 @@
// unit-test-free-list.cpp
#include "../../source/core/slang-free-list.h"
+#include "../../source/core/slang-list.h"
+#include "../../source/core/slang-random-generator.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "../../source/core/slang-random-generator.h"
-#include "../../source/core/slang-list.h"
-
using namespace Slang;
SLANG_UNIT_TEST(freeList)
@@ -24,7 +22,7 @@ SLANG_UNIT_TEST(freeList)
for (int i = 0; i < 1000; i++)
{
const int numAlloc = randGen.nextInt32UpTo(20);
-
+
for (int j = 0; j < numAlloc; j++)
{
int* ptr = (int*)freeList.allocate();
@@ -50,4 +48,3 @@ SLANG_UNIT_TEST(freeList)
}
}
}
-
diff --git a/tools/slang-unit-test/unit-test-function-reflection.cpp b/tools/slang-unit-test/unit-test-function-reflection.cpp
index f893da69d..2d62bd761 100644
--- a/tools/slang-unit-test/unit-test-function-reflection.cpp
+++ b/tools/slang-unit-test/unit-test-function-reflection.cpp
@@ -1,15 +1,14 @@
// unit-test-translation-unit-import.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
static String getTypeFullName(slang::TypeReflection* type)
@@ -59,19 +58,30 @@ SLANG_UNIT_TEST(functionReflection)
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef());
+ auto module = session->loadModuleFromSourceString(
+ "m",
+ "m.slang",
+ userSourceBody,
+ diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IEntryPoint> entryPoint;
- module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef());
+ module->findAndCheckEntryPoint(
+ "fragMain",
+ SLANG_STAGE_FRAGMENT,
+ entryPoint.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(entryPoint != nullptr);
auto entryPointFuncReflection = entryPoint->getFunctionReflection();
SLANG_CHECK(entryPointFuncReflection != nullptr);
SLANG_CHECK(UnownedStringSlice(entryPointFuncReflection->getName()) == "fragMain");
SLANG_CHECK(entryPointFuncReflection->getParameterCount() == 1);
- SLANG_CHECK(UnownedStringSlice(entryPointFuncReflection->getParameterByIndex(0)->getName()) == "pos");
- SLANG_CHECK(getTypeFullName(entryPointFuncReflection->getParameterByIndex(0)->getType()) == "vector<float,4>");
+ SLANG_CHECK(
+ UnownedStringSlice(entryPointFuncReflection->getParameterByIndex(0)->getName()) == "pos");
+ SLANG_CHECK(
+ getTypeFullName(entryPointFuncReflection->getParameterByIndex(0)->getType()) ==
+ "vector<float,4>");
auto funcReflection = module->getLayout()->findFunctionByName("ordinaryFunc");
SLANG_CHECK(funcReflection != nullptr);
@@ -82,7 +92,8 @@ SLANG_UNIT_TEST(functionReflection)
SLANG_CHECK(funcReflection->getParameterCount() == 2);
SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(0)->getName()) == "x");
SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == "float");
- SLANG_CHECK(funcReflection->getParameterByIndex(0)->findModifier(slang::Modifier::NoDiff) != nullptr);
+ SLANG_CHECK(
+ funcReflection->getParameterByIndex(0)->findModifier(slang::Modifier::NoDiff) != nullptr);
SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(1)->getName()) == "y");
SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(1)->getType()) == "int");
@@ -96,7 +107,9 @@ SLANG_UNIT_TEST(functionReflection)
auto result = userAttribute->getArgumentValueInt(0, &val);
SLANG_CHECK(result == SLANG_OK);
SLANG_CHECK(val == 1024);
- SLANG_CHECK(funcReflection->findUserAttributeByName(globalSession.get(), "MyFuncProperty") == userAttribute);
+ SLANG_CHECK(
+ funcReflection->findUserAttributeByName(globalSession.get(), "MyFuncProperty") ==
+ userAttribute);
// Check overloaded method resolution
auto overloadReflection = module->getLayout()->findFunctionByName("foo");
@@ -129,7 +142,7 @@ SLANG_UNIT_TEST(functionReflection)
//
// More testing for specializeWithArgTypes
- //
+ //
// bar1 (IFloat, IFloat) -> int
//
@@ -144,11 +157,13 @@ SLANG_UNIT_TEST(functionReflection)
argTypes[1] = float3Type;
resolvedFunctionReflection = bar1Reflection->specializeWithArgTypes(2, argTypes);
-
+
SLANG_CHECK(resolvedFunctionReflection != nullptr);
SLANG_CHECK(resolvedFunctionReflection->getParameterCount() == 2);
- SLANG_CHECK(getTypeFullName(resolvedFunctionReflection->getParameterByIndex(0)->getType()) == "IFloat");
- SLANG_CHECK(getTypeFullName(resolvedFunctionReflection->getParameterByIndex(1)->getType()) == "IFloat");
+ SLANG_CHECK(
+ getTypeFullName(resolvedFunctionReflection->getParameterByIndex(0)->getType()) == "IFloat");
+ SLANG_CHECK(
+ getTypeFullName(resolvedFunctionReflection->getParameterByIndex(1)->getType()) == "IFloat");
// bar2 (T : IFloat, float3) -> int
//
@@ -166,8 +181,11 @@ SLANG_UNIT_TEST(functionReflection)
SLANG_CHECK(resolvedFunctionReflection != nullptr);
SLANG_CHECK(resolvedFunctionReflection->getParameterCount() == 2);
- SLANG_CHECK(getTypeFullName(resolvedFunctionReflection->getParameterByIndex(0)->getType()) == "float");
- SLANG_CHECK(getTypeFullName(resolvedFunctionReflection->getParameterByIndex(1)->getType()) == "vector<float,3>");
+ SLANG_CHECK(
+ getTypeFullName(resolvedFunctionReflection->getParameterByIndex(0)->getType()) == "float");
+ SLANG_CHECK(
+ getTypeFullName(resolvedFunctionReflection->getParameterByIndex(1)->getType()) ==
+ "vector<float,3>");
// failure case
@@ -188,4 +206,3 @@ SLANG_UNIT_TEST(functionReflection)
SLANG_CHECK(resolvedFunctionReflection != nullptr);
SLANG_CHECK(resolvedFunctionReflection == bar3Reflection);
}
-
diff --git a/tools/slang-unit-test/unit-test-generic-interface-conformance.cpp b/tools/slang-unit-test/unit-test-generic-interface-conformance.cpp
index 740d13bef..df5e6e63a 100644
--- a/tools/slang-unit-test/unit-test-generic-interface-conformance.cpp
+++ b/tools/slang-unit-test/unit-test-generic-interface-conformance.cpp
@@ -1,18 +1,17 @@
// unit-test-translation-unit-import.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
-// Test that the IModule::findAndCheckEntryPoint API supports discovering
+// Test that the IModule::findAndCheckEntryPoint API supports discovering
// entrypoints without a [shader] attribute.
SLANG_UNIT_TEST(genericInterfaceConformance)
@@ -56,26 +55,38 @@ SLANG_UNIT_TEST(genericInterfaceConformance)
sessionDesc.targetCount = 1;
sessionDesc.targets = &targetDesc;
sessionDesc.allowGLSLSyntax = true;
-
+
ComPtr<slang::ISession> session;
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef());
+ auto module = session->loadModuleFromSourceString(
+ "m",
+ "m.slang",
+ userSourceBody,
+ diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IEntryPoint> entryPoint;
- module->findAndCheckEntryPoint("computeMain", SLANG_STAGE_COMPUTE, entryPoint.writeRef(), diagnosticBlob.writeRef());
+ module->findAndCheckEntryPoint(
+ "computeMain",
+ SLANG_STAGE_COMPUTE,
+ entryPoint.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(entryPoint != nullptr);
ComPtr<slang::IComponentType> compositeProgram;
- slang::IComponentType* components[] = { module, entryPoint.get() };
- session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef());
+ slang::IComponentType* components[] = {module, entryPoint.get()};
+ session->createCompositeComponentType(
+ components,
+ 2,
+ compositeProgram.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(compositeProgram != nullptr);
ComPtr<slang::ITypeConformance> typeConformance;
- auto result = session->createTypeConformanceComponentType(
- compositeProgram->getLayout()->findTypeByName("TestInterfaceImpl<float>"),
+ auto result = session->createTypeConformanceComponentType(
+ compositeProgram->getLayout()->findTypeByName("TestInterfaceImpl<float>"),
compositeProgram->getLayout()->findTypeByName("ITestInterface<float>"),
typeConformance.writeRef(),
3,
@@ -84,9 +95,12 @@ SLANG_UNIT_TEST(genericInterfaceConformance)
SLANG_CHECK(typeConformance != nullptr);
ComPtr<slang::IComponentType> compositeProgram2;
- slang::IComponentType* components2[] = { compositeProgram.get(), typeConformance.get() };
+ slang::IComponentType* components2[] = {compositeProgram.get(), typeConformance.get()};
session->createCompositeComponentType(
- components2, 2, compositeProgram2.writeRef(), diagnosticBlob.writeRef());
+ components2,
+ 2,
+ compositeProgram2.writeRef(),
+ diagnosticBlob.writeRef());
ComPtr<slang::IComponentType> linkedProgram;
compositeProgram2->link(linkedProgram.writeRef(), diagnosticBlob.writeRef());
@@ -99,4 +113,3 @@ SLANG_UNIT_TEST(genericInterfaceConformance)
auto codeSrc = UnownedStringSlice((const char*)code->getBufferPointer());
SLANG_CHECK(codeSrc.indexOf(toSlice("computeMain")) != -1);
}
-
diff --git a/tools/slang-unit-test/unit-test-get-target-code.cpp b/tools/slang-unit-test/unit-test-get-target-code.cpp
index 7cb51c91b..f3df15b64 100644
--- a/tools/slang-unit-test/unit-test-get-target-code.cpp
+++ b/tools/slang-unit-test/unit-test-get-target-code.cpp
@@ -1,15 +1,14 @@
// unit-test-translation-unit-import.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
// Test that the IComponentType::getTargetCode API supports
@@ -47,7 +46,11 @@ SLANG_UNIT_TEST(getTargetCode)
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef());
+ auto module = session->loadModuleFromSourceString(
+ "m",
+ "m.slang",
+ userSourceBody,
+ diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IComponentType> linkedProgram;
@@ -66,4 +69,3 @@ SLANG_UNIT_TEST(getTargetCode)
SLANG_CHECK(resultStr.indexOf(toSlice("fragMain")) != -1);
SLANG_CHECK(resultStr.indexOf(toSlice("vertMain")) != -1);
}
-
diff --git a/tools/slang-unit-test/unit-test-image-format-reflection.cpp b/tools/slang-unit-test/unit-test-image-format-reflection.cpp
index 34678472c..66d18b3e0 100644
--- a/tools/slang-unit-test/unit-test-image-format-reflection.cpp
+++ b/tools/slang-unit-test/unit-test-image-format-reflection.cpp
@@ -1,15 +1,14 @@
// unit-test-image-format-reflection.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
// Test that the getBindingRangeImageFormat API works.
@@ -39,20 +38,31 @@ SLANG_UNIT_TEST(imageFormatReflection)
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef());
+ auto module = session->loadModuleFromSourceString(
+ "m",
+ "m.slang",
+ userSourceBody,
+ diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IEntryPoint> entryPoint;
- module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef());
+ module->findAndCheckEntryPoint(
+ "fragMain",
+ SLANG_STAGE_FRAGMENT,
+ entryPoint.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(entryPoint != nullptr);
ComPtr<slang::IComponentType> compositeProgram;
- slang::IComponentType* components[] = { module, entryPoint.get() };
- session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef());
+ slang::IComponentType* components[] = {module, entryPoint.get()};
+ session->createCompositeComponentType(
+ components,
+ 2,
+ compositeProgram.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(compositeProgram != nullptr);
auto layout = compositeProgram->getLayout(0);
auto format = layout->getGlobalParamsTypeLayout()->getBindingRangeImageFormat(0);
SLANG_CHECK(format == SLANG_IMAGE_FORMAT_rgba32ui);
}
-
diff --git a/tools/slang-unit-test/unit-test-io.cpp b/tools/slang-unit-test/unit-test-io.cpp
index fbac5af17..0e6cab94d 100644
--- a/tools/slang-unit-test/unit-test-io.cpp
+++ b/tools/slang-unit-test/unit-test-io.cpp
@@ -1,7 +1,6 @@
// unit-test-io.cpp
#include "../../source/core/slang-io.h"
-
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
@@ -9,7 +8,7 @@ using namespace Slang;
static SlangResult _checkGenerateTemporary()
{
/// Test temporary file functionality
-
+
List<String> paths;
for (Index i = 0; i < 10; ++i)
@@ -47,7 +46,7 @@ static SlangResult _checkGenerateTemporary()
for (auto& path : paths)
{
SLANG_CHECK(File::exists(path));
-
+
const auto removeResult = File::remove(path);
SLANG_CHECK(SLANG_SUCCEEDED(removeResult));
diff --git a/tools/slang-unit-test/unit-test-json-native.cpp b/tools/slang-unit-test/unit-test-json-native.cpp
index 546131e4b..de5b7cfa4 100644
--- a/tools/slang-unit-test/unit-test-json-native.cpp
+++ b/tools/slang-unit-test/unit-test-json-native.cpp
@@ -1,21 +1,20 @@
// unit-test-json-native.cpp
-#include "../../source/core/slang-rtti-info.h"
-
#include "../../source/compiler-core/slang-json-native.h"
#include "../../source/compiler-core/slang-json-parser.h"
-
+#include "../../source/core/slang-rtti-info.h"
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
-namespace { // anonymous
+namespace
+{ // anonymous
struct OtherStruct
{
typedef OtherStruct ThisType;
- bool operator==(const ThisType& rhs) const { return f == rhs.f && value == rhs.value; }
+ bool operator==(const ThisType& rhs) const { return f == rhs.f && value == rhs.value; }
bool operator!=(const ThisType& rhs) const { return !(*this == rhs); }
float f = 1.0f;
@@ -32,7 +31,7 @@ static const StructRttiInfo _makeOtherStructRtti()
builder.addField("value", &obj.value);
return builder.make();
}
-/* static */const StructRttiInfo OtherStruct::g_rttiInfo = _makeOtherStructRtti();
+/* static */ const StructRttiInfo OtherStruct::g_rttiInfo = _makeOtherStructRtti();
struct SomeStruct
{
@@ -40,13 +39,9 @@ struct SomeStruct
bool operator==(const ThisType& rhs) const
{
- return a == rhs.a &&
- b == rhs.b &&
- s == rhs.s &&
- list == rhs.list &&
- boolValue == rhs.boolValue &&
- structList == rhs.structList &&
- makeConstArrayView(fixedArray) == makeConstArrayView(rhs.fixedArray);
+ return a == rhs.a && b == rhs.b && s == rhs.s && list == rhs.list &&
+ boolValue == rhs.boolValue && structList == rhs.structList &&
+ makeConstArrayView(fixedArray) == makeConstArrayView(rhs.fixedArray);
}
bool operator!=(const ThisType& rhs) const { return !(*this == rhs); }
@@ -58,7 +53,7 @@ struct SomeStruct
List<OtherStruct> structList;
- int fixedArray[2] = { 0, 0 };
+ int fixedArray[2] = {0, 0};
static const StructRttiInfo g_rttiInfo;
};
@@ -78,9 +73,9 @@ static const StructRttiInfo _makeSomeStructRtti()
return builder.make();
}
-/* static */const StructRttiInfo SomeStruct::g_rttiInfo = _makeSomeStructRtti();
+/* static */ const StructRttiInfo SomeStruct::g_rttiInfo = _makeSomeStructRtti();
-} // anonymous
+} // namespace
static SlangResult _check()
@@ -107,7 +102,7 @@ static SlangResult _check()
DiagnosticSink sink(&sourceManager, &JSONLexer::calcLexemeLocation);
- auto typeMap = JSONNativeUtil::getTypeFuncsMap();
+ auto typeMap = JSONNativeUtil::getTypeFuncsMap();
RefPtr<JSONContainer> container(new JSONContainer(&sourceManager));
@@ -129,7 +124,8 @@ static SlangResult _check()
{
// Now need to parse as JSON
String contents(json);
- SourceFile* sourceFile = sourceManager.createSourceFileWithString(PathInfo::makeUnknown(), contents);
+ SourceFile* sourceFile =
+ sourceManager.createSourceFileWithString(PathInfo::makeUnknown(), contents);
SourceView* sourceView = sourceManager.createSourceView(sourceFile, nullptr, SourceLoc());
JSONLexer lexer;
@@ -149,7 +145,8 @@ static SlangResult _check()
{
SomeStruct readS;
- SLANG_RETURN_ON_FAIL(converter.convert(readValue, GetRttiInfo<SomeStruct>::get(), &readS));
+ SLANG_RETURN_ON_FAIL(
+ converter.convert(readValue, GetRttiInfo<SomeStruct>::get(), &readS));
// Should be equal
SLANG_CHECK(readS == s);
@@ -162,5 +159,4 @@ static SlangResult _check()
SLANG_UNIT_TEST(JSONNative)
{
SLANG_CHECK(SLANG_SUCCEEDED(_check()));
-
}
diff --git a/tools/slang-unit-test/unit-test-json.cpp b/tools/slang-unit-test/unit-test-json.cpp
index b861465c8..532777030 100644
--- a/tools/slang-unit-test/unit-test-json.cpp
+++ b/tools/slang-unit-test/unit-test-json.cpp
@@ -1,14 +1,14 @@
#include "../../source/compiler-core/slang-json-lexer.h"
-#include "../../source/core/slang-string-escape-util.h"
#include "../../source/compiler-core/slang-json-parser.h"
#include "../../source/compiler-core/slang-json-value.h"
-
+#include "../../source/core/slang-string-escape-util.h"
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
-namespace { // anonymous
+namespace
+{ // anonymous
struct Element
{
@@ -16,14 +16,15 @@ struct Element
const char* value;
};
-} // anonymous
+} // namespace
static SlangResult _lex(const char* in, DiagnosticSink* sink, List<JSONToken>& toks)
{
SourceManager* sourceManager = sink->getSourceManager();
String contents(in);
- SourceFile* sourceFile = sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), contents);
+ SourceFile* sourceFile =
+ sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), contents);
SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc());
JSONLexer lexer;
@@ -55,7 +56,8 @@ static SlangResult _parse(const char* in, DiagnosticSink* sink, JSONListener* li
SourceManager* sourceManager = sink->getSourceManager();
String contents(in);
- SourceFile* sourceFile = sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), contents);
+ SourceFile* sourceFile =
+ sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), contents);
SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc());
JSONLexer lexer;
@@ -66,7 +68,11 @@ static SlangResult _parse(const char* in, DiagnosticSink* sink, JSONListener* li
return SLANG_OK;
}
-static bool _areEqual(SourceManager* sourceManager, const List<JSONToken>& toks, const Element* eles, Index elesCount)
+static bool _areEqual(
+ SourceManager* sourceManager,
+ const List<JSONToken>& toks,
+ const Element* eles,
+ Index elesCount)
{
if (toks.getCount() != elesCount)
{
@@ -74,7 +80,7 @@ static bool _areEqual(SourceManager* sourceManager, const List<JSONToken>& toks,
}
SourceView* sourceView = toks.getCount() ? sourceManager->findSourceView(toks[0].loc) : nullptr;
- const char*const content = sourceView ? sourceView->getContent().begin() : nullptr;
+ const char* const content = sourceView ? sourceView->getContent().begin() : nullptr;
for (Index i = 0; i < toks.getCount(); ++i)
{
@@ -108,32 +114,32 @@ SLANG_UNIT_TEST(json)
DiagnosticSink sink(&sourceManager, nullptr);
{
- const char text[] = " { \"Hello\" : [ \"World\", 1, 2.0, -3.0, -435.5345435, 45e-10, 421.00e+20, 17e1] }";
+ const char text[] =
+ " { \"Hello\" : [ \"World\", 1, 2.0, -3.0, -435.5345435, 45e-10, 421.00e+20, 17e1] }";
- const Element eles[] =
- {
- {JSONTokenType::LBrace, "{" },
+ const Element eles[] = {
+ {JSONTokenType::LBrace, "{"},
{JSONTokenType::StringLiteral, "\"Hello\""},
- {JSONTokenType::Colon, ":" },
- {JSONTokenType::LBracket, "[" },
- {JSONTokenType::StringLiteral, "\"World\"" },
- {JSONTokenType::Comma, "," },
- {JSONTokenType::IntegerLiteral, "1" },
- {JSONTokenType::Comma, "," },
- {JSONTokenType::FloatLiteral, "2.0" },
- {JSONTokenType::Comma, "," },
- {JSONTokenType::FloatLiteral, "-3.0" },
- {JSONTokenType::Comma, "," },
- {JSONTokenType::FloatLiteral, "-435.5345435" },
- {JSONTokenType::Comma, "," },
- {JSONTokenType::FloatLiteral, "45e-10" },
- {JSONTokenType::Comma, "," },
- {JSONTokenType::FloatLiteral, "421.00e+20" },
- {JSONTokenType::Comma, "," },
- {JSONTokenType::FloatLiteral, "17e1" },
- {JSONTokenType::RBracket, "]" },
- {JSONTokenType::RBrace, "}" },
- {JSONTokenType::EndOfFile, "" },
+ {JSONTokenType::Colon, ":"},
+ {JSONTokenType::LBracket, "["},
+ {JSONTokenType::StringLiteral, "\"World\""},
+ {JSONTokenType::Comma, ","},
+ {JSONTokenType::IntegerLiteral, "1"},
+ {JSONTokenType::Comma, ","},
+ {JSONTokenType::FloatLiteral, "2.0"},
+ {JSONTokenType::Comma, ","},
+ {JSONTokenType::FloatLiteral, "-3.0"},
+ {JSONTokenType::Comma, ","},
+ {JSONTokenType::FloatLiteral, "-435.5345435"},
+ {JSONTokenType::Comma, ","},
+ {JSONTokenType::FloatLiteral, "45e-10"},
+ {JSONTokenType::Comma, ","},
+ {JSONTokenType::FloatLiteral, "421.00e+20"},
+ {JSONTokenType::Comma, ","},
+ {JSONTokenType::FloatLiteral, "17e1"},
+ {JSONTokenType::RBracket, "]"},
+ {JSONTokenType::RBrace, "}"},
+ {JSONTokenType::EndOfFile, ""},
};
List<JSONToken> toks;
@@ -145,7 +151,7 @@ SLANG_UNIT_TEST(json)
{
StringEscapeHandler* handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::JSON);
-
+
{
const auto slice = UnownedStringSlice::fromLiteral("\n\r\b\f\t \"\\/ Some text...");
@@ -173,8 +179,9 @@ SLANG_UNIT_TEST(json)
{
const uint32_t digitValue = (v >> ((3 - i) * 4)) & 0xf;
- char digitC = (digitValue > 9) ? char(digitValue - 10 + 'a') : char(digitValue + '0');
- work[i + 2] = digitC;
+ char digitC =
+ (digitValue > 9) ? char(digitValue - 10 + 'a') : char(digitValue + '0');
+ work[i + 2] = digitC;
}
buf << UnownedStringSlice(work, 6);
@@ -241,7 +248,6 @@ SLANG_UNIT_TEST(json)
}
SLANG_CHECK(container->areEqual(value, copy));
-
}
}
@@ -254,7 +260,7 @@ SLANG_UNIT_TEST(json)
for (Int i = 0; i < 100; ++i)
{
-
+
values.add(JSONValue::makeInt(i));
values.add(JSONValue::makeFloat(-double(i)));
}
@@ -266,11 +272,14 @@ SLANG_UNIT_TEST(json)
SLANG_CHECK(arrayView.getCount() == values.getCount());
// Check the values are the same
- SLANG_CHECK(container->areEqual(arrayView.getBuffer(), values.getBuffer(), arrayView.getCount()));
+ SLANG_CHECK(container->areEqual(
+ arrayView.getBuffer(),
+ values.getBuffer(),
+ arrayView.getCount()));
{
JSONWriter writer(JSONWriter::IndentationStyle::KNR, 80);
-
+
container->traverseRecursively(array, &writer);
}
}
@@ -296,7 +305,7 @@ SLANG_UNIT_TEST(json)
RefPtr<JSONContainer> container = new JSONContainer(&sourceManager);
const char aText[] = "{ \"a\" : 10, \"b\" : 20.0, \"a\" : \"Hello\" }";
-
+
JSONBuilder builder(container);
SLANG_CHECK(SLANG_SUCCEEDED(_parse(aText, &sink, &builder)));
const JSONValue a = builder.getRootValue();
@@ -319,7 +328,8 @@ SLANG_UNIT_TEST(json)
{
RefPtr<JSONContainer> container = new JSONContainer(&sourceManager);
- const char aText[] = "{ \"a\" : \"Hi!\", \"b\" : 20.0, \"c\" : \"Hello\", \"d\" : 30, \"e\": null, \"f\": true }";
+ const char aText[] = "{ \"a\" : \"Hi!\", \"b\" : 20.0, \"c\" : \"Hello\", \"d\" : 30, "
+ "\"e\": null, \"f\": true }";
JSONBuilder builder(container);
SLANG_CHECK(SLANG_SUCCEEDED(_parse(aText, &sink, &builder)));
@@ -329,7 +339,7 @@ SLANG_UNIT_TEST(json)
for (char c = 'a'; c <= 'f'; c++)
{
- const char name[] = { c, 0 };
+ const char name[] = {c, 0};
JSONKey key = container->getKey(UnownedStringSlice(name, 1));
auto value = container->findObjectValue(rootValue, key);
@@ -357,4 +367,3 @@ SLANG_UNIT_TEST(json)
SLANG_CHECK(values[5].asBool() == true);
}
}
-
diff --git a/tools/slang-unit-test/unit-test-lock-file.cpp b/tools/slang-unit-test/unit-test-lock-file.cpp
index 4915770fe..5ef9fa036 100644
--- a/tools/slang-unit-test/unit-test-lock-file.cpp
+++ b/tools/slang-unit-test/unit-test-lock-file.cpp
@@ -1,8 +1,7 @@
// unit-test-lock-file.cpp
-#include "tools/unit-test/slang-unit-test.h"
-
#include "../../source/core/slang-io.h"
#include "../../source/core/slang-process.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <atomic>
#include <future>
@@ -11,7 +10,9 @@
using namespace Slang;
-static const String fileName = Path::simplify(Path::getParentDirectory(Path::getExecutablePath()) + "/test_lock_file" + String(Process::getId()));
+static const String fileName = Path::simplify(
+ Path::getParentDirectory(Path::getExecutablePath()) + "/test_lock_file" +
+ String(Process::getId()));
SLANG_UNIT_TEST(lockFileOpenClose)
{
@@ -86,8 +87,8 @@ SLANG_UNIT_TEST(lockFileSync)
SLANG_CHECK(lockFile2.tryLock(LockFile::LockType::Exclusive) == SLANG_E_TIME_OUT);
// Start a number of threads and wait for them to start up.
- // Each thread immediately tries to acquire the lock in non-blocking mode (expected to fail).
- // Next each thread acquires the lock in blocking mode.
+ // Each thread immediately tries to acquire the lock in non-blocking mode (expected to
+ // fail). Next each thread acquires the lock in blocking mode.
std::vector<LockTask> tasks(32);
for (auto& task : tasks)
{
diff --git a/tools/slang-unit-test/unit-test-memory-arena.cpp b/tools/slang-unit-test/unit-test-memory-arena.cpp
index b2671160a..beb19b28b 100644
--- a/tools/slang-unit-test/unit-test-memory-arena.cpp
+++ b/tools/slang-unit-test/unit-test-memory-arena.cpp
@@ -1,15 +1,13 @@
// unit-test-free-list.cpp
+#include "../../source/core/slang-list.h"
#include "../../source/core/slang-memory-arena.h"
+#include "../../source/core/slang-random-generator.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "../../source/core/slang-random-generator.h"
-#include "../../source/core/slang-list.h"
-
using namespace Slang;
@@ -32,21 +30,17 @@ enum class TestMode
eCount,
};
-} // anonymous
+} // namespace
static size_t getAlignment(TestMode mode)
{
switch (mode)
{
- default:
- case TestMode::eUnaligned:
- return 1;
- case TestMode::eExplicitAligned:
- return 16;
- case TestMode::eImplicitAligned:
- return 32;
- case TestMode::eDefaultAligned:
- return MemoryArena::kMinAlignment;
+ default:
+ case TestMode::eUnaligned: return 1;
+ case TestMode::eExplicitAligned: return 16;
+ case TestMode::eImplicitAligned: return 32;
+ case TestMode::eDefaultAligned: return MemoryArena::kMinAlignment;
}
}
@@ -129,7 +123,7 @@ SLANG_UNIT_TEST(memoryArena)
arena.reset();
{
- uint32_t data[] = { 1, 2, 3 };
+ uint32_t data[] = {1, 2, 3};
const uint32_t* copy = arena.allocateAndCopyArray(data, SLANG_COUNT_OF(data));
@@ -141,7 +135,8 @@ SLANG_UNIT_TEST(memoryArena)
int count = 0;
const size_t blockSize = 1024;
- for (TestMode mode = TestMode(0); int(mode) < int(TestMode::eCount); mode = TestMode(int(mode) + 1))
+ for (TestMode mode = TestMode(0); int(mode) < int(TestMode::eCount);
+ mode = TestMode(int(mode) + 1))
{
const size_t alignment = getAlignment(mode);
@@ -162,7 +157,7 @@ SLANG_UNIT_TEST(memoryArena)
// Deallocate everything
arena.deallocateAll();
blocks.clear();
- }
+ }
else if (var == 2)
{
arena.reset();
@@ -181,7 +176,6 @@ SLANG_UNIT_TEST(memoryArena)
arena.rewindToCursor(blocks[rewindIndex].m_data);
// All the blocks (includign this one) and now deallocated
blocks.setCount(rewindIndex);
-
}
else
{
@@ -202,7 +196,7 @@ SLANG_UNIT_TEST(memoryArena)
}
else if ((randGen.nextInt32() & 0xff) < 2)
{
- // Let's try for a block that's awkwardly sized
+ // Let's try for a block that's awkwardly sized
sizeInBytes = blockSize / 3 + 10;
}
@@ -211,25 +205,25 @@ SLANG_UNIT_TEST(memoryArena)
void* mem = nullptr;
switch (mode)
{
- default:
- case TestMode::eUnaligned:
+ default:
+ case TestMode::eUnaligned:
{
mem = arena.allocateUnaligned(sizeInBytes);
break;
}
- case TestMode::eImplicitAligned:
+ case TestMode::eImplicitAligned:
{
// Fix the size to get implicit alignment
sizeInBytes = (sizeInBytes & ~(alignment - 1)) + alignment;
mem = arena.allocateUnaligned(sizeInBytes);
break;
}
- case TestMode::eExplicitAligned:
+ case TestMode::eExplicitAligned:
{
mem = arena.allocateAligned(sizeInBytes, alignment);
break;
}
- case TestMode::eDefaultAligned:
+ case TestMode::eDefaultAligned:
{
mem = arena.allocate(sizeInBytes);
break;
@@ -264,8 +258,5 @@ SLANG_UNIT_TEST(memoryArena)
}
{
// Do lots of allocations and test out rewind
-
-
-
}
}
diff --git a/tools/slang-unit-test/unit-test-offset-container.cpp b/tools/slang-unit-test/unit-test-offset-container.cpp
index 9d8e3a9ff..90f187282 100644
--- a/tools/slang-unit-test/unit-test-offset-container.cpp
+++ b/tools/slang-unit-test/unit-test-offset-container.cpp
@@ -1,7 +1,6 @@
// unit-test-offset-container.cpp
#include "../../source/core/slang-offset-container.h"
-
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
@@ -19,16 +18,17 @@ static void _checkEncodeDecode(uint32_t size)
SLANG_CHECK(chars - (const char*)encode == encodeSize);
}
-namespace { // anonymous
+namespace
+{ // anonymous
struct Root
{
- Offset32Array<Offset32Ptr<OffsetString> > dirs;
+ Offset32Array<Offset32Ptr<OffsetString>> dirs;
Offset32Ptr<OffsetString> name;
float value;
};
-} // anonymous
+} // namespace
SLANG_UNIT_TEST(offsetContainer)
{
@@ -41,9 +41,8 @@ SLANG_UNIT_TEST(offsetContainer)
{
OffsetContainer container;
-
- const char* strings[] =
- {
+
+ const char* strings[] = {
"Hello",
"World",
nullptr,
@@ -65,7 +64,7 @@ SLANG_UNIT_TEST(offsetContainer)
{
List<uint8_t> copy;
copy.addRange(container.getData(), container.getDataCount());
-
+
MemoryOffsetBase base;
base.set(copy.getBuffer(), copy.getCount());
@@ -109,7 +108,7 @@ SLANG_UNIT_TEST(offsetContainer)
SLANG_CHECK(str == nullptr);
}
- index ++;
+ index++;
}
}
}
diff --git a/tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp b/tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp
index 911bdc5a4..c437ae2a2 100644
--- a/tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp
+++ b/tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp
@@ -1,15 +1,14 @@
// unit-test-parameter-usage-reflection.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
// Test that the isParameterLocationUsed API works.
@@ -40,16 +39,28 @@ SLANG_UNIT_TEST(isParameterLocationUsedReflection)
SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK);
ComPtr<slang::IBlob> diagnosticBlob;
- auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef());
+ auto module = session->loadModuleFromSourceString(
+ "m",
+ "m.slang",
+ userSourceBody,
+ diagnosticBlob.writeRef());
SLANG_CHECK(module != nullptr);
ComPtr<slang::IEntryPoint> entryPoint;
- module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef());
+ module->findAndCheckEntryPoint(
+ "fragMain",
+ SLANG_STAGE_FRAGMENT,
+ entryPoint.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(entryPoint != nullptr);
ComPtr<slang::IComponentType> compositeProgram;
- slang::IComponentType* components[] = { module, entryPoint.get() };
- session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef());
+ slang::IComponentType* components[] = {module, entryPoint.get()};
+ session->createCompositeComponentType(
+ components,
+ 2,
+ compositeProgram.writeRef(),
+ diagnosticBlob.writeRef());
SLANG_CHECK(compositeProgram != nullptr);
ComPtr<slang::IComponentType> linkedProgram;
@@ -65,4 +76,3 @@ SLANG_UNIT_TEST(isParameterLocationUsedReflection)
metadata->isParameterLocationUsed(SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT, 0, 1, isUsed);
SLANG_CHECK(!isUsed);
}
-
diff --git a/tools/slang-unit-test/unit-test-path.cpp b/tools/slang-unit-test/unit-test-path.cpp
index c27feee9c..d96acd4f7 100644
--- a/tools/slang-unit-test/unit-test-path.cpp
+++ b/tools/slang-unit-test/unit-test-path.cpp
@@ -1,7 +1,6 @@
// unit-test-path.cpp
#include "../../source/core/slang-io.h"
-
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
@@ -37,7 +36,9 @@ SLANG_UNIT_TEST(path)
SLANG_CHECK(Path::simplify("a:\\what\\..\\.\\..\\is\\.\\..\\this\\.\\") == "a:/../this");
- SLANG_CHECK(Path::simplify("tests/preprocessor/.\\pragma-once-a.h") == "tests/preprocessor/pragma-once-a.h");
+ SLANG_CHECK(
+ Path::simplify("tests/preprocessor/.\\pragma-once-a.h") ==
+ "tests/preprocessor/pragma-once-a.h");
SLANG_CHECK(Path::hasRelativeElement("."));
@@ -55,8 +56,5 @@ SLANG_UNIT_TEST(path)
SLANG_CHECK(Path::hasRelativeElement("a:/what/.././../is/./../this/./"));
SLANG_CHECK(Path::hasRelativeElement("a:\\what\\..\\.\\..\\is\\.\\..\\this\\.\\"));
-
-
}
}
-
diff --git a/tools/slang-unit-test/unit-test-persistent-cache.cpp b/tools/slang-unit-test/unit-test-persistent-cache.cpp
index cb7ebcab2..fa5d286f2 100644
--- a/tools/slang-unit-test/unit-test-persistent-cache.cpp
+++ b/tools/slang-unit-test/unit-test-persistent-cache.cpp
@@ -1,18 +1,17 @@
// unit-test-persistent-cache.cpp
-#include "tools/unit-test/slang-unit-test.h"
-
-#include "../../source/core/slang-persistent-cache.h"
-#include "../../source/core/slang-io.h"
#include "../../source/core/slang-file-system.h"
-#include "../../source/core/slang-random-generator.h"
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-persistent-cache.h"
#include "../../source/core/slang-process.h"
+#include "../../source/core/slang-random-generator.h"
+#include "tools/unit-test/slang-unit-test.h"
-#include <chrono>
-#include <thread>
#include <atomic>
-#include <mutex>
+#include <chrono>
#include <condition_variable>
#include <functional>
+#include <mutex>
+#include <thread>
using namespace Slang;
@@ -28,19 +27,17 @@ inline ComPtr<ISlangBlob> createRandomBlob(size_t size)
inline bool isBlobEqual(ISlangBlob* a, ISlangBlob* b)
{
- return
- a->getBufferSize() == b->getBufferSize() &&
- ::memcmp(a->getBufferPointer(), b->getBufferPointer(), a->getBufferSize()) == 0;
+ return a->getBufferSize() == b->getBufferSize() &&
+ ::memcmp(a->getBufferPointer(), b->getBufferPointer(), a->getBufferSize()) == 0;
}
class Barrier
{
public:
Barrier(size_t threadCount, std::function<void()> completionFunc = nullptr)
- : m_threadCount(threadCount)
- , m_waitCount(threadCount)
- , m_completionFunc(completionFunc)
- {}
+ : m_threadCount(threadCount), m_waitCount(threadCount), m_completionFunc(completionFunc)
+ {
+ }
Barrier(const Barrier& barrier) = delete;
Barrier& operator=(const Barrier& barrier) = delete;
@@ -53,14 +50,15 @@ public:
if (--m_waitCount == 0)
{
- if (m_completionFunc) m_completionFunc();
+ if (m_completionFunc)
+ m_completionFunc();
++m_generation;
m_waitCount = m_threadCount;
m_condition.notify_all();
}
else
{
- m_condition.wait(lock, [this, generation] () { return generation != m_generation; });
+ m_condition.wait(lock, [this, generation]() { return generation != m_generation; });
}
}
@@ -87,7 +85,9 @@ struct PersistentCacheTest
PersistentCacheTest(Count maxEntryCount = 0)
{
osFileSystem = OSFileSystem::getMutableSingleton();
- cacheDirectory = Path::simplify(Path::getParentDirectory(Path::getExecutablePath()) + "/persistent-cache-test" + String(Process::getId()));
+ cacheDirectory = Path::simplify(
+ Path::getParentDirectory(Path::getExecutablePath()) + "/persistent-cache-test" +
+ String(Process::getId()));
removeCacheFiles();
@@ -153,16 +153,10 @@ struct PersistentCacheTest
}
// Get the absolute filename for a cache entry file.
- String getEntryFileName(const Entry& entry)
- {
- return cache->getEntryFileName(entry.key);
- }
+ String getEntryFileName(const Entry& entry) { return cache->getEntryFileName(entry.key); }
// Get the absolute filename of the cache index file.
- String getIndexFilename()
- {
- return cache->m_indexFileName;
- }
+ String getIndexFilename() { return cache->m_indexFileName; }
};
} // namespace Slang
@@ -174,7 +168,10 @@ struct PersistentCacheTest
// - resetting stats
struct BasicTest : public PersistentCacheTest
{
- BasicTest() : PersistentCacheTest() {}
+ BasicTest()
+ : PersistentCacheTest()
+ {
+ }
void run()
{
@@ -189,7 +186,7 @@ struct BasicTest : public PersistentCacheTest
{
auto data = createRandomBlob(i * 1024);
auto key = SHA1::compute(data->getBufferPointer(), data->getBufferSize());
- entries.add(Entry{ key, data });
+ entries.add(Entry{key, data});
}
for (size_t i = 0; i < 10; ++i)
@@ -251,7 +248,10 @@ struct BasicTest : public PersistentCacheTest
// Tests the least-recently-used cache eviction policy.
struct EvictionTest : public PersistentCacheTest
{
- EvictionTest() : PersistentCacheTest(3) {}
+ EvictionTest()
+ : PersistentCacheTest(3)
+ {
+ }
void run()
{
@@ -261,7 +261,7 @@ struct EvictionTest : public PersistentCacheTest
{
auto data = createRandomBlob(4096);
auto key = SHA1::compute(data->getBufferPointer(), data->getBufferSize());
- entries.add(Entry{ key, data });
+ entries.add(Entry{key, data});
}
writeEntry(entries[0]);
@@ -335,8 +335,8 @@ struct CorruptionTest : public PersistentCacheTest
{
auto data = createRandomBlob(4096);
auto key = SHA1::compute(data->getBufferPointer(), data->getBufferSize());
- entries.add(Entry{ key, data });
- }
+ entries.add(Entry{key, data});
+ }
// Test behavior when a cached entry file is removed externally before reading.
writeEntry(entries[0]);
@@ -372,17 +372,18 @@ struct CorruptionTest : public PersistentCacheTest
// Test different corruptions of the index file.
testIndexCorruption(
- [this]()
- {
- osFileSystem->remove(getIndexFilename().getBuffer());
- },
+ [this]() { osFileSystem->remove(getIndexFilename().getBuffer()); },
SLANG_E_NOT_FOUND);
testIndexCorruption(
[this]()
{
FileStream fs;
- fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite);
+ fs.init(
+ getIndexFilename(),
+ FileMode::Open,
+ FileAccess::ReadWrite,
+ FileShare::ReadWrite);
fs.write("x", 1);
},
SLANG_E_INTERNAL_FAIL);
@@ -391,7 +392,11 @@ struct CorruptionTest : public PersistentCacheTest
[this]()
{
FileStream fs;
- fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite);
+ fs.init(
+ getIndexFilename(),
+ FileMode::Open,
+ FileAccess::ReadWrite,
+ FileShare::ReadWrite);
fs.seek(SeekOrigin::Start, 4);
uint32_t version = 0xffffffff;
fs.write(&version, sizeof(version));
@@ -402,7 +407,11 @@ struct CorruptionTest : public PersistentCacheTest
[this]()
{
FileStream fs;
- fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite);
+ fs.init(
+ getIndexFilename(),
+ FileMode::Open,
+ FileAccess::ReadWrite,
+ FileShare::ReadWrite);
fs.seek(SeekOrigin::Start, 8);
uint32_t count = 0x7fffffff;
fs.write(&count, sizeof(count));
@@ -413,7 +422,11 @@ struct CorruptionTest : public PersistentCacheTest
[this]()
{
FileStream fs;
- fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite);
+ fs.init(
+ getIndexFilename(),
+ FileMode::Open,
+ FileAccess::ReadWrite,
+ FileShare::ReadWrite);
fs.seek(SeekOrigin::Start, 8);
uint32_t count = 0;
fs.write(&count, sizeof(count));
@@ -424,7 +437,11 @@ struct CorruptionTest : public PersistentCacheTest
[this]()
{
FileStream fs;
- fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite);
+ fs.init(
+ getIndexFilename(),
+ FileMode::Open,
+ FileAccess::ReadWrite,
+ FileShare::ReadWrite);
fs.seek(SeekOrigin::End, 0);
fs.write("x", 1);
},
@@ -432,11 +449,13 @@ struct CorruptionTest : public PersistentCacheTest
}
};
-#undef ENABLE_LOGGING
+#undef ENABLE_LOGGING
#undef ENABLE_WRITE_TEST
#ifdef ENABLE_LOGGING
-#define LOG(fmt, ...) printf(fmt, ##__VA_ARGS__); fflush(stdout);
+#define LOG(fmt, ...) \
+ printf(fmt, ##__VA_ARGS__); \
+ fflush(stdout);
#else
#define LOG(fmt, ...)
#endif
@@ -475,10 +494,13 @@ struct StressTest : public PersistentCacheTest
std::atomic<uint32_t> readSuccess{0};
std::thread threads[kThreadCount];
- Barrier *read_barrier;
- Barrier *write_barrier;
+ Barrier* read_barrier;
+ Barrier* write_barrier;
- StressTest() : PersistentCacheTest(kEntryCount - kEntryShortageCount) {}
+ StressTest()
+ : PersistentCacheTest(kEntryCount - kEntryShortageCount)
+ {
+ }
void run()
{
@@ -488,20 +510,16 @@ struct StressTest : public PersistentCacheTest
size_t size = rng.nextInt32InRange(256, 64 * 1024);
auto data = createRandomBlob(size);
auto key = SHA1::compute(data->getBufferPointer(), data->getBufferSize());
- entries.add(Entry{ key, data });
+ entries.add(Entry{key, data});
}
auto startTime = std::chrono::high_resolution_clock::now();
- Barrier read_barrier_(
- kThreadCount,
- []()
- {
- LOG("Read synchronized\n");
- });
+ Barrier read_barrier_(kThreadCount, []() { LOG("Read synchronized\n"); });
Barrier write_barrier_(
kThreadCount,
- [this](){
+ [this]()
+ {
LOG("Write synchronized\n");
#ifndef ENABLE_WRITE_TEST
SLANG_CHECK(readSuccess == kEntryCount - kEntryShortageCount);
@@ -523,12 +541,16 @@ struct StressTest : public PersistentCacheTest
while (true)
{
// Write to cache.
- size_t startIndex = (iteration * kEntryCount + (threadIndex * kBatchCount)) % (kEntryCount * 2);
+ size_t startIndex =
+ (iteration * kEntryCount + (threadIndex * kBatchCount)) %
+ (kEntryCount * 2);
for (size_t i = 0; i < kBatchCount; ++i)
{
const Entry& entry = entries[startIndex + i];
#ifdef ENABLE_WRITE_TEST
- osFileSystem->saveFileBlob(getEntryFileName(entry).getBuffer(), entry.data);
+ osFileSystem->saveFileBlob(
+ getEntryFileName(entry).getBuffer(),
+ entry.data);
#else
writeEntry(entry);
#endif
@@ -536,7 +558,9 @@ struct StressTest : public PersistentCacheTest
bytesWritten.fetch_add((uint32_t)entry.data->getBufferSize());
}
- LOG("Thread %u: ended writing (iteration=%u)\n", threadIndex, iteration.load());
+ LOG("Thread %u: ended writing (iteration=%u)\n",
+ threadIndex,
+ iteration.load());
// Synchronize.
read_barrier->wait();
@@ -555,7 +579,9 @@ struct StressTest : public PersistentCacheTest
entriesRead.fetch_add(1);
}
- LOG("Thread %u: ended reading (iteration=%u)\n", threadIndex, iteration.load());
+ LOG("Thread %u: ended reading (iteration=%u)\n",
+ threadIndex,
+ iteration.load());
// Synchronize.
write_barrier->wait();
@@ -577,7 +603,8 @@ struct StressTest : public PersistentCacheTest
auto endTime = std::chrono::high_resolution_clock::now();
auto duration = endTime - startTime;
- auto seconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() / 1000.0;
+ auto seconds =
+ std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() / 1000.0;
LOG("Total time: %.3fs\n", seconds);
LOG("Total bytes written: %d\n", bytesWritten.load());
diff --git a/tools/slang-unit-test/unit-test-process.cpp b/tools/slang-unit-test/unit-test-process.cpp
index d24120716..8866f4a9e 100644
--- a/tools/slang-unit-test/unit-test-process.cpp
+++ b/tools/slang-unit-test/unit-test-process.cpp
@@ -1,17 +1,19 @@
// unit-test-process.cpp
-#include "../../source/core/slang-string-util.h"
-#include "../../source/core/slang-process-util.h"
-
-#include "../../source/core/slang-io.h"
#include "../../source/core/slang-http.h"
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process-util.h"
#include "../../source/core/slang-random-generator.h"
-
+#include "../../source/core/slang-string-util.h"
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
-static SlangResult _createProcess(UnitTestContext* context, const char* toolName, const List<String>* optArgs, RefPtr<Process>& outProcess)
+static SlangResult _createProcess(
+ UnitTestContext* context,
+ const char* toolName,
+ const List<String>* optArgs,
+ RefPtr<Process>& outProcess)
{
CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(context->executableDirectory, "test-process"));
@@ -34,7 +36,8 @@ static SlangResult _httpReflectTest(UnitTestContext* context)
SLANG_RETURN_ON_FAIL(_createProcess(context, "http-reflect", nullptr, process));
Stream* writeStream = process->getStream(StdStreamType::In);
- RefPtr<BufferedReadStream> readStream( new BufferedReadStream(process->getStream(StdStreamType::Out)));
+ RefPtr<BufferedReadStream> readStream(
+ new BufferedReadStream(process->getStream(StdStreamType::Out)));
RefPtr<HTTPPacketConnection> connection = new HTTPPacketConnection(readStream, writeStream);
RefPtr<RandomGenerator> rand = RandomGenerator::create(10000);
@@ -91,7 +94,8 @@ static SlangResult _httpReflectTest(UnitTestContext* context)
static SlangResult _countTest(UnitTestContext* context, Index size, Index crashIndex = -1)
{
/* Here we are trying to test what happens if the server produces a large amount of data, and
- we just wait for termination. Do we receive all of the data irrespective of how much there is? */
+ we just wait for termination. Do we receive all of the data irrespective of how much there is?
+ */
List<String> args;
{
@@ -147,7 +151,7 @@ static SlangResult _countTest(UnitTestContext* context, Index size, Index crashI
static SlangResult _countTests(UnitTestContext* context)
{
- const Index sizes[] = { 1, 10, 1000, 1000, 10000, 100000 };
+ const Index sizes[] = {1, 10, 1000, 1000, 10000, 100000};
for (auto size : sizes)
{
SLANG_RETURN_ON_FAIL(_countTest(context, size));
diff --git a/tools/slang-unit-test/unit-test-record-replay.cpp b/tools/slang-unit-test/unit-test-record-replay.cpp
index 33bbab0c3..b81304937 100644
--- a/tools/slang-unit-test/unit-test-record-replay.cpp
+++ b/tools/slang-unit-test/unit-test-record-replay.cpp
@@ -1,12 +1,10 @@
// unit-test-record-replay.cpp
-#include "../../source/core/slang-string-util.h"
-#include "../../source/core/slang-process-util.h"
-
-#include "../../source/core/slang-io.h"
#include "../../source/core/slang-http.h"
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process-util.h"
#include "../../source/core/slang-random-generator.h"
-
+#include "../../source/core/slang-string-util.h"
#include "tools/unit-test/slang-unit-test.h"
#include <chrono>
@@ -14,7 +12,11 @@
using namespace Slang;
-static SlangResult createProcess(UnitTestContext* context, const char* processName, const List<String>* optArgs, RefPtr<Process>& outProcess)
+static SlangResult createProcess(
+ UnitTestContext* context,
+ const char* processName,
+ const List<String>* optArgs,
+ RefPtr<Process>& outProcess)
{
CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(context->executableDirectory, processName));
@@ -60,7 +62,9 @@ static SlangResult parseHashes(List<String> const& lines, List<entryHashInfo>& o
}
entryHashInfo hashInfo;
- auto extractToken = [](const UnownedStringSlice& token, const char splitChar, UnownedStringSlice& outToken) -> SlangResult
+ auto extractToken = [](const UnownedStringSlice& token,
+ const char splitChar,
+ UnownedStringSlice& outToken) -> SlangResult
{
List<UnownedStringSlice> subTokens;
StringUtil::split(token, splitChar, subTokens);
@@ -153,7 +157,10 @@ static void findRecordFileName(List<String>* fileNames)
m_fileNames->add(filename);
}
}
- Visitor(List<String>* fileNames) : m_fileNames(fileNames) {}
+ Visitor(List<String>* fileNames)
+ : m_fileNames(fileNames)
+ {
+ }
List<String>* m_fileNames;
};
@@ -161,14 +168,18 @@ static void findRecordFileName(List<String>* fileNames)
Path::find("slang-record", "*.cap", &visitor);
}
-static SlangResult launchProcessAndReadStdout(UnitTestContext* context, const List<String>& optArgs,
- const char* exampleName, RefPtr<Process>& process, ExecuteResult& exeRes)
+static SlangResult launchProcessAndReadStdout(
+ UnitTestContext* context,
+ const List<String>& optArgs,
+ const char* exampleName,
+ RefPtr<Process>& process,
+ ExecuteResult& exeRes)
{
StringBuilder msgBuilder;
SlangResult res = createProcess(context, exampleName, &optArgs, process);
if (SLANG_FAILED(res))
{
- msgBuilder << "Failed to launch process of '"<< exampleName << "'\n";
+ msgBuilder << "Failed to launch process of '" << exampleName << "'\n";
getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer());
return res;
}
@@ -202,7 +213,10 @@ static SlangResult launchProcessAndReadStdout(UnitTestContext* context, const Li
return SLANG_OK;
}
-static SlangResult runExample(UnitTestContext* context, const char* exampleName, List<entryHashInfo>& outHashes)
+static SlangResult runExample(
+ UnitTestContext* context,
+ const char* exampleName,
+ List<entryHashInfo>& outHashes)
{
SlangResult finalRes = SLANG_OK;
@@ -301,7 +315,9 @@ static SlangResult replayExample(UnitTestContext* context, List<entryHashInfo>&
return SLANG_OK;
}
-static SlangResult resultCompare(List<entryHashInfo> const& expectHashes, List<entryHashInfo> const& resultHashes)
+static SlangResult resultCompare(
+ List<entryHashInfo> const& expectHashes,
+ List<entryHashInfo> const& resultHashes)
{
if (expectHashes.getCount() == 0)
{
@@ -312,7 +328,8 @@ static SlangResult resultCompare(List<entryHashInfo> const& expectHashes, List<e
StringBuilder msgBuilder;
if (expectHashes.getCount() != resultHashes.getCount())
{
- msgBuilder << "The number of hashes doesn't match, expect: " << expectHashes.getCount() << ", actual: " << resultHashes.getCount() << "\n";
+ msgBuilder << "The number of hashes doesn't match, expect: " << expectHashes.getCount()
+ << ", actual: " << resultHashes.getCount() << "\n";
getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer());
return SLANG_FAIL;
}
@@ -322,23 +339,32 @@ static SlangResult resultCompare(List<entryHashInfo> const& expectHashes, List<e
if (expectHashes[i].targetIndex != resultHashes[i].targetIndex)
{
msgBuilder << "Failed to match 'targetIndex' at index " << i << "\n";
- msgBuilder << "Expect: " << expectHashes[i].targetIndex << ", actual: " << resultHashes[i].targetIndex << "\n";
- getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer());
+ msgBuilder << "Expect: " << expectHashes[i].targetIndex
+ << ", actual: " << resultHashes[i].targetIndex << "\n";
+ getTestReporter()->message(
+ TestMessageType::TestFailure,
+ msgBuilder.toString().getBuffer());
return SLANG_FAIL;
}
if (expectHashes[i].entryPointIndex != resultHashes[i].entryPointIndex)
{
msgBuilder << "Failed to match 'entryPointIndex' at index " << i << "\n";
- msgBuilder << "Expect: " << expectHashes[i].entryPointIndex << ", actual: " << resultHashes[i].entryPointIndex << "\n";
- getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer());
+ msgBuilder << "Expect: " << expectHashes[i].entryPointIndex
+ << ", actual: " << resultHashes[i].entryPointIndex << "\n";
+ getTestReporter()->message(
+ TestMessageType::TestFailure,
+ msgBuilder.toString().getBuffer());
return SLANG_FAIL;
}
if (expectHashes[i].hash != resultHashes[i].hash)
{
msgBuilder << "Failed to match 'hash' at index " << i << "\n";
- msgBuilder << "Expect: " << expectHashes[i].hash << ", actual: " << resultHashes[i].hash << "\n";
- getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer());
+ msgBuilder << "Expect: " << expectHashes[i].hash << ", actual: " << resultHashes[i].hash
+ << "\n";
+ getTestReporter()->message(
+ TestMessageType::TestFailure,
+ msgBuilder.toString().getBuffer());
return SLANG_FAIL;
}
}
@@ -351,7 +377,9 @@ static SlangResult cleanupRecordFiles()
SlangResult res = Path::removeNonEmpty("slang-record");
if (SLANG_FAILED(res))
{
- getTestReporter()->message(TestMessageType::TestFailure, "Failed to remove 'slang-record' directory\n");
+ getTestReporter()->message(
+ TestMessageType::TestFailure,
+ "Failed to remove 'slang-record' directory\n");
}
return res;
@@ -362,17 +390,17 @@ static SlangResult runTest(UnitTestContext* context, const char* testName)
List<entryHashInfo> expectHashes;
List<entryHashInfo> resultHashes;
SlangResult res = SLANG_OK;
- if((res = runExample(context, testName, expectHashes)) != SLANG_OK)
+ if ((res = runExample(context, testName, expectHashes)) != SLANG_OK)
{
goto error;
}
- if((res = replayExample(context, resultHashes)) != SLANG_OK)
+ if ((res = replayExample(context, resultHashes)) != SLANG_OK)
{
goto error;
}
- if((res = resultCompare(expectHashes, resultHashes)) != SLANG_OK)
+ if ((res = resultCompare(expectHashes, resultHashes)) != SLANG_OK)
{
goto error;
}
@@ -384,15 +412,15 @@ error:
static SlangResult runTests(UnitTestContext* context)
{
- const char* testBinaryNames[] = {
+ const char* testBinaryNames[] = {
"cpu-hello-world",
"triangle",
"ray-tracing",
"ray-tracing-pipeline",
"autodiff-texture",
"gpu-printing"
- // "shader-object", // these examples requires reflection API to replay, we have to disable it for now.
- // "model-viewer",
+ // "shader-object", // these examples requires reflection API to replay, we have to disable
+ // it for now. "model-viewer",
};
SlangResult finalRes = SLANG_OK;
@@ -403,7 +431,9 @@ static SlangResult runTests(UnitTestContext* context)
{
StringBuilder msgBuilder;
msgBuilder << "Failed subtest: '" << testBinaryName << "'\n\n\n";
- getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer());
+ getTestReporter()->message(
+ TestMessageType::TestFailure,
+ msgBuilder.toString().getBuffer());
finalRes = res;
}
}
diff --git a/tools/slang-unit-test/unit-test-riff.cpp b/tools/slang-unit-test/unit-test-riff.cpp
index 2902a9af5..a0eb91a47 100644
--- a/tools/slang-unit-test/unit-test-riff.cpp
+++ b/tools/slang-unit-test/unit-test-riff.cpp
@@ -1,14 +1,16 @@
// unit-test-riff.cpp
-#include "../../source/core/slang-riff.h"
-
#include "../../source/core/slang-random-generator.h"
-
+#include "../../source/core/slang-riff.h"
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
-static void _writeRandom(RandomGenerator* rand, size_t maxSize, RiffContainer& ioContainer, List<uint8_t>& ioData)
+static void _writeRandom(
+ RandomGenerator* rand,
+ size_t maxSize,
+ RiffContainer& ioContainer,
+ List<uint8_t>& ioData)
{
while (true)
{
@@ -29,7 +31,8 @@ static void _writeRandom(RandomGenerator* rand, size_t maxSize, RiffContainer& i
}
// Should be a single block with same data as the List
- RiffContainer::DataChunk* dataChunk = as<RiffContainer::DataChunk>(ioContainer.getCurrentChunk());
+ RiffContainer::DataChunk* dataChunk =
+ as<RiffContainer::DataChunk>(ioContainer.getCurrentChunk());
SLANG_ASSERT(dataChunk);
}
@@ -45,7 +48,7 @@ SLANG_UNIT_TEST(riff)
RiffContainer container;
{
- ScopeChunk scopeContainer(&container, Kind::List, markThings);
+ ScopeChunk scopeContainer(&container, Kind::List, markThings);
{
ScopeChunk scopeChunk(&container, Kind::Data, markData);
@@ -89,7 +92,7 @@ SLANG_UNIT_TEST(riff)
}
{
- OwnedMemoryStream stream(FileAccess::ReadWrite);
+ OwnedMemoryStream stream(FileAccess::ReadWrite);
SLANG_CHECK(SLANG_SUCCEEDED(RiffUtil::write(container.getRoot(), true, &stream)));
stream.seek(SeekOrigin::Start, 0);
@@ -108,10 +111,10 @@ SLANG_UNIT_TEST(riff)
SLANG_CHECK(readBuilder == builder);
}
}
-
}
- // Test writing as a stream only allocates a single data block (as long as there is enough space).
+ // Test writing as a stream only allocates a single data block (as long as there is enough
+ // space).
{
RiffContainer container;
@@ -121,39 +124,46 @@ SLANG_UNIT_TEST(riff)
RefPtr<RandomGenerator> rand = RandomGenerator::create(0x345234);
List<uint8_t> data;
- _writeRandom(rand, container.getMemoryArena().getBlockPayloadSize() / 2, container, data);
+ _writeRandom(
+ rand,
+ container.getMemoryArena().getBlockPayloadSize() / 2,
+ container,
+ data);
// Should be a single block with same data as the List
- RiffContainer::DataChunk* dataChunk = as<RiffContainer::DataChunk>(container.getCurrentChunk());
+ RiffContainer::DataChunk* dataChunk =
+ as<RiffContainer::DataChunk>(container.getCurrentChunk());
SLANG_ASSERT(dataChunk);
// It should be a single block
SLANG_CHECK(dataChunk->getSingleData() != nullptr);
SLANG_CHECK(dataChunk->isEqual(data.getBuffer(), data.getCount()));
-
}
- }
+ }
// Test writing across multiple data blocks
{
RefPtr<RandomGenerator> rand = RandomGenerator::create(0x345234);
- for (Int i = 0 ; i < 100; ++i)
+ for (Int i = 0; i < 100; ++i)
{
RiffContainer container;
- const size_t maxSize = rand->nextInt32InRange(1, int32_t(container.getMemoryArena().getBlockPayloadSize() * 3));
-
+ const size_t maxSize = rand->nextInt32InRange(
+ 1,
+ int32_t(container.getMemoryArena().getBlockPayloadSize() * 3));
+
ScopeChunk scopeChunk(&container, Kind::List, markData);
{
ScopeChunk scopeChunk(&container, Kind::Data, markData);
-
+
List<uint8_t> data;
_writeRandom(rand, maxSize, container, data);
// Should be a single block with same data as the List
- RiffContainer::DataChunk* dataChunk = as<RiffContainer::DataChunk>(container.getCurrentChunk());
+ RiffContainer::DataChunk* dataChunk =
+ as<RiffContainer::DataChunk>(container.getCurrentChunk());
SLANG_CHECK(dataChunk && dataChunk->isEqual(data.getBuffer(), data.getCount()));
}
}
@@ -176,4 +186,3 @@ SLANG_UNIT_TEST(riff)
}
#endif
}
-
diff --git a/tools/slang-unit-test/unit-test-rtti.cpp b/tools/slang-unit-test/unit-test-rtti.cpp
index f72cfbde2..485d58aea 100644
--- a/tools/slang-unit-test/unit-test-rtti.cpp
+++ b/tools/slang-unit-test/unit-test-rtti.cpp
@@ -1,12 +1,12 @@
// unit-test-rtti.cpp
#include "../../source/core/slang-rtti-info.h"
-
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
-namespace { // anonymous
+namespace
+{ // anonymous
struct SomeStruct
{
@@ -18,7 +18,7 @@ struct SomeStruct
static const StructRttiInfo g_rttiInfo;
};
-} // anonymous
+} // namespace
static const StructRttiInfo _makeSomeStructRtti()
{
@@ -32,14 +32,13 @@ static const StructRttiInfo _makeSomeStructRtti()
return builder.make();
}
-/* static */const StructRttiInfo SomeStruct::g_rttiInfo = _makeSomeStructRtti();
+/* static */ const StructRttiInfo SomeStruct::g_rttiInfo = _makeSomeStructRtti();
SLANG_UNIT_TEST(Rtti)
{
using namespace Slang;
- const RttiInfo* types[] =
- {
+ const RttiInfo* types[] = {
GetRttiInfo<int32_t>::get(),
GetRttiInfo<int32_t[10]>::get(),
GetRttiInfo<String>::get(),
@@ -48,7 +47,7 @@ SLANG_UNIT_TEST(Rtti)
GetRttiInfo<int32_t[2][3]>::get(),
GetRttiInfo<SomeStruct>::get(),
GetRttiInfo<SomeStruct*>::get(),
- GetRttiInfo<const float*const>::get(),
+ GetRttiInfo<const float* const>::get(),
};
StringBuilder buf;
@@ -59,16 +58,15 @@ SLANG_UNIT_TEST(Rtti)
buf << "\n";
}
- const char expected[] =
- "int32_t\n"
- "int32_t[10]\n"
- "String\n"
- "List<String>\n"
- "List<List<String>>\n"
- "int32_t[2][3]\n"
- "SomeStruct\n"
- "SomeStruct*\n"
- "float*\n";
+ const char expected[] = "int32_t\n"
+ "int32_t[10]\n"
+ "String\n"
+ "List<String>\n"
+ "List<List<String>>\n"
+ "int32_t[2][3]\n"
+ "SomeStruct\n"
+ "SomeStruct*\n"
+ "float*\n";
SLANG_CHECK(buf == expected)
}
diff --git a/tools/slang-unit-test/unit-test-short-list.cpp b/tools/slang-unit-test/unit-test-short-list.cpp
index 2760d633e..9d5de9328 100644
--- a/tools/slang-unit-test/unit-test-short-list.cpp
+++ b/tools/slang-unit-test/unit-test-short-list.cpp
@@ -19,36 +19,36 @@ static bool _checkArrayView(ArrayView<T> v0, ArrayView<T> v1)
SLANG_UNIT_TEST(shortList)
{
{
- ShortList<String, 4> shortList = { "a", "b", "c" };
+ ShortList<String, 4> shortList = {"a", "b", "c"};
shortList.add("d");
auto arrayView = shortList.getArrayView();
SLANG_CHECK(arrayView.ownsStorage == false);
- SLANG_CHECK(_checkArrayView(arrayView.arrayView,
- List<String>{"a", "b", "c", "d"}.getArrayView()));
+ SLANG_CHECK(
+ _checkArrayView(arrayView.arrayView, List<String>{"a", "b", "c", "d"}.getArrayView()));
shortList.add("e");
auto arrayView2 = shortList.getArrayView();
SLANG_CHECK(arrayView2.ownsStorage == true);
- SLANG_CHECK(_checkArrayView(arrayView2.arrayView,
+ SLANG_CHECK(_checkArrayView(
+ arrayView2.arrayView,
List<String>{"a", "b", "c", "d", "e"}.getArrayView()));
auto arrayView3 = shortList.getArrayView(0, 2);
SLANG_CHECK(arrayView3.ownsStorage == false);
- SLANG_CHECK(_checkArrayView(arrayView3.arrayView,
- List<String>{"a", "b"}.getArrayView()));
+ SLANG_CHECK(_checkArrayView(arrayView3.arrayView, List<String>{"a", "b"}.getArrayView()));
auto arrayView4 = shortList.getArrayView(4, 1);
SLANG_CHECK(arrayView4.ownsStorage == false);
- SLANG_CHECK(_checkArrayView(arrayView4.arrayView,
- List<String>{"e"}.getArrayView()));
+ SLANG_CHECK(_checkArrayView(arrayView4.arrayView, List<String>{"e"}.getArrayView()));
auto arrayView5 = shortList.getArrayView(2, 3);
SLANG_CHECK(arrayView5.ownsStorage == true);
- SLANG_CHECK(_checkArrayView(arrayView5.arrayView,
- List<String>{"c", "d", "e"}.getArrayView()));
+ SLANG_CHECK(
+ _checkArrayView(arrayView5.arrayView, List<String>{"c", "d", "e"}.getArrayView()));
ShortList<String, 1> copy2;
ShortList<String, 2> copy1;
copy1 = shortList;
for (auto item : copy1)
copy2.add(item);
- SLANG_CHECK(_checkArrayView(copy2.getArrayView().arrayView,
+ SLANG_CHECK(_checkArrayView(
+ copy2.getArrayView().arrayView,
List<String>{"a", "b", "c", "d", "e"}.getArrayView()));
SLANG_CHECK(copy2.indexOf("a") == 0);
@@ -61,17 +61,20 @@ SLANG_UNIT_TEST(shortList)
copy2.add("f");
copy2.fastRemove("c");
copy2.compress();
- SLANG_CHECK(_checkArrayView(copy2.getArrayView().arrayView,
+ SLANG_CHECK(_checkArrayView(
+ copy2.getArrayView().arrayView,
List<String>{"a", "b", "f", "d", "e"}.getArrayView()));
shortList.removeLast();
shortList.removeLast();
shortList.compress();
- SLANG_CHECK(_checkArrayView(shortList.getArrayView().arrayView,
+ SLANG_CHECK(_checkArrayView(
+ shortList.getArrayView().arrayView,
List<String>{"a", "b", "c"}.getArrayView()));
shortList.add("d");
shortList.add("e");
- SLANG_CHECK(_checkArrayView(shortList.getArrayView().arrayView,
+ SLANG_CHECK(_checkArrayView(
+ shortList.getArrayView().arrayView,
List<String>{"a", "b", "c", "d", "e"}.getArrayView()));
}
}
diff --git a/tools/slang-unit-test/unit-test-source-map.cpp b/tools/slang-unit-test/unit-test-source-map.cpp
index d4363e02c..797229afe 100644
--- a/tools/slang-unit-test/unit-test-source-map.cpp
+++ b/tools/slang-unit-test/unit-test-source-map.cpp
@@ -1,28 +1,29 @@
#include "../../source/compiler-core/slang-json-lexer.h"
-#include "../../source/core/slang-string-escape-util.h"
+#include "../../source/compiler-core/slang-json-native.h"
#include "../../source/compiler-core/slang-json-parser.h"
+#include "../../source/compiler-core/slang-json-source-map-util.h"
#include "../../source/compiler-core/slang-json-value.h"
-
-#include "../../source/compiler-core/slang-json-native.h"
-
#include "../../source/compiler-core/slang-source-map.h"
-#include "../../source/compiler-core/slang-json-source-map-util.h"
-
#include "../../source/core/slang-rtti-info.h"
-
+#include "../../source/core/slang-string-escape-util.h"
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
-static SlangResult _read(JSONContainer* container, const String& json, DiagnosticSink* sink, SourceMap& outSourceMap)
+static SlangResult _read(
+ JSONContainer* container,
+ const String& json,
+ DiagnosticSink* sink,
+ SourceMap& outSourceMap)
{
auto sourceManager = sink->getSourceManager();
JSONValue rootValue;
{
// Now need to parse as JSON
- SourceFile* sourceFile = sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), json);
+ SourceFile* sourceFile =
+ sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), json);
SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc());
JSONLexer lexer;
@@ -41,7 +42,11 @@ static SlangResult _read(JSONContainer* container, const String& json, Diagnosti
return SLANG_OK;
}
-static SlangResult _write(JSONContainer* container, const SourceMap& sourceMap, DiagnosticSink* sink, String& out)
+static SlangResult _write(
+ JSONContainer* container,
+ const SourceMap& sourceMap,
+ DiagnosticSink* sink,
+ String& out)
{
// Write it out
JSONValue jsonValue;
@@ -78,10 +83,10 @@ static SlangResult _check()
SourceMap sourceMap;
SLANG_RETURN_ON_FAIL(_read(container, jsonSource, &sink, sourceMap));
-
+
String json;
SLANG_RETURN_ON_FAIL(_write(container, sourceMap, &sink, json));
-
+
SourceMap readSourceMap;
SLANG_RETURN_ON_FAIL(_read(container, json, &sink, readSourceMap));
@@ -89,7 +94,7 @@ static SlangResult _check()
{
return SLANG_FAIL;
}
-
+
// Lets try copy construction
{
SourceMap copy(sourceMap);
@@ -117,4 +122,3 @@ SLANG_UNIT_TEST(sourceMap)
{
SLANG_CHECK(SLANG_SUCCEEDED(_check()));
}
-
diff --git a/tools/slang-unit-test/unit-test-string-escape.cpp b/tools/slang-unit-test/unit-test-string-escape.cpp
index 337573081..3a1cb7f06 100644
--- a/tools/slang-unit-test/unit-test-string-escape.cpp
+++ b/tools/slang-unit-test/unit-test-string-escape.cpp
@@ -1,79 +1,80 @@
// unit-test-string-escape.cpp
#include "../../source/core/slang-string-escape-util.h"
-
#include "tools/unit-test/slang-unit-test.h"
using namespace Slang;
static bool _checkConversion(StringEscapeHandler* handler, const UnownedStringSlice& check)
{
- StringBuilder buf;
- handler->appendEscaped(check, buf);
+ StringBuilder buf;
+ handler->appendEscaped(check, buf);
- StringBuilder decode;
- handler->appendUnescaped(buf.getUnownedSlice(), decode);
+ StringBuilder decode;
+ handler->appendUnescaped(buf.getUnownedSlice(), decode);
- return decode == check;
+ return decode == check;
}
static bool _checkDecode(const UnownedStringSlice& encoded, const UnownedStringSlice& decoded)
{
- auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp);
+ auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp);
- StringBuilder buf;
- StringEscapeUtil::appendUnquoted(handler, encoded, buf);
- return buf == decoded;
+ StringBuilder buf;
+ StringEscapeUtil::appendUnquoted(handler, encoded, buf);
+ return buf == decoded;
}
-#define SLANG_ENCODED_DECODED(x) \
- const auto encoded = toSlice(#x); \
- const auto decoded = toSlice(x);
+#define SLANG_ENCODED_DECODED(x) \
+ const auto encoded = toSlice(#x); \
+ const auto decoded = toSlice(x);
SLANG_UNIT_TEST(StringEscape)
{
- // Check greedy hex digits
- {
- // \x can have any number of hex digits
- const char text[] = "\x000001";
- SLANG_ASSERT(SLANG_COUNT_OF(text) == 2 && text[0] == 1);
- }
-
- // Check octal greedy
- {
- //\ + up to 3 octal digits
- const char text[] = "\0011";
- SLANG_ASSERT(SLANG_COUNT_OF(text) == 3 && text[0] == 1 && text[1] == '1');
-
- const char text2[] = "\78";
- SLANG_ASSERT(SLANG_COUNT_OF(text2) == 3 && text2[0] == 7 && text2[1] == '8');
- }
-
- {
- auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp);
-
- SLANG_CHECK(_checkConversion(handler, toSlice("\0\1\2""2")));
- }
-
- {
- auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp);
-
- // We can't just use '\uxxxx', because it has to be translatable into an output character in MSVC (not into utf8)
- // Can make work perhaps with something like
- // #pragma execution_character_set("utf-8")
- // But for now we don't worry
- //
- // Visual Studio does not appear to support '\U' by default, presumably because wchar_t is 16 bits
-
- {
- SLANG_ENCODED_DECODED("\a\b\0hey~\u0023\n\0");
- SLANG_CHECK(_checkDecode(encoded, decoded));
- }
-
- {
- SLANG_ENCODED_DECODED("\n\v\b\t\1\02\003\x5z\x00007f\0");
- SLANG_CHECK(_checkDecode(encoded, decoded));
- }
- }
+ // Check greedy hex digits
+ {
+ // \x can have any number of hex digits
+ const char text[] = "\x000001";
+ SLANG_ASSERT(SLANG_COUNT_OF(text) == 2 && text[0] == 1);
+ }
+
+ // Check octal greedy
+ {
+ //\ + up to 3 octal digits
+ const char text[] = "\0011";
+ SLANG_ASSERT(SLANG_COUNT_OF(text) == 3 && text[0] == 1 && text[1] == '1');
+
+ const char text2[] = "\78";
+ SLANG_ASSERT(SLANG_COUNT_OF(text2) == 3 && text2[0] == 7 && text2[1] == '8');
+ }
+
+ {
+ auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp);
+
+ SLANG_CHECK(_checkConversion(
+ handler,
+ toSlice("\0\1\2"
+ "2")));
+ }
+
+ {
+ auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp);
+
+ // We can't just use '\uxxxx', because it has to be translatable into an output character in
+ // MSVC (not into utf8) Can make work perhaps with something like #pragma
+ // execution_character_set("utf-8") But for now we don't worry
+ //
+ // Visual Studio does not appear to support '\U' by default, presumably because wchar_t is
+ // 16 bits
+
+ {
+ SLANG_ENCODED_DECODED("\a\b\0hey~\u0023\n\0");
+ SLANG_CHECK(_checkDecode(encoded, decoded));
+ }
+
+ {
+ SLANG_ENCODED_DECODED("\n\v\b\t\1\02\003\x5z\x00007f\0");
+ SLANG_CHECK(_checkDecode(encoded, decoded));
+ }
+ }
}
-
diff --git a/tools/slang-unit-test/unit-test-string.cpp b/tools/slang-unit-test/unit-test-string.cpp
index 230cb72f8..4a71bca4b 100644
--- a/tools/slang-unit-test/unit-test-string.cpp
+++ b/tools/slang-unit-test/unit-test-string.cpp
@@ -1,16 +1,18 @@
// unit-test-path.cpp
#include "../../source/core/slang-string-util.h"
-
#include "tools/unit-test/slang-unit-test.h"
-//#include <math.h>
+// #include <math.h>
#include <sstream>
using namespace Slang;
-static bool _areEqual(const List<UnownedStringSlice>& lines, const UnownedStringSlice* checkLines, Int checkLinesCount)
+static bool _areEqual(
+ const List<UnownedStringSlice>& lines,
+ const UnownedStringSlice* checkLines,
+ Int checkLinesCount)
{
if (checkLinesCount != lines.getCount())
{
@@ -27,7 +29,10 @@ static bool _areEqual(const List<UnownedStringSlice>& lines, const UnownedString
return true;
}
-static bool _checkLines(const UnownedStringSlice& input, const UnownedStringSlice* checkLines, Int checkLinesCount)
+static bool _checkLines(
+ const UnownedStringSlice& input,
+ const UnownedStringSlice* checkLines,
+ Int checkLinesCount)
{
List<UnownedStringSlice> lines;
StringUtil::calcLines(input, lines);
@@ -100,7 +105,11 @@ static int64_t _calcULPDistance(double a, double b)
return distance < 0 ? -distance : distance;
}
-static bool _areApproximatelyEqual(double a, double b, double fixedEpsilon = 1e-10, int ulpsEpsilon = 100)
+static bool _areApproximatelyEqual(
+ double a,
+ double b,
+ double fixedEpsilon = 1e-10,
+ int ulpsEpsilon = 100)
{
// Handle the near-zero case.
const double difference = abs(a - b);
@@ -115,8 +124,11 @@ static bool _areApproximatelyEqual(double a, double b, double fixedEpsilon = 1e-
SLANG_UNIT_TEST(string)
{
{
- UnownedStringSlice checkLines[] = { UnownedStringSlice::fromLiteral("") };
- SLANG_CHECK(_checkLines(UnownedStringSlice::fromLiteral(""), checkLines, SLANG_COUNT_OF(checkLines)));
+ UnownedStringSlice checkLines[] = {UnownedStringSlice::fromLiteral("")};
+ SLANG_CHECK(_checkLines(
+ UnownedStringSlice::fromLiteral(""),
+ checkLines,
+ SLANG_COUNT_OF(checkLines)));
}
{
// Will emit no lines
@@ -124,16 +136,30 @@ SLANG_UNIT_TEST(string)
}
{
// Two lines - both empty
- UnownedStringSlice checkLines[] = { UnownedStringSlice(), UnownedStringSlice()};
- SLANG_CHECK(_checkLines(UnownedStringSlice::fromLiteral("\n"), checkLines, SLANG_COUNT_OF(checkLines)));
+ UnownedStringSlice checkLines[] = {UnownedStringSlice(), UnownedStringSlice()};
+ SLANG_CHECK(_checkLines(
+ UnownedStringSlice::fromLiteral("\n"),
+ checkLines,
+ SLANG_COUNT_OF(checkLines)));
}
{
- UnownedStringSlice checkLines[] = { UnownedStringSlice::fromLiteral("Hello"), UnownedStringSlice::fromLiteral("World!") };
- SLANG_CHECK(_checkLines(UnownedStringSlice::fromLiteral("Hello\nWorld!"), checkLines, SLANG_COUNT_OF(checkLines)));
+ UnownedStringSlice checkLines[] = {
+ UnownedStringSlice::fromLiteral("Hello"),
+ UnownedStringSlice::fromLiteral("World!")};
+ SLANG_CHECK(_checkLines(
+ UnownedStringSlice::fromLiteral("Hello\nWorld!"),
+ checkLines,
+ SLANG_COUNT_OF(checkLines)));
}
{
- UnownedStringSlice checkLines[] = { UnownedStringSlice::fromLiteral("Hello"), UnownedStringSlice::fromLiteral("World!"), UnownedStringSlice() };
- SLANG_CHECK(_checkLines(UnownedStringSlice::fromLiteral("Hello\n\rWorld!\n"), checkLines, SLANG_COUNT_OF(checkLines)));
+ UnownedStringSlice checkLines[] = {
+ UnownedStringSlice::fromLiteral("Hello"),
+ UnownedStringSlice::fromLiteral("World!"),
+ UnownedStringSlice()};
+ SLANG_CHECK(_checkLines(
+ UnownedStringSlice::fromLiteral("Hello\n\rWorld!\n"),
+ checkLines,
+ SLANG_COUNT_OF(checkLines)));
}
{
@@ -143,16 +169,27 @@ SLANG_UNIT_TEST(string)
}
{
Int value;
- SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-10"), value)) && value == -10);
- SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("0"), value)) && value == 0);
- SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-0"), value)) && value == 0);
-
- SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("13824"), value)) && value == 13824);
- SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-13824"), value)) && value == -13824);
+ SLANG_CHECK(
+ SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-10"), value)) &&
+ value == -10);
+ SLANG_CHECK(
+ SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("0"), value)) && value == 0);
+ SLANG_CHECK(
+ SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-0"), value)) && value == 0);
+
+ SLANG_CHECK(
+ SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("13824"), value)) &&
+ value == 13824);
+ SLANG_CHECK(
+ SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-13824"), value)) &&
+ value == -13824);
}
{
- UnownedStringSlice values[] = { UnownedStringSlice("hello"), UnownedStringSlice("world"), UnownedStringSlice("!") };
+ UnownedStringSlice values[] = {
+ UnownedStringSlice("hello"),
+ UnownedStringSlice("world"),
+ UnownedStringSlice("!")};
ArrayView<UnownedStringSlice> valuesView(values, SLANG_COUNT_OF(values));
List<UnownedStringSlice> checkValues;
@@ -192,7 +229,7 @@ SLANG_UNIT_TEST(string)
}
}
{
-
+
List<double> values;
values.add(0.0);
values.add(-0.0);
@@ -221,7 +258,7 @@ SLANG_UNIT_TEST(string)
SlangResult res = StringUtil::parseDouble(slice, parsedValue);
auto ulpsParsed = _calcULPDistance(value, parsedValue);
-
+
SLANG_CHECK(SLANG_SUCCEEDED(res));
// Check that they are equal
@@ -254,7 +291,7 @@ SLANG_UNIT_TEST(string)
SlangResult res = StringUtil::parseInt64(slice, parsedValue);
SLANG_CHECK(SLANG_SUCCEEDED(res));
-
+
// Check that they are equal
SLANG_CHECK(value == parsedValue);
}
diff --git a/tools/slang-unit-test/unit-test-translation-unit-import.cpp b/tools/slang-unit-test/unit-test-translation-unit-import.cpp
index 3b7f90c00..9870cf1e6 100644
--- a/tools/slang-unit-test/unit-test-translation-unit-import.cpp
+++ b/tools/slang-unit-test/unit-test-translation-unit-import.cpp
@@ -1,15 +1,14 @@
// unit-test-translation-unit-import.cpp
+#include "../../source/core/slang-io.h"
+#include "../../source/core/slang-process.h"
+#include "slang-com-ptr.h"
#include "slang.h"
+#include "tools/unit-test/slang-unit-test.h"
#include <stdio.h>
#include <stdlib.h>
-#include "tools/unit-test/slang-unit-test.h"
-#include "slang-com-ptr.h"
-#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-process.h"
-
using namespace Slang;
// Test that the API supports discovering previously checked translation unit in the same
@@ -17,10 +16,9 @@ using namespace Slang;
SLANG_UNIT_TEST(translationUnitImport)
{
// Source for the first translation unit.
- const char* generatedSource =
- "public int f() {"
- " return 5;"
- "};";
+ const char* generatedSource = "public int f() {"
+ " return 5;"
+ "};";
// Source for the a file that imports the first translation unit.
// The import should succeed and `f` should be visible to this module.
@@ -50,13 +48,21 @@ SLANG_UNIT_TEST(translationUnitImport)
File::writeAllText(moduleName + ".slang", fileSource);
spAddCodeGenTarget(request, SLANG_HLSL);
- int generatedTranslationUnitIndex = spAddTranslationUnit(request, SLANG_SOURCE_LANGUAGE_SLANG, "generatedUnit");
+ int generatedTranslationUnitIndex =
+ spAddTranslationUnit(request, SLANG_SOURCE_LANGUAGE_SLANG, "generatedUnit");
spAddTranslationUnitSourceString(
- request, generatedTranslationUnitIndex, "generatedFile", generatedSource);
+ request,
+ generatedTranslationUnitIndex,
+ "generatedFile",
+ generatedSource);
- int entryPointTranslationUnitIndex = spAddTranslationUnit(request, SLANG_SOURCE_LANGUAGE_SLANG, "userUnit");
+ int entryPointTranslationUnitIndex =
+ spAddTranslationUnit(request, SLANG_SOURCE_LANGUAGE_SLANG, "userUnit");
spAddTranslationUnitSourceString(
- request, entryPointTranslationUnitIndex, "userFile", userSource.getUnownedSlice().begin());
+ request,
+ entryPointTranslationUnitIndex,
+ "userFile",
+ userSource.getUnownedSlice().begin());
spAddEntryPoint(request, entryPointTranslationUnitIndex, "computeMain", SLANG_STAGE_COMPUTE);
auto compileResult = spCompile(request);
@@ -65,9 +71,8 @@ SLANG_UNIT_TEST(translationUnitImport)
Slang::ComPtr<ISlangBlob> outBlob;
spGetEntryPointCodeBlob(request, 0, 0, outBlob.writeRef());
SLANG_CHECK(outBlob && outBlob->getBufferSize() != 0);
-
+
spDestroyCompileRequest(request);
spDestroySession(session);
File::remove(moduleName + ".slang");
}
-
diff --git a/tools/slangd/main.cpp b/tools/slangd/main.cpp
index 42d6e0c1b..240992273 100644
--- a/tools/slangd/main.cpp
+++ b/tools/slangd/main.cpp
@@ -2,11 +2,11 @@
// This file implements the entry point for `slangd`, the daemon process of Slang's language server.
-#include <thread>
-
#include "../../source/core/slang-basic.h"
#include "../../source/slang/slang-language-server.h"
+#include <thread>
+
int main(int argc, const char* const* argv)
{
bool isDebug = false;
@@ -23,7 +23,7 @@ int main(int argc, const char* const* argv)
}
Slang::LanguageServerStartupOptions options;
options.parse(argc, argv);
- auto result = Slang::runLanguageServer(options);
+ auto result = Slang::runLanguageServer(options);
slang::shutdown();
return result;
}
diff --git a/tools/test-process/test-process-main.cpp b/tools/test-process/test-process-main.cpp
index ea8f30c11..31e7f3ef5 100644
--- a/tools/test-process/test-process-main.cpp
+++ b/tools/test-process/test-process-main.cpp
@@ -1,19 +1,16 @@
// test-process-main.cpp
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-
-#include "slang-com-helper.h"
-
-#include "../../source/core/slang-string.h"
+#include "../../source/core/slang-http.h"
#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-process-util.h"
-
+#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-string.h"
#include "../../source/core/slang-test-tool-util.h"
-#include "../../source/core/slang-http.h"
+#include "slang-com-helper.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
namespace TestProcess
{
@@ -80,7 +77,7 @@ static SlangResult _outputReflect()
List<Byte> buffer;
- Index startIndex = 0;
+ Index startIndex = 0;
while (true)
{
@@ -88,7 +85,9 @@ static SlangResult _outputReflect()
while (true)
{
- UnownedStringSlice slice((const char*)buffer.begin() + startIndex, (const char*)buffer.end());
+ UnownedStringSlice slice(
+ (const char*)buffer.begin() + startIndex,
+ (const char*)buffer.end());
UnownedStringSlice line;
if (!StringUtil::extractLine(slice, line) || slice.begin() == nullptr)
@@ -107,7 +106,9 @@ static SlangResult _outputReflect()
fputc('\n', fileOut);
// Move the start index forward
- const Index newStartIndex = slice.begin() ? Index(slice.begin() - (const char*)buffer.getBuffer()) : buffer.getCount();
+ const Index newStartIndex = slice.begin()
+ ? Index(slice.begin() - (const char*)buffer.getBuffer())
+ : buffer.getCount();
SLANG_ASSERT(newStartIndex > startIndex);
startIndex = newStartIndex;
}
@@ -157,7 +158,7 @@ static SlangResult _httpReflect(int argc, const char* const* argv)
return SLANG_OK;
}
-static SlangResult execute(int argc, const char*const* argv)
+static SlangResult execute(int argc, const char* const* argv)
{
if (argc < 2)
{
diff --git a/tools/test-server/test-server-diagnostic-defs.h b/tools/test-server/test-server-diagnostic-defs.h
index 8eedaba0d..f80ac9476 100644
--- a/tools/test-server/test-server-diagnostic-defs.h
+++ b/tools/test-server/test-server-diagnostic-defs.h
@@ -19,7 +19,11 @@
#endif
DIAGNOSTIC(100000, Error, unableToLoadSharedLibrary, "Unable to load shared library '$0'")
-DIAGNOSTIC(100001, Error, unableToFindFunctionInSharedLibrary, "Unable to find function '$0' in shared library")
+DIAGNOSTIC(
+ 100001,
+ Error,
+ unableToFindFunctionInSharedLibrary,
+ "Unable to find function '$0' in shared library")
DIAGNOSTIC(100002, Error, unableToGetUnitTestModule, "Unable to get unit test module")
DIAGNOSTIC(100003, Error, unableToFindTest, "Unable to find test '$0'")
DIAGNOSTIC(100004, Error, unableToFindUnitTestModule, "Unable to find unit test module '$0'")
diff --git a/tools/test-server/test-server-diagnostics.cpp b/tools/test-server/test-server-diagnostics.cpp
index ddefc53d3..8fb1f5a43 100644
--- a/tools/test-server/test-server-diagnostics.cpp
+++ b/tools/test-server/test-server-diagnostics.cpp
@@ -1,13 +1,15 @@
#include "test-server-diagnostics.h"
-namespace TestServer {
+namespace TestServer
+{
namespace ServerDiagnostics
{
using namespace Slang;
-#define DIAGNOSTIC(id, severity, name, messageFormat) const DiagnosticInfo name = { id, Severity::severity, #name, messageFormat };
+#define DIAGNOSTIC(id, severity, name, messageFormat) \
+ const DiagnosticInfo name = {id, Severity::severity, #name, messageFormat};
#include "test-server-diagnostic-defs.h"
-}
+} // namespace ServerDiagnostics
} // namespace TestServer
diff --git a/tools/test-server/test-server-diagnostics.h b/tools/test-server/test-server-diagnostics.h
index be816135a..2f9bf170c 100644
--- a/tools/test-server/test-server-diagnostics.h
+++ b/tools/test-server/test-server-diagnostics.h
@@ -1,21 +1,22 @@
#ifndef TEST_SERVER_DIAGNOSTICS_H
#define TEST_SERVER_DIAGNOSTICS_H
+#include "../../source/compiler-core/slang-diagnostic-sink.h"
+#include "../../source/compiler-core/slang-source-loc.h"
#include "../../source/core/slang-basic.h"
#include "../../source/core/slang-writer.h"
-#include "../../source/compiler-core/slang-source-loc.h"
-#include "../../source/compiler-core/slang-diagnostic-sink.h"
-
-namespace TestServer {
+namespace TestServer
+{
using namespace Slang;
-namespace ServerDiagnostics {
+namespace ServerDiagnostics
+{
#define DIAGNOSTIC(id, severity, name, messageFormat) extern const DiagnosticInfo name;
#include "test-server-diagnostic-defs.h"
-} // ServerDiagnostics
-} // TestServer
+} // namespace ServerDiagnostics
+} // namespace TestServer
#endif
diff --git a/tools/test-server/test-server-main.cpp b/tools/test-server/test-server-main.cpp
index fab84b9f5..00a705155 100644
--- a/tools/test-server/test-server-main.cpp
+++ b/tools/test-server/test-server-main.cpp
@@ -1,31 +1,23 @@
// test-server.cpp
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "../../source/core/slang-secure-crt.h"
-
-#include "slang-com-helper.h"
-
-#include "../../source/core/slang-string.h"
+#include "../../source/compiler-core/slang-json-rpc-connection.h"
+#include "../../source/compiler-core/slang-test-server-protocol.h"
#include "../../source/core/slang-io.h"
-#include "../../source/core/slang-writer.h"
-#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-process-util.h"
-
+#include "../../source/core/slang-secure-crt.h"
#include "../../source/core/slang-shared-library.h"
-
+#include "../../source/core/slang-string-util.h"
+#include "../../source/core/slang-string.h"
#include "../../source/core/slang-test-tool-util.h"
-
-#include "../../source/compiler-core/slang-json-rpc-connection.h"
-
-#include "../../source/compiler-core/slang-test-server-protocol.h"
-
+#include "../../source/core/slang-writer.h"
+#include "slang-com-helper.h"
#include "test-server-diagnostics.h"
-
#include "tools/unit-test/slang-unit-test.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
namespace TestServer
{
using namespace Slang;
@@ -34,13 +26,18 @@ class TestReporter : public ITestReporter
{
public:
// ITestReporter
- virtual SLANG_NO_THROW void SLANG_MCALL startTest(const char* testName) SLANG_OVERRIDE { }
- virtual SLANG_NO_THROW void SLANG_MCALL addResult(TestResult result)SLANG_OVERRIDE;
- virtual SLANG_NO_THROW void SLANG_MCALL addResultWithLocation(TestResult result, const char* testText, const char* file, int line) SLANG_OVERRIDE;
- virtual SLANG_NO_THROW void SLANG_MCALL addResultWithLocation(bool testSucceeded, const char* testText, const char* file, int line) SLANG_OVERRIDE;
- virtual SLANG_NO_THROW void SLANG_MCALL addExecutionTime(double time) SLANG_OVERRIDE { }
- virtual SLANG_NO_THROW void SLANG_MCALL message(TestMessageType type, const char* message) SLANG_OVERRIDE;
- virtual SLANG_NO_THROW void SLANG_MCALL endTest() SLANG_OVERRIDE { }
+ virtual SLANG_NO_THROW void SLANG_MCALL startTest(const char* testName) SLANG_OVERRIDE {}
+ virtual SLANG_NO_THROW void SLANG_MCALL addResult(TestResult result) SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ addResultWithLocation(TestResult result, const char* testText, const char* file, int line)
+ SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ addResultWithLocation(bool testSucceeded, const char* testText, const char* file, int line)
+ SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW void SLANG_MCALL addExecutionTime(double time) SLANG_OVERRIDE {}
+ virtual SLANG_NO_THROW void SLANG_MCALL message(TestMessageType type, const char* message)
+ SLANG_OVERRIDE;
+ virtual SLANG_NO_THROW void SLANG_MCALL endTest() SLANG_OVERRIDE {}
StringBuilder m_buf;
Index m_failCount = 0;
@@ -54,22 +51,22 @@ public:
SlangResult init(int argc, const char* const* argv);
- /// Can return nullptr if cannot create the session
+ /// Can return nullptr if cannot create the session
slang::IGlobalSession* getOrCreateGlobalSession();
- /// Can return nullptr if cannot load the tool
+ /// Can return nullptr if cannot load the tool
ISlangSharedLibrary* loadSharedLibrary(const String& name, DiagnosticSink* sink = nullptr);
- /// Get a unit test module. Returns nullptr if not found.
+ /// Get a unit test module. Returns nullptr if not found.
IUnitTestModule* getUnitTestModule(const String& name, DiagnosticSink* sink = nullptr);
- /// Given a tool name return it's function pointer. Or nullptr on failure.
+ /// Given a tool name return it's function pointer. Or nullptr on failure.
InnerMainFunc getToolFunction(const String& name, DiagnosticSink* sink = nullptr);
- /// Execute the server
+ /// Execute the server
SlangResult execute();
- /// Dtor
+ /// Dtor
~TestServer();
protected:
@@ -79,20 +76,23 @@ protected:
bool m_quit = false;
- ComPtr<slang::IGlobalSession> m_session; /// The slang session. Is created on demand
+ ComPtr<slang::IGlobalSession> m_session; /// The slang session. Is created on demand
- Dictionary<String, ComPtr<ISlangSharedLibrary>> m_sharedLibraryMap; ///< Maps tool names to the dll
- Dictionary<String, IUnitTestModule*> m_unitTestModules; ///< All the unit test modules.
+ Dictionary<String, ComPtr<ISlangSharedLibrary>>
+ m_sharedLibraryMap; ///< Maps tool names to the dll
+ Dictionary<String, IUnitTestModule*> m_unitTestModules; ///< All the unit test modules.
- String m_exePath; ///< Path to executable (including exe name)
- String m_exeDirectory; ///< The directory that holds the exe
+ String m_exePath; ///< Path to executable (including exe name)
+ String m_exeDirectory; ///< The directory that holds the exe
- RefPtr<JSONRPCConnection> m_connection; ///< RPC connection, recieves calls to execute and returns results via JSON-RPC
+ RefPtr<JSONRPCConnection> m_connection; ///< RPC connection, recieves calls to execute and
+ ///< returns results via JSON-RPC
};
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!! TestServer !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
-namespace SlangCTool {
+namespace SlangCTool
+{
static void _diagnosticCallback(char const* message, void* userData)
{
@@ -100,17 +100,23 @@ static void _diagnosticCallback(char const* message, void* userData)
writer->write(message, strlen(message));
}
-SlangResult innerMain(StdWriters* stdWriters, slang::IGlobalSession* sharedSession, int argc, const char* const* argv)
+SlangResult innerMain(
+ StdWriters* stdWriters,
+ slang::IGlobalSession* sharedSession,
+ int argc,
+ const char* const* argv)
{
// Assume we will used the shared session
ComPtr<slang::IGlobalSession> session(sharedSession);
// The sharedSession always has a pre-loaded core module.
// This differed test checks if the command line has an option to setup the core module.
- // If so we *don't* use the sharedSession, and create a new session without the core module just for this compilation.
+ // If so we *don't* use the sharedSession, and create a new session without the core module just
+ // for this compilation.
if (TestToolUtil::hasDeferredCoreModule(Index(argc - 1), argv + 1))
{
- SLANG_RETURN_ON_FAIL(slang_createGlobalSessionWithoutCoreModule(SLANG_API_VERSION, session.writeRef()));
+ SLANG_RETURN_ON_FAIL(
+ slang_createGlobalSessionWithoutCoreModule(SLANG_API_VERSION, session.writeRef()));
}
ComPtr<slang::ICompileRequest> compileRequest;
@@ -125,7 +131,9 @@ SlangResult innerMain(StdWriters* stdWriters, slang::IGlobalSession* sharedSessi
compileRequest->setWriter(channel, stdWriters->getWriter(channel));
}
- compileRequest->setDiagnosticCallback(&_diagnosticCallback, stdWriters->getWriter(SLANG_WRITER_CHANNEL_STD_ERROR));
+ compileRequest->setDiagnosticCallback(
+ &_diagnosticCallback,
+ stdWriters->getWriter(SLANG_WRITER_CHANNEL_STD_ERROR));
compileRequest->setCommandLineCompilerMode();
{
@@ -143,11 +151,13 @@ SlangResult innerMain(StdWriters* stdWriters, slang::IGlobalSession* sharedSessi
try
#endif
{
- // Run the compiler (this will produce any diagnostics through SLANG_WRITER_TARGET_TYPE_DIAGNOSTIC).
+ // Run the compiler (this will produce any diagnostics through
+ // SLANG_WRITER_TARGET_TYPE_DIAGNOSTIC).
compileRes = compileRequest->compile();
// If the compilation failed, then get out of here...
- // Turn into an internal Result -> such that return code can be used to vary result to match previous behavior
+ // Turn into an internal Result -> such that return code can be used to vary result to match
+ // previous behavior
compileRes = SLANG_FAILED(compileRes) ? SLANG_E_INTERNAL_FAIL : compileRes;
}
#ifndef _DEBUG
@@ -248,12 +258,16 @@ IUnitTestModule* TestServer::getUnitTestModule(const String& name, DiagnosticSin
const char funcName[] = "slangUnitTestGetModule";
// get the unit test export name
- UnitTestGetModuleFunc getModuleFunc = (UnitTestGetModuleFunc)sharedLibrary->findFuncByName(funcName);
+ UnitTestGetModuleFunc getModuleFunc =
+ (UnitTestGetModuleFunc)sharedLibrary->findFuncByName(funcName);
if (!getModuleFunc)
{
if (sink)
{
- sink->diagnose(SourceLoc(), ServerDiagnostics::unableToFindFunctionInSharedLibrary, funcName);
+ sink->diagnose(
+ SourceLoc(),
+ ServerDiagnostics::unableToFindFunctionInSharedLibrary,
+ funcName);
}
return nullptr;
}
@@ -294,9 +308,12 @@ TestServer::InnerMainFunc TestServer::getToolFunction(const String& name, Diagno
auto func = (InnerMainFunc)sharedLibrary->findFuncByName(funcName);
if (!func && sink)
{
- sink->diagnose(SourceLoc(), ServerDiagnostics::unableToFindFunctionInSharedLibrary, funcName);
+ sink->diagnose(
+ SourceLoc(),
+ ServerDiagnostics::unableToFindFunctionInSharedLibrary,
+ funcName);
}
-
+
return func;
}
@@ -315,7 +332,7 @@ SlangResult TestServer::_executeSingle()
switch (msgType)
{
- case JSONRPCMessageType::Call:
+ case JSONRPCMessageType::Call:
{
JSONRPCCall call;
SLANG_RETURN_ON_FAIL(m_connection->getRPCOrSendError(&call));
@@ -341,9 +358,11 @@ SlangResult TestServer::_executeSingle()
return m_connection->sendError(JSONRPC::ErrorCode::MethodNotFound, call.id);
}
}
- default:
+ default:
{
- return m_connection->sendError(JSONRPC::ErrorCode::InvalidRequest, m_connection->getCurrentMessageId());
+ return m_connection->sendError(
+ JSONRPC::ErrorCode::InvalidRequest,
+ m_connection->getCurrentMessageId());
}
}
@@ -391,7 +410,7 @@ SlangResult TestServer::_executeUnitTest(const JSONRPCCall& call)
TestReporter testReporter;
testModule->setTestReporter(&testReporter);
-
+
// Assume we will used the shared session
slang::IGlobalSession* session = getOrCreateGlobalSession();
if (!session)
@@ -441,7 +460,7 @@ SlangResult TestServer::_executeTool(const JSONRPCCall& call)
auto id = m_connection->getPersistentValue(call.id);
TestServerProtocol::ExecuteToolTestArgs args;
-
+
SLANG_RETURN_ON_FAIL(m_connection->toNativeArgsOrSendError(call.params, &args, id));
auto sink = m_connection->getSink();
@@ -462,7 +481,7 @@ SlangResult TestServer::_executeTool(const JSONRPCCall& call)
// Work out the args sent to the shared library
List<const char*> toolArgs;
- // Add the 'exe' name
+ // Add the 'exe' name
toolArgs.add(args.toolName.getBuffer());
// Add the args
@@ -483,12 +502,13 @@ SlangResult TestServer::_executeTool(const JSONRPCCall& call)
stdWriters.setWriter(SLANG_WRITER_CHANNEL_STD_OUTPUT, stdOutWriter);
// HACK, to make behavior the same as previously
- if (args.toolName== "slangc")
+ if (args.toolName == "slangc")
{
stdWriters.setWriter(SLANG_WRITER_CHANNEL_DIAGNOSTIC, stdErrorWriter);
}
- const SlangResult funcRes = func(&stdWriters, session, int(toolArgs.getCount()), toolArgs.begin());
+ const SlangResult funcRes =
+ func(&stdWriters, session, int(toolArgs.getCount()), toolArgs.begin());
TestServerProtocol::ExecutionResult result;
result.result = funcRes;
@@ -504,8 +524,7 @@ SlangResult TestServer::execute()
while (m_connection->isActive() && !m_quit)
{
// Failure doesn't make the execution terminate
- [[maybe_unused]]
- const SlangResult res = _executeSingle();
+ [[maybe_unused]] const SlangResult res = _executeSingle();
}
return SLANG_OK;
@@ -515,8 +534,7 @@ SlangResult TestServer::execute()
void TestReporter::message(TestMessageType type, const char* message)
{
- if (type == TestMessageType::RunError ||
- type == TestMessageType::TestFailure)
+ if (type == TestMessageType::RunError || type == TestMessageType::TestFailure)
{
m_failCount++;
}
@@ -524,7 +542,11 @@ void TestReporter::message(TestMessageType type, const char* message)
m_buf << message << "\n";
}
-void TestReporter::addResultWithLocation(TestResult result, const char* testText, const char* file, int line)
+void TestReporter::addResultWithLocation(
+ TestResult result,
+ const char* testText,
+ const char* file,
+ int line)
{
if (result == TestResult::Fail)
{
@@ -536,7 +558,11 @@ void TestReporter::addResultWithLocation(TestResult result, const char* testText
}
}
-void TestReporter::addResultWithLocation(bool testSucceeded, const char* testText, const char* file, int line)
+void TestReporter::addResultWithLocation(
+ bool testSucceeded,
+ const char* testText,
+ const char* file,
+ int line)
{
m_testCount++;
@@ -573,5 +599,5 @@ SlangResult _execute(int argc, const char* const* argv)
int main(int argc, const char* const* argv)
{
- return (int)Slang::TestToolUtil::getReturnCode(TestServer:: _execute(argc, argv));
+ return (int)Slang::TestToolUtil::getReturnCode(TestServer::_execute(argc, argv));
}
diff --git a/tools/unit-test/slang-unit-test.cpp b/tools/unit-test/slang-unit-test.cpp
index 8b57b375b..61f778c9a 100644
--- a/tools/unit-test/slang-unit-test.cpp
+++ b/tools/unit-test/slang-unit-test.cpp
@@ -1,4 +1,5 @@
#include "slang-unit-test.h"
+
#include "slang.h"
#include "source/core/slang-basic.h"
@@ -14,10 +15,7 @@ public:
Slang::List<SlangUnitTest> tests;
ITestReporter* testReporter = nullptr;
- virtual SLANG_NO_THROW SlangInt SLANG_MCALL getTestCount() override
- {
- return tests.getCount();
- }
+ virtual SLANG_NO_THROW SlangInt SLANG_MCALL getTestCount() override { return tests.getCount(); }
virtual SLANG_NO_THROW const char* SLANG_MCALL getTestName(SlangInt index) override
{
return tests[index].name;
@@ -33,11 +31,7 @@ public:
testReporter = reporter;
}
- virtual SLANG_NO_THROW void SLANG_MCALL destroy() override
- {
- tests = decltype(tests)();
- }
-
+ virtual SLANG_NO_THROW void SLANG_MCALL destroy() override { tests = decltype(tests)(); }
};
SlangUnitTestModule* _getTestModule()
@@ -53,13 +47,13 @@ ITestReporter* getTestReporter()
extern "C"
{
-SLANG_DLL_EXPORT IUnitTestModule* slangUnitTestGetModule()
-{
- return _getTestModule();
-}
+ SLANG_DLL_EXPORT IUnitTestModule* slangUnitTestGetModule()
+ {
+ return _getTestModule();
+ }
}
UnitTestRegisterHelper::UnitTestRegisterHelper(const char* name, UnitTestFunc testFunc)
{
- _getTestModule()->tests.add(SlangUnitTest{ name, testFunc });
+ _getTestModule()->tests.add(SlangUnitTest{name, testFunc});
}
diff --git a/tools/unit-test/slang-unit-test.h b/tools/unit-test/slang-unit-test.h
index 8f96f6805..c63fb8a10 100644
--- a/tools/unit-test/slang-unit-test.h
+++ b/tools/unit-test/slang-unit-test.h
@@ -5,8 +5,9 @@
enum class TestResult
{
- // NOTE! Must keep in order such that combine is meaningful. That is larger values are higher precident - and a series of tests that has lots of passes
- // and a fail, is still a fail overall.
+ // NOTE! Must keep in order such that combine is meaningful. That is larger values are higher
+ // precident - and a series of tests that has lots of passes and a fail, is still a fail
+ // overall.
Ignored,
Pass,
ExpectedFail,
@@ -15,9 +16,9 @@ enum class TestResult
enum class TestMessageType
{
- Info, ///< General info (may not be shown depending on verbosity setting)
- TestFailure, ///< Describes how a test failure took place
- RunError, ///< Describes an error that caused a test not to actually correctly run
+ Info, ///< General info (may not be shown depending on verbosity setting)
+ TestFailure, ///< Describes how a test failure took place
+ RunError, ///< Describes an error that caused a test not to actually correctly run
};
class ITestReporter
@@ -25,8 +26,10 @@ class ITestReporter
public:
virtual SLANG_NO_THROW void SLANG_MCALL startTest(const char* testName) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL addResult(TestResult result) = 0;
- virtual SLANG_NO_THROW void SLANG_MCALL addResultWithLocation(TestResult result, const char* testText, const char* file, int line) = 0;
- virtual SLANG_NO_THROW void SLANG_MCALL addResultWithLocation(bool testSucceeded, const char* testText, const char* file, int line) = 0;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ addResultWithLocation(TestResult result, const char* testText, const char* file, int line) = 0;
+ virtual SLANG_NO_THROW void SLANG_MCALL
+ addResultWithLocation(bool testSucceeded, const char* testText, const char* file, int line) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL addExecutionTime(double time) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL message(TestMessageType type, const char* message) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL endTest() = 0;
@@ -60,24 +63,35 @@ public:
UnitTestRegisterHelper(const char* name, UnitTestFunc testFunc);
};
-class AbortTestException {};
+class AbortTestException
+{
+};
typedef IUnitTestModule* (*UnitTestGetModuleFunc)();
-#define SLANG_UNIT_TEST(name) \
-void _##name##_impl(UnitTestContext* unitTestContext); \
-void name(UnitTestContext* unitTestContext)\
-{\
- try { _##name##_impl(unitTestContext); } catch (AbortTestException&){} \
-}\
-UnitTestRegisterHelper _##name##RegisterHelper(#name, name); \
-void _##name##_impl(UnitTestContext* unitTestContext)
+#define SLANG_UNIT_TEST(name) \
+ void _##name##_impl(UnitTestContext* unitTestContext); \
+ void name(UnitTestContext* unitTestContext) \
+ { \
+ try \
+ { \
+ _##name##_impl(unitTestContext); \
+ } \
+ catch (AbortTestException&) \
+ { \
+ } \
+ } \
+ UnitTestRegisterHelper _##name##RegisterHelper(#name, name); \
+ void _##name##_impl(UnitTestContext* unitTestContext)
#define SLANG_CHECK(x) getTestReporter()->addResultWithLocation((x), #x, __FILE__, __LINE__);
-#define SLANG_CHECK_ABORT(x) \
- { \
- bool _slang_check_result = (x); \
- getTestReporter()->addResultWithLocation(_slang_check_result, #x, __FILE__, __LINE__); \
- if (!_slang_check_result) throw AbortTestException(); \
+#define SLANG_CHECK_ABORT(x) \
+ { \
+ bool _slang_check_result = (x); \
+ getTestReporter()->addResultWithLocation(_slang_check_result, #x, __FILE__, __LINE__); \
+ if (!_slang_check_result) \
+ throw AbortTestException(); \
}
-#define SLANG_IGNORE_TEST getTestReporter()->addResult(TestResult::Ignored); throw AbortTestException();
+#define SLANG_IGNORE_TEST \
+ getTestReporter()->addResult(TestResult::Ignored); \
+ throw AbortTestException();
diff --git a/tools/vk-pipeline-create/main.cpp b/tools/vk-pipeline-create/main.cpp
index f9acd69ac..67301a2a0 100644
--- a/tools/vk-pipeline-create/main.cpp
+++ b/tools/vk-pipeline-create/main.cpp
@@ -3,19 +3,19 @@
// This tools reads a gfx pipeline dump file and replays the pipeline creation to trigger
// shader compilation in the driver.
//
-#include "slang.h"
-#include "slang-com-ptr.h"
-
-#include "examples/hello-world/vulkan-api.h"
-#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-stream.h"
+#include "../../source/core/slang-string-util.h"
+#include "examples/hello-world/vulkan-api.h"
+#include "slang-com-ptr.h"
#include "slang-gfx.h"
+#include "slang.h"
+
#include <chrono>
#if SLANG_WINDOWS_FAMILY
-# include <windows.h>
+#include <windows.h>
#else
-# include <dlfcn.h>
+#include <dlfcn.h>
#endif
using namespace Slang;
@@ -42,7 +42,10 @@ struct PipelineCreationReplay
{
Index position;
List<uint8_t>& fileBlob;
- Reader(List<uint8_t>& blob, Index pos) : fileBlob(blob), position(pos) {}
+ Reader(List<uint8_t>& blob, Index pos)
+ : fileBlob(blob), position(pos)
+ {
+ }
template<typename T>
void readRaw(T& val)
{
@@ -106,7 +109,10 @@ struct PipelineCreationReplay
reader.readRaw(createInfo.bindingCount);
List<VkDescriptorSetLayoutBinding> bindings;
bindings.setCount(createInfo.bindingCount);
- memcpy(bindings.getBuffer(), reader.getPtr(), sizeof(VkDescriptorSetLayoutBinding) * bindings.getCount());
+ memcpy(
+ bindings.getBuffer(),
+ reader.getPtr(),
+ sizeof(VkDescriptorSetLayoutBinding) * bindings.getCount());
createInfo.pBindings = bindings.getBuffer();
vkAPI.vkCreateDescriptorSetLayout(vkAPI.device, &createInfo, nullptr, &layout);
@@ -134,7 +140,10 @@ struct PipelineCreationReplay
reader.readRaw(createInfo.pushConstantRangeCount);
List<VkPushConstantRange> pushConstants;
pushConstants.setCount(createInfo.pushConstantRangeCount);
- memcpy(pushConstants.getBuffer(), reader.getPtr(), sizeof(VkPushConstantRange) * createInfo.pushConstantRangeCount);
+ memcpy(
+ pushConstants.getBuffer(),
+ reader.getPtr(),
+ sizeof(VkPushConstantRange) * createInfo.pushConstantRangeCount);
createInfo.pPushConstantRanges = pushConstants.getBuffer();
vkAPI.vkCreatePipelineLayout(vkAPI.device, &createInfo, nullptr, &layout);
@@ -160,8 +169,14 @@ struct PipelineCreationReplay
VkPipeline pipeline = VK_NULL_HANDLE;
auto startTime = std::chrono::high_resolution_clock::now();
-
- if (vkAPI.vkCreateComputePipelines(vkAPI.device, VK_NULL_HANDLE, 1, &createInfo, nullptr, &pipeline) == 0)
+
+ if (vkAPI.vkCreateComputePipelines(
+ vkAPI.device,
+ VK_NULL_HANDLE,
+ 1,
+ &createInfo,
+ nullptr,
+ &pipeline) == 0)
printf("done");
else
printf("failed");
@@ -203,8 +218,11 @@ struct PipelineCreationReplay
loadPipeline(pipelineIndex, pipelineOffsets[pipelineIndex]);
}
- for (auto p: descSetLayouts)
- vkAPI.vkDestroyDescriptorSetLayout(vkAPI.device, *KeyValueDetail::getValue(&p), nullptr);
+ for (auto p : descSetLayouts)
+ vkAPI.vkDestroyDescriptorSetLayout(
+ vkAPI.device,
+ *KeyValueDetail::getValue(&p),
+ nullptr);
for (auto p : pipelineLayouts)
vkAPI.vkDestroyPipelineLayout(vkAPI.device, *KeyValueDetail::getValue(&p), nullptr);
for (auto p : shaderModules)