Skip to content

Commit 7ab184e

Browse files
author
Aleksander Katan
committed
Add double buffering
1 parent a083cb1 commit 7ab184e

File tree

1 file changed

+12
-4
lines changed
  • apps/typegpu-docs/src/examples/simulation/slime-mold-3d

1 file changed

+12
-4
lines changed

apps/typegpu-docs/src/examples/simulation/slime-mold-3d/index.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,15 +103,19 @@ const Params = d.struct({
103103
evaporationRate: d.f32,
104104
});
105105

106-
const agentsData = root.createMutable(d.arrayOf(Agent, NUM_AGENTS));
106+
const agentsDataBuffers = [0, 1].map(() =>
107+
root.createBuffer(d.arrayOf(Agent, NUM_AGENTS)).$usage('storage')
108+
);
107109

110+
const mutableAgentsDataBuffers = agentsDataBuffers.map((b) => b.as('mutable'));
108111
root['~unstable'].createGuardedComputePipeline((x) => {
109112
'use gpu';
110113
randf.seed(x / NUM_AGENTS);
111114
const pos = randf.inUnitSphere().mul(resolution.x / 4).add(resolution.div(2));
112115
const center = resolution.div(2);
113116
const dir = std.normalize(center.sub(pos));
114-
agentsData.$[x] = Agent({ position: pos, direction: dir });
117+
mutableAgentsDataBuffers[0].$[x] = Agent({ position: pos, direction: dir });
118+
mutableAgentsDataBuffers[1].$[x] = Agent({ position: pos, direction: dir });
115119
}).dispatchThreads(NUM_AGENTS);
116120

117121
const params = root.createUniform(Params, {
@@ -134,7 +138,9 @@ const textures = [0, 1].map(() =>
134138
);
135139

136140
const computeLayout = tgpu.bindGroupLayout({
141+
oldAgents: { storage: d.arrayOf(Agent), access: 'readonly' },
137142
oldState: { storageTexture: d.textureStorage3d('r32float', 'read-only') },
143+
newAgents: { storage: d.arrayOf(Agent), access: 'mutable' },
138144
newState: { storageTexture: d.textureStorage3d('r32float', 'write-only') },
139145
});
140146

@@ -227,7 +233,7 @@ const updateAgents = tgpu['~unstable'].computeFn({
227233
const dims = std.textureDimensions(computeLayout.$.oldState);
228234
const dimsf = d.vec3f(dims);
229235

230-
const agent = agentsData.$[gid.x];
236+
const agent = computeLayout.$.oldAgents[gid.x];
231237
const random = randf.sample();
232238

233239
let direction = std.normalize(agent.direction);
@@ -296,7 +302,7 @@ const updateAgents = tgpu['~unstable'].computeFn({
296302
);
297303
}
298304

299-
agentsData.$[gid.x] = Agent({
305+
computeLayout.$.newAgents[gid.x] = Agent({
300306
position: newPos,
301307
direction,
302308
});
@@ -466,7 +472,9 @@ const blurPipeline = root['~unstable']
466472

467473
const bindGroups = [0, 1].map((i) =>
468474
root.createBindGroup(computeLayout, {
475+
oldAgents: agentsDataBuffers[i],
469476
oldState: textures[i],
477+
newAgents: agentsDataBuffers[1 - i],
470478
newState: textures[1 - i],
471479
})
472480
);

0 commit comments

Comments
 (0)