flutter3d
Showcase Changelog 62 packages API reference

Smoke lit by the scene: the source

since 0.8.0 Physics and particles

Regions the guide quotes: upload (line 54), puffs (line 67), lights (line 74), orbit (line 124), swap (line 135), check (line 178), bake (line 187).

1/// Three puffs of smoke between a red light and a blue one, each side of each
2/// puff taking the light on that side through a six-way sheet.
3///
4/// Quoted by `six_way_smoke.md` and shown whole in the Source tab.
5library;
6
7import 'dart:math' as math;
8import 'dart:typed_data';
9
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_particles/flutter3d_particles.dart';
12import 'package:flutter3d_showcase/src/demo/demo.dart';
14/// The `six-way-smoke` page: three smoke puffs between a red light and a
15/// blue one. Its check is that the puffs are alive and drawn.
16final class SixWaySmokeDemo extends ShowcaseDemo {
17 /// Whether the puffs are lit through the six-way sheet; off draws them with
18 /// the plain contributor, the same from every side.
19 bool sixWay = true;
21 /// Where the two lights stand around the puffs, in radians, 0 to 2π: they
22 /// circle at a radius of 3 m, opposite each other.
23 double angle = 0.0;
25 /// Each light's intensity as a multiple of `LightNode.legacyUnit`,
26 /// 0 to 24.
27 double intensity = 12.0;
29 /// The sheet's ambient grey, 0 to 0.3, the light a puff takes from no side
30 /// at all.
31 double ambient = 0.0;
33 late final ParticleSystem _particles;
34 late final SixWayMaterial _sheet;
35 late final ParticleContributor _lit;
36 late final ParticleContributor _plain;
37 late ParticleContributor _shown;
38 late Registration _drawn;
39 late final LightNode _red;
40 late final LightNode _blue;
42 static const int _cell = 24;
44 @override
45 void configureView(DemoContext context) {
46 context.orbit
47 ..distance = 4.0
48 ..pitch = 0.0
49 ..yaw = 0.0;
50 }
52 @override
53 Scene build(DemoContext context) {
54 final SixWayTextures baked = _bakeBall(_cell);
55 TextureHandle upload(Uint8List bytes) =>
56 context.device.createTextureFromPixels(
57 width: _cell,
58 height: _cell,
59 format: TextureFormat.r8g8b8a8UNormInt,
60 pixels: ByteData.sublistView(bytes),
61 );
62 _sheet = SixWayMaterial(
63 positive: upload(baked.positive),
64 negative: upload(baked.negative),
65 );
67 _particles = ParticleSystem(capacity: 8);
68 _burst();
69 _lit = ParticleContributor(_particles, sixWay: _sheet);
70 _plain = ParticleContributor(_particles);
71 _shown = _lit;
72 _drawn = context.renderer.renderSteps.addContributor(_lit);
74 LightNode point(Vector3 color) => LightNode(
75 type: LightType.point,
76 intensity: intensity * LightNode.legacyUnit,
77 color: color.toLinearColor(),
78 )..castsShadow = false;
79 _red = point(Vector3(1.0, 0.2, 0.1));
80 _blue = point(Vector3(0.1, 0.2, 1.0));
81 final Scene scene = Scene()
82 ..ambientIntensity = 0.0
83 ..defaultLightWhenUnlit = false
84 ..add(_red)
85 ..add(_blue);
87 // A dark wall far behind, so the frame has something with bounds.
88 return scene..add(
89 MeshNode(
90 DeviceMesh.upload(
91 context.device,
92 CuboidShape(size: Vector3(40.0, 40.0, 0.1)).build(),
93 ),
94 RenderMaterial(
95 lighting: LightingModel.unlit,
96 baseColor: LinearColor.fromSrgb(0.04, 0.04, 0.05, 1.0),
97 ),
98 name: 'backdrop',
99 )..setPosition(0.0, 0.0, -6.0),
100 );
101 }
103 /// Three puffs in a row that stand still for eight seconds.
104 void _burst() {
105 for (final double x in <double>[-0.4, 0.0, 0.4]) {
106 _particles.burst(
107 ParticleEffect(
108 count: 1,
109 emitter: const SphereEmitter(speed: Range.exact(0.0)),
110 lifetime: const Range.exact(8.0),
111 size: const Range.exact(1.6),
112 color: LinearColor(1.0, 1.0, 1.0, 1.0),
113 ),
114 Vector3(x, 0.0, x * 0.5),
115 );
116 }
117 }
119 @override
120 void update(DemoContext context, double dt) {
121 _particles.update(dt);
122 if (_particles.aliveCount == 0) _burst();
124 final double c = math.cos(angle) * 3.0;
125 final double s = math.sin(angle) * 3.0;
126 // The slider is in multiples of the default, as the lights were built.
127 _red
128 ..setPosition(-c, 0.0, -s)
129 ..intensity = intensity * LightNode.legacyUnit;
130 _blue
131 ..setPosition(c, 0.0, s)
132 ..intensity = intensity * LightNode.legacyUnit;
133 _sheet.ambient = LinearColor(ambient, ambient, ambient);
135 final ParticleContributor shown = sixWay ? _lit : _plain;
136 if (!identical(shown, _shown)) {
137 _drawn.cancel();
138 _shown = shown;
139 _drawn = context.renderer.renderSteps.addContributor(shown);
140 }
141 }
143 @override
144 List<DemoControl> controls(DemoContext context) => <DemoControl>[
145 ToggleControl(
146 'Six-way sheet',
147 value: () => sixWay,
148 onChanged: (bool v) => sixWay = v,
149 ),
150 SliderControl(
151 'Lights around the puffs',
152 min: 0.0,
153 max: 2.0 * math.pi,
154 value: () => angle,
155 onChanged: (double v) => angle = v,
156 format: (double v) => '${(v * 180.0 / math.pi).round()} deg',
157 ),
158 SliderControl(
159 'Light intensity',
160 min: 0.0,
161 max: 24.0,
162 value: () => intensity,
163 onChanged: (double v) => intensity = v,
164 format: (double v) => v.toStringAsFixed(1),
165 ),
166 SliderControl(
167 'Ambient',
168 min: 0.0,
169 max: 0.3,
170 value: () => ambient,
171 onChanged: (double v) => ambient = v,
172 format: (double v) => v.toStringAsFixed(2),
173 ),
174 ];
176 @override
177 void verify(Scene scene, FrameResult frame) {
178 if (_particles.aliveCount != 3 || !_lit.isActive) {
179 throw StateError('the three puffs are not alive');
180 }
181 if (frame.drawCalls < 1) {
182 throw StateError('the frame drew nothing');
183 }
184 }
187/// A six-way sheet of one frame, [n] pixels square, of a soft ball of smoke.
188///
189/// Single scattering along the six axes: the light reaching a voxel from one
190/// side is the density summed along its row to that side's face, and each
191/// pixel marches once from the viewer through its column. The layout is the
192/// one `SixWayMaterial` reads: positive holds right, top, back and coverage,
193/// negative holds left, bottom, front and emission, unpremultiplied, and the
194/// rows run bottom to top.
195SixWayTextures _bakeBall(int n) {
196 const double extinction = 6.0;
197 final double step = 2.0 / n;
198 double at(int i) => -1.0 + (i + 0.5) * step;
199 int index(int x, int y, int z) => (z * n + y) * n + x;
201 final Float64List sigma = Float64List(n * n * n);
202 for (var z = 0; z < n; z++) {
203 for (var y = 0; y < n; y++) {
204 for (var x = 0; x < n; x++) {
205 final double r =
206 math.sqrt(at(x) * at(x) + at(y) * at(y) + at(z) * at(z)) / 0.8;
207 sigma[index(x, y, z)] = extinction * ((1.0 - r) * 2.5).clamp(0.0, 1.0);
208 }
209 }
210 }
212 // How much the smoke takes out between each voxel and the face each light
213 // comes in through: right, left, top, bottom, back (from -z), front.
214 final List<Float64List> depth = List<Float64List>.generate(
215 6,
216 (_) => Float64List(n * n * n),
217 );
218 void sweep(Float64List into, int Function(int a, int b, int s) voxel) {
219 for (var a = 0; a < n; a++) {
220 for (var b = 0; b < n; b++) {
221 var total = 0.0;
222 for (var s = 0; s < n; s++) {
223 final int i = voxel(a, b, s);
224 into[i] = total + sigma[i] * step * 0.5;
225 total += sigma[i] * step;
226 }
227 }
228 }
229 }
231 sweep(depth[0], (int y, int z, int s) => index(n - 1 - s, y, z));
232 sweep(depth[1], (int y, int z, int s) => index(s, y, z));
233 sweep(depth[2], (int x, int z, int s) => index(x, n - 1 - s, z));
234 sweep(depth[3], (int x, int z, int s) => index(x, s, z));
235 sweep(depth[4], (int x, int y, int s) => index(x, y, s));
236 sweep(depth[5], (int x, int y, int s) => index(x, y, n - 1 - s));
238 int byte(double v) => (v.clamp(0.0, 1.0) * 255.0 + 0.5).floor();
239 final Uint8List positive = Uint8List(n * n * 4);
240 final Uint8List negative = Uint8List(n * n * 4);
241 final Float64List lit = Float64List(6);
242 for (var y = 0; y < n; y++) {
243 for (var x = 0; x < n; x++) {
244 lit.fillRange(0, 6, 0.0);
245 var through = 1.0;
246 for (var z = n - 1; z >= 0; z--) {
247 final int i = index(x, y, z);
248 final double absorbed = 1.0 - math.exp(-sigma[i] * step);
249 final double weight = through * absorbed;
250 for (var d = 0; d < 6; d++) {
251 lit[d] += weight * math.exp(-depth[d][i]);
252 }
253 through *= 1.0 - absorbed;
254 }
255 final double coverage = 1.0 - through;
256 final double scale = coverage > 1e-4 ? 1.0 / coverage : 0.0;
257 final int out = (y * n + x) * 4;
258 positive
259 ..[out] = byte(lit[0] * scale)
260 ..[out + 1] = byte(lit[2] * scale)
261 ..[out + 2] = byte(lit[4] * scale)
262 ..[out + 3] = byte(coverage);
263 negative
264 ..[out] = byte(lit[1] * scale)
265 ..[out + 1] = byte(lit[3] * scale)
266 ..[out + 2] = byte(lit[5] * scale)
267 ..[out + 3] = 0;
268 }
269 }
270 return SixWayTextures(positive: positive, negative: negative);