Distance rolloff: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: curves (line 36), sample (line 44), compare (line 91).
1/// Three curves for how a sound gets quieter with distance, and what each
2/// one answers at the same handful of distances.
3///
4/// Quoted by `audio_rolloff.md` and shown whole in the Source tab.
5library;
7import 'package:flutter/widgets.dart';
8import 'package:flutter3d/flutter3d.dart';
9import 'package:flutter3d_audio/flutter3d_audio.dart';
10import 'package:flutter3d_showcase/src/demo/demo.dart';
12/// The `audio-rolloff` page: a speaker and the three rolloff curves plotted
13/// against distance. Its check is that every curve falls with distance and
14/// is silent past its maximum.
15final class AudioRolloffDemo extends ShowcaseDemo {
17 Scene build(DemoContext context) {
18 // The printed answer, for the second step of the guide.
19 _run();
20 final material = RenderMaterial(
21 name: 'speaker',
22 baseColor: LinearColor.fromSrgb(0.4, 0.6, 0.9, 1.0),
23 );
24 final node = MeshNode(
25 DeviceMesh.upload(context.device, SphereShape(segments: 16).build()),
26 material,
27 );
28 return Scene()
29 ..add(node)
30 ..add(
31 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
32 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
33 );
34 }
36 /// The three curves, by the name the plot and the readout give them.
37 static const curves = <String, Attenuation>{
38 'inverse': InverseRolloff(),
39 'linear': LinearRolloff(),
40 'exponential': ExponentialRolloff(),
41 };
43 static String _run() {
44 const distances = <double>[1.0, 5.0, 10.0, 20.0];
45 final lines = <String>[
46 for (final entry in curves.entries)
47 '${entry.key}: ${[for (final d in distances) entry.value.gainAt(d).toStringAsFixed(2)].join(', ')}',
48 ];
49 return 'gain at ${distances.join(', ')} metres\n${lines.join('\n')}';
50 }
52 /// The distance the plot marks, in metres, 0 to 30.
53 double distance = 6.0;
55 static const List<Color> _inks = <Color>[
56 Color(0xFF7FB0FF),
57 Color(0xFF6CE07C),
58 Color(0xFFE8A33D),
59 ];
62 List<DemoControl> controls(DemoContext context) => <DemoControl>[
63 SliderControl(
64 'Distance',
65 min: 0.0,
66 max: 30.0,
67 value: () => distance,
68 onChanged: (double v) => distance = v,
69 format: (double v) => '${v.toStringAsFixed(1)} m',
70 ),
71 ];
74 Widget? customBody(BuildContext buildContext, DemoContext context) =>
75 ColoredBox(
76 color: const Color(0xFF14161A),
77 child: Padding(
78 padding: const EdgeInsets.all(24),
79 child: CustomPaint(
80 painter: _CurvePainter(distance, _inks),
81 child: const SizedBox.expand(),
82 ),
83 ),
84 );
87 void verify(Scene scene, FrameResult frame) {
88 if (frame.drawCalls < 1) {
89 throw StateError('the speaker marker was not drawn');
90 }
91 const inverse = InverseRolloff();
92 const linear = LinearRolloff();
93 final closer = inverse.gainAt(5.0) > inverse.gainAt(10.0);
94 final silentPastMaximum = linear.gainAt(linear.maximum + 1.0) <= 0.0;
95 if (!closer || !silentPastMaximum) {
96 throw StateError(
97 'every curve should get quieter with distance and go silent past '
98 'its maximum',
99 );
100 }
101 }
102}
104/// The three curves against distance, with a marker where the slider is and
105/// what each curve answers there.
106final class _CurvePainter extends CustomPainter {
107 const _CurvePainter(this.distance, this.inks);
109 final double distance;
110 final List<Color> inks;
112 static const double _reach = 30.0;
115 void paint(Canvas canvas, Size size) {
116 final Rect plot = Rect.fromLTWH(
117 48.0,
118 8.0,
119 size.width - 64.0,
120 size.height - 56.0,
121 );
122 final Paint axis = Paint()
123 ..color = const Color(0x55FFFFFF)
124 ..style = PaintingStyle.stroke;
125 canvas.drawRect(plot, axis);
126 Offset at(double d, double gain) => Offset(
127 plot.left + d / _reach * plot.width,
128 plot.bottom - gain.clamp(0.0, 1.0) * plot.height,
129 );
130 void label(String text, Offset where, Color color) {
131 final TextPainter painter = TextPainter(
132 text: TextSpan(
133 text: text,
134 style: TextStyle(color: color, fontSize: 13),
135 ),
136 textDirection: TextDirection.ltr,
137 )..layout();
138 painter.paint(canvas, where);
139 }
141 for (var m = 0; m <= 30; m += 5) {
142 final Offset x = at(m.toDouble(), 0.0);
143 canvas.drawLine(
144 x,
145 Offset(x.dx, plot.top),
146 axis..color = const Color(0x22FFFFFF),
147 );
148 label(
149 '$m m',
150 Offset(x.dx - 10, plot.bottom + 4),
151 const Color(0xAAFFFFFF),
152 );
153 }
154 for (var g = 0; g <= 4; g++) {
155 label(
156 '${g * 25}%',
157 Offset(6, plot.bottom - g / 4 * plot.height - 8),
158 const Color(0xAAFFFFFF),
159 );
160 }
162 var i = 0;
163 for (final MapEntry<String, Attenuation> entry
164 in AudioRolloffDemo.curves.entries) {
165 final Path path = Path();
166 for (var step = 0; step <= 150; step++) {
167 final double d = step / 150 * _reach;
168 // A gain never runs off the top: at the source itself it is 1.
169 final Offset p = at(d, entry.value.gainAt(d));
170 step == 0 ? path.moveTo(p.dx, p.dy) : path.lineTo(p.dx, p.dy);
171 }
172 canvas.drawPath(
173 path,
174 Paint()
175 ..color = inks[i]
176 ..style = PaintingStyle.stroke
177 // Widest first: two curves that coincide stay both visible.
178 ..strokeWidth = 7.0 - 2.0 * i,
179 );
180 final double here = entry.value.gainAt(distance);
181 canvas.drawCircle(at(distance, here), 5.0, Paint()..color = inks[i]);
182 label(
183 '${entry.key}: ${(here * 100).round()}%',
184 Offset(plot.right - 170, plot.top + 8 + 18.0 * i),
185 inks[i],
186 );
187 i++;
188 }
189 canvas.drawLine(
190 at(distance, 0.0),
191 at(distance, 1.0),
192 Paint()
193 ..color = const Color(0x88FFFFFF)
194 ..strokeWidth = 1.5,
195 );
196 }
199 bool shouldRepaint(covariant _CurvePainter oldDelegate) => true;
200}