yum-mirror/slang

Making it easier to work with shaders

git clone https://git.yummers.dev/yum-mirror/slang

Yong HeShader-Object example (#1694)df7548ef6

master
2.1 KiB65 linesraw
1// shader-object.slang
2
3// This file implements a simple compute shader that transforms
4// input floating point numbers stored in a `RWStructuredBuffer`.
5// Specifically, for each number x from input buffer, compute
6// f(x) and store the result back in the same buffer.
7
8// The compute shader supports multiple transformation functions,
9// such add(x, c) which returns x+c, or mul(x, c) which returns x*c.
10// This functions are implemented as types that conforms to the
11// `ITransformer` interface.
12
13// The main entry point function takes a parameter of `ITransformer`
14// type, and applies the transformation to numbers in the input
15// buffer. By defining the shader parameter using interfaces,
16// we enable the flexiblity to generate either specialized compute
17// kernels that performs specific transformation or a general
18// kernel that can perform any transformations encoded by the
19// parameter at run-time, without changing any shader code or
20// host-application logic for setting and preparing shader parameters.
21
22// Defines the transformer interface, which implements a single
23// `transform` operation.
24interface ITransformer
25{
26    float transform(float x);
27}
28
29// Represents a transform function f(x) = x + c.
30struct AddTransformer : ITransformer
31{
32    float c;
33    float transform(float x) { return x + c + 10.0f; }
34};
35
36// Represents a transform function f(x) = x * c.
37struct MulTransformer : ITransformer
38{
39    float c;
40    float transform(float x) { return x * c; }
41};
42
43// Represents a composite function f(x) = f0(f1(x));
44struct CompositeTransformer : ITransformer
45{
46    ITransformer func0;
47    ITransformer func1;
48    float transform(float x)
49    {
50        return func0.transform(func1.transform(x));
51    }
52};
53
54// Main entry-point. Applies the transformation encoded by `transformer`
55// to all elements in `buffer`.
56[shader("compute")]
57[numthreads(4,1,1)]
58void computeMain(
59    uint3 sv_dispatchThreadID : SV_DispatchThreadID,
60    uniform RWStructuredBuffer<float> buffer,
61    uniform ITransformer transformer)
62{
63    var input = buffer[sv_dispatchThreadID.x];
64    buffer[sv_dispatchThreadID.x] = transformer.transform(input);
65}