-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathComputeExample.cs
More file actions
241 lines (218 loc) · 9.73 KB
/
ComputeExample.cs
File metadata and controls
241 lines (218 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
namespace Pollus.Examples;
using Core.Assets;
using Pollus.Debugging;
using Pollus.ECS;
using Pollus.Engine;
using Pollus.Assets;
using Pollus.Engine.Camera;
using Pollus.Engine.Debug;
using Pollus.Engine.Rendering;
using Pollus.Graphics;
using Pollus.Graphics.Rendering;
using Pollus.Graphics.Windowing;
using Pollus.Mathematics;
using Pollus.Utils;
public partial class ComputeExample : IExample
{
public string Name => "compute";
[ShaderType]
partial struct Particle
{
public Vec2f Position;
public Vec2f Velocity;
}
[ShaderType]
partial struct SceneData
{
public float Time;
public float DeltaTime;
public uint Width;
public uint Height;
}
class ComputeData
{
public Handle<ComputeShader> Compute = Handle<ComputeShader>.Null;
public Handle<ParticleMaterial> ParticleMaterial = Handle<ParticleMaterial>.Null;
}
[Asset]
partial class ParticleMaterial : IMaterial
{
public static string Name => "particle";
public static VertexBufferLayout[] VertexLayouts => [];
public static RenderPipelineDescriptor PipelineDescriptor => RenderPipelineDescriptor.Default with
{
Label = "particle",
VertexState = new()
{
EntryPoint = "vs_main",
Layouts = VertexLayouts,
},
FragmentState = new()
{
EntryPoint = "fs_main",
},
PrimitiveState = PrimitiveState.Default with
{
Topology = PrimitiveTopology.TriangleStrip,
CullMode = CullMode.None,
FrontFace = FrontFace.CW,
},
};
public static BlendState? Blend => BlendState.Default with
{
Alpha = new()
{
SrcFactor = BlendFactor.SrcAlpha,
DstFactor = BlendFactor.OneMinusSrcAlpha,
Operation = BlendOperation.Add,
},
};
public required Handle<ShaderAsset> ShaderSource { get; set; }
public required StorageBufferBinding<Particle> ParticleBuffer { get; set; }
public IBinding[][] Bindings =>
[
[
new UniformBinding<SceneUniform>(),
ParticleBuffer
]
];
}
struct ComputePassData
{
public ResourceHandle<BufferResource> ParticleBuffer;
}
struct ParticlePassData
{
public ResourceHandle<TextureResource> ColorAttachment;
public ResourceHandle<BufferResource> ParticleBuffer;
}
IApplication? app;
public void Run()
{
app = Application.Builder
.AddPlugins([
new AssetPlugin() { RootPath = "assets" },
new RenderingPlugin(),
new MaterialPlugin<ParticleMaterial>(),
new RandomPlugin(),
new PerformanceTrackerPlugin(),
new UniformPlugin<SceneData, Param<Time, IWindow>>()
{
Extract = static (in param, ref sceneData) =>
{
var (time, window) = param;
sceneData.Time = (float)time.SecondsSinceStartup;
sceneData.DeltaTime = (float)time.DeltaTime;
sceneData.Width = (uint)window.Size.X;
sceneData.Height = (uint)window.Size.Y;
}
},
])
.AddResource(new ComputeData())
.AddSystems(CoreStage.Init, FnSystem.Create("Setup",
static (Commands commands, Random random, IWindow window,
ComputeData computeData, RenderAssets renderAssets, AssetServer assetServer,
Assets<ComputeShader> computeShaders, Assets<ParticleMaterial> particleMaterials,
Assets<StorageBuffer> particleBuffers) =>
{
commands.Spawn(Camera2D.Bundle);
var particleBuffer = StorageBuffer.From<Particle>(1_000_000, BufferUsage.CopyDst);
var particleBufferHandle = particleBuffers.Add(particleBuffer);
for (int i = 0; i < particleBuffer.Capacity; i++)
{
particleBuffer.Write<Particle>(i, new Particle()
{
Position = new Vec2f(random.NextFloat(0, window.Size.X), random.NextFloat(0, window.Size.Y)),
Velocity = random.NextVec2f().Normalized() * random.NextFloat(5f, 50f),
});
}
computeData.ParticleMaterial = particleMaterials.Add(new()
{
ShaderSource = assetServer.LoadAsync<ShaderAsset>("shaders/particle.wgsl"),
ParticleBuffer = new()
{
Buffer = particleBufferHandle,
BufferType = BufferBindingType.ReadOnlyStorage,
Visibility = ShaderStage.Vertex | ShaderStage.Fragment,
},
});
computeData.Compute = computeShaders.Add(new()
{
Label = "compute",
EntryPoint = "main",
Shader = assetServer.LoadAsync<ShaderAsset>("shaders/compute.wgsl"),
Bindings =
[
[
new StorageBufferBinding<Particle>()
{
Visibility = ShaderStage.Compute,
BufferType = BufferBindingType.Storage,
Buffer = particleBufferHandle,
},
new UniformBinding<SceneData>()
{
Visibility = ShaderStage.Compute,
}
]
]
});
}))
.AddSystems(CoreStage.PreRender, FnSystem.Create(new("PrepareRender")
{
RunsAfter = [FrameGraph2DPlugin.BeginFrame],
},
static (FrameGraph2D frameGraph) =>
{
frameGraph.FrameGraph.AddBuffer(BufferDescriptor.Storage<Particle>("particles_buffer", 1_000_000));
frameGraph.AddPass(RenderStep2D.Main,
static (ref FrameGraph<FrameGraph2DParam>.Builder builder, in FrameGraph2DParam param, ref ComputePassData data) => { data.ParticleBuffer = builder.Writes<BufferResource>("particles_buffer"); },
static (context, in param, in data) =>
{
var computeData = param.Resources.Get<ComputeData>();
var compute = param.RenderAssets.Get<ComputeRenderData>(computeData.Compute);
using var computeEncoder = context.GetCurrentCommandEncoder().BeginComputePass("""particles_compute""");
ComputeCommands.Builder
.SetPipeline(compute.Pipeline)
.SetBindGroups(0, compute.BindGroups)
.Dispatch((uint)MathF.Ceiling(1_000_000 / 256f), 1, 1)
.ApplyAndDispose(computeEncoder, param.RenderAssets);
});
frameGraph.AddPass(RenderStep2D.Main,
static (ref FrameGraph<FrameGraph2DParam>.Builder builder, in FrameGraph2DParam param, ref ParticlePassData data) =>
{
data.ColorAttachment = builder.Writes<TextureResource>(FrameGraph2D.Textures.ColorTarget);
data.ParticleBuffer = builder.Reads<BufferResource>("particles_buffer");
},
static (context, in param, in data) =>
{
var computeData = param.Resources.Get<ComputeData>();
var particleMaterial = param.RenderAssets.Get<MaterialRenderData>(computeData.ParticleMaterial);
using var renderEncoder = context.GetCurrentCommandEncoder().BeginRenderPass(new()
{
Label = """particles_render""",
ColorAttachments =
[
new()
{
View = context.Resources.GetTexture(data.ColorAttachment).TextureView.Native,
LoadOp = LoadOp.Load,
StoreOp = StoreOp.Store,
}
]
});
RenderCommands.Builder
.SetPipeline(particleMaterial.Pipeline)
.SetBindGroups(0, particleMaterial.BindGroups)
.Draw(4, 1_000_000, 0, 0)
.ApplyAndDispose(renderEncoder, param.RenderAssets);
});
}))
.Build();
app.Run();
}
public void Stop()
{
app?.Shutdown();
}
}