flutter3d
Showcase Changelog 62 packages API reference

Particles that light: the source

since 0.2.0 Physics and particles

Regions the guide quotes: emit (line 40), light (line 63), advance (line 70), follow (line 72), check (line 81).

1/// A torch whose flame lights the room it burns in, measured from the
2/// particles themselves rather than from a light somebody hand-tuned to
3/// match.
4///
5/// Quoted by `particle_lights.md` and shown whole in the Source tab.
6library;
7
8import 'dart:math' as math;
9
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_particles/flutter3d_particles.dart';
12import 'package:flutter3d_showcase/src/demo/demo.dart';
14/// Mixing in [LightEmitter] is the whole of what it takes to become a source
15/// the particle system will measure. It carries no fields of its own.
16final class _Torch with LightEmitter {}
18/// The `particle-lights` page: a torch flame that lights the room from its
19/// own particles. Its check is that the torch is lit by its flame.
20final class ParticleLightsDemo extends ShowcaseDemo {
21 late final ParticleSystem _particles;
22 late final LightNode _glow;
24 final _Torch _torch = _Torch();
26 static const double _rate = 240.0;
28 @override
29 void configureView(DemoContext context) {
30 context.orbit
31 ..distance = 4.0
32 ..pitch = 0.2
33 ..yaw = 0.4;
34 }
36 @override
37 Scene build(DemoContext context) {
38 _particles = ParticleSystem(capacity: 256, seed: 77);
40 final ParticleEffect flame = ParticleEffect(
41 count: 1,
42 emitter: const ConeEmitter(
43 speed: Range(0.8, 1.6),
44 halfAngle: 12.0 * math.pi / 180.0,
45 ),
46 lifetime: const Range(0.4, 0.7),
47 size: const Range(0.08, 0.14),
48 color: LinearColor(1.0, 0.6, 0.2, 1.0),
49 affectors: <ParticleAffector>[const ParticleFade(startsAt: 0.3)],
50 );
51 _particles.emit(
52 _torch,
53 flame,
54 Vector3.zero(),
55 perSecond: _rate,
56 direction: Vector3(0.0, 1.0, 0.0),
57 );
59 context.renderer.renderSteps.addContributor(
60 ParticleContributor(_particles),
61 );
63 _glow = LightNode(name: 'glow', type: LightType.point, intensity: 0.0);
65 return Scene()..add(_glow);
66 }
68 @override
69 void update(DemoContext context, double dt) {
70 _particles.update(dt);
72 final ParticleGlow glow = _torch.glow;
73 if (glow.isLocated) {
74 _glow.setPositionFrom(glow.center);
75 _glow.intensity = glow.power * 0.6 * LightNode.legacyUnit;
76 }
77 }
79 @override
80 void verify(Scene scene, FrameResult frame) {
81 if (_torch.glow.count == 0 || _torch.glow.power <= 0.0) {
82 throw StateError('the torch should be lit by its own flame');
83 }
84 if (frame.drawCalls < 1) {
85 throw StateError('the flame did not reach the frame');
86 }
87 }