Mesh particles: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: mesh (line 35), contributor (line 54), check (line 78).
1/// Every live particle drawn as a copy of a real mesh instead of a
2/// camera-facing quad, in one instanced call.
3///
4/// Quoted by `mesh_particles.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 `mesh-particles` page: shards drawn as instanced copies of a mesh.
12/// Its check is that they are alive and drawn.
13final class MeshParticlesDemo extends ShowcaseDemo {
14 late final ParticleSystem _particles;
15 late final ParticleEffect _debrisEffect;
16 late final MeshParticleContributor _contributor;
18 static const int _count = 40;
20 // Debris that fell once and lay still would leave nothing moving to look
21 // at once gravity settled it below the frame.
22 static const double _pause = 1.0;
23 double _cooldown = 0.0;
26 void configureView(DemoContext context) {
27 context.orbit
28 ..distance = 4.5
29 ..pitch = 0.25
30 ..yaw = 0.4;
31 }
34 Scene build(DemoContext context) {
35 // One shape, uploaded once. Every particle is a placement of it rather
36 // than a separate draw, which is what keeps this a single instanced call
37 // however many shards are on screen.
38 final DeviceMesh shard = DeviceMesh.upload(
39 context.device,
40 CuboidShape(size: Vector3(0.12, 0.12, 0.12)).build(),
41 );
43 _particles = ParticleSystem(capacity: _count, seed: 808);
44 _debrisEffect = ParticleEffect(
45 count: _count,
46 emitter: const SphereEmitter(speed: Range(1.0, 2.5)),
47 lifetime: const Range(1.0, 1.8),
48 size: const Range(0.6, 1.2),
49 color: LinearColor(0.8, 0.75, 0.7, 1.0),
50 affectors: <ParticleAffector>[const ParticleGravity(acceleration: -3.0)],
51 );
52 _particles.burst(_debrisEffect, Vector3.zero());
54 _contributor = MeshParticleContributor(_particles, mesh: shard);
55 context.renderer.renderSteps.addContributor(_contributor);
57 return Scene()..add(
58 LightNode(name: 'sun', intensity: 2.0 * LightNode.legacyUnit)
59 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
60 );
61 }
64 void update(DemoContext context, double dt) {
65 _particles.update(dt);
67 if (_particles.aliveCount == 0) {
68 _cooldown -= dt;
69 if (_cooldown <= 0.0) {
70 _particles.burst(_debrisEffect, Vector3.zero());
71 _cooldown = _pause;
72 }
73 }
74 }
77 void verify(Scene scene, FrameResult frame) {
78 if (!_contributor.isActive) {
79 throw StateError('the mesh particles should be alive and drawing');
80 }
81 if (_particles.aliveCount != _count || frame.drawCalls < 1) {
82 throw StateError('the shards did not reach the frame');
83 }
84 }
85}