A particle pool in one draw call: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: system (line 36), effect (line 41), burst (line 49), advance (line 61), check (line 74).
1/// One pool of particles, drawn in a single instanced call however many
2/// effects are bursting out of it.
3///
4/// Quoted by `particle_pool.md` and shown whole in the Source tab.
5library;
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_particles/flutter3d_particles.dart';
9import 'package:flutter3d_showcase/src/demo/demo.dart';
11/// The `particle-pool` page: several effects bursting out of one pool, drawn
12/// in one call. Its check is the number of live particles.
13final class ParticlePoolDemo extends ShowcaseDemo {
14 late final ParticleSystem _particles;
15 late final ParticleEffect _sprayEffect;
16 late final ParticleContributor _contributor;
18 static const int _capacity = 512;
19 static const int _burstCount = 120;
21 // The point of the page is a pool that outlives any one burst; a burst
22 // that never repeated would never show it being reused.
23 static const double _pause = 1.0;
24 double _cooldown = 0.0;
27 void configureView(DemoContext context) {
28 context.orbit
29 ..distance = 4.0
30 ..pitch = 0.3
31 ..yaw = 0.5;
32 }
35 Scene build(DemoContext context) {
36 // A fixed seed, so the same burst comes out byte for byte on every run.
37 // That is what a `ParticleRandom` buys: not randomness, but a stream a
38 // particle owns from the moment it is born.
39 _particles = ParticleSystem(capacity: _capacity, seed: 20260919);
41 _sprayEffect = ParticleEffect(
42 count: _burstCount,
43 emitter: const SphereEmitter(speed: Range(1.5, 3.0)),
44 lifetime: const Range(0.8, 1.6),
45 size: const Range(0.05, 0.12),
46 color: LinearColor(1.0, 0.7, 0.3, 1.0),
47 );
49 _particles.burst(_sprayEffect, Vector3.zero());
50 _contributor = ParticleContributor(_particles);
51 context.renderer.renderSteps.addContributor(_contributor);
53 return Scene()..add(
54 LightNode(name: 'sun', intensity: 2.0 * LightNode.legacyUnit)
55 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
56 );
57 }
60 void update(DemoContext context, double dt) {
61 _particles.update(dt);
63 if (_particles.aliveCount == 0) {
64 _cooldown -= dt;
65 if (_cooldown <= 0.0) {
66 _particles.burst(_sprayEffect, Vector3.zero());
67 _cooldown = _pause;
68 }
69 }
70 }
73 void verify(Scene scene, FrameResult frame) {
74 if (_particles.aliveCount != _burstCount) {
75 throw StateError(
76 'expected $_burstCount live particles, got ${_particles.aliveCount}',
77 );
78 }
79 if (!_contributor.isActive || frame.drawCalls < 1) {
80 throw StateError('the pool did not reach the frame');
81 }
82 }
83}