Terrain erosion: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: hill (line 47), erode (line 70), measure (line 187), check (line 208).
1/// One hill twice: on the left as it was made, on the right after scree has
2/// slid off it, rain has run down it, or both.
3///
4/// Quoted by `terrain_erosion.md` and shown whole in the Source tab.
5library;
7import 'dart:math' as math;
8import 'dart:typed_data';
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_showcase/src/demo/demo.dart';
12import 'package:flutter3d_sim/flutter3d_sim.dart';
14/// The `terrain-erosion` page: one hill as made and after erosion. Its check
15/// is that each erosion keeps the volume, lowers the top and puts material
16/// down at the foot.
17final class TerrainErosionDemo extends ShowcaseDemo {
18 /// 0 thermal, 1 hydraulic, 2 both.
19 int kind = 2;
21 /// The seed the erosion's droplets are drawn from, 1 to 20.
22 int seed = 7;
24 /// How many rain droplets run down the hill, 500 to 8000.
25 double droplets = 3000;
27 late final Heightfield _before;
28 late Heightfield _after;
29 late final MeshNode _left;
30 late final MeshNode _right;
31 late final DemoContext _context;
33 static const int _side = 33;
35 /// How far apart the two hills stand, in metres along x.
36 static const double _apart = 18.0;
39 void configureView(DemoContext context) {
40 context.orbit
41 ..distance = 46.0
42 ..pitch = 0.6
43 ..yaw = 0.0;
44 context.orbit.target.setValues(0.0, 2.0, 0.0);
45 }
47 /// A steep hill with a ridge across it: slopes past what loose ground
48 /// holds, and a valley for water to find. Heights in metres, a metre a
49 /// cell.
50 static Heightfield _hill() {
51 final heights = Float32List(_side * _side);
52 for (var z = 0; z < _side; z++) {
53 for (var x = 0; x < _side; x++) {
54 final double dx = x - 16.0, dz = z - 16.0;
55 final double r = math.sqrt(dx * dx + dz * dz);
56 heights[z * _side + x] =
57 math.max(0.0, 9.0 - 0.6 * r) +
58 1.2 * math.sin(x * 0.7) * math.cos(z * 0.5);
59 }
60 }
61 return Heightfield(
62 columns: _side,
63 rows: _side,
64 cellSize: 1.0,
65 heights: heights,
66 origin: WorldPosition(-16.0, 0.0, -16.0),
67 );
68 }
70 /// The hill after [kind]: scree first, then rain, when it is both. Each
71 /// answers a new field and leaves the one it was given alone.
72 Heightfield _erode(Heightfield field) => switch (kind) {
73 0 => erodeThermally(field, talus: 0.7, passes: 60),
74 1 => erodeHydraulically(field, seed: seed, droplets: droplets.round()),
75 _ => erodeHydraulically(
76 erodeThermally(field, talus: 0.7, passes: 60),
77 seed: seed,
78 droplets: droplets.round(),
79 ),
80 };
83 Scene build(DemoContext context) {
84 _context = context;
85 _before = _hill();
86 _after = _erode(_before);
87 _left = MeshNode(
88 DeviceMesh.upload(context.device, _meshOf(_before)),
89 RenderMaterial(
90 name: 'before',
91 baseColor: LinearColor.fromSrgb(0.55, 0.5, 0.42, 1.0),
92 ),
93 name: 'before',
94 )..setPosition(-_apart / 2, 0.0, 0.0);
95 _right = MeshNode(
96 DeviceMesh.upload(context.device, _meshOf(_after)),
97 RenderMaterial(
98 name: 'after',
99 baseColor: LinearColor.fromSrgb(0.45, 0.55, 0.38, 1.0),
100 ),
101 name: 'after',
102 )..setPosition(_apart / 2, 0.0, 0.0);
103 return Scene()
104 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
105 ..ambientIntensity = 0.3 * LightNode.legacyUnit
106 ..add(_left)
107 ..add(_right)
108 ..add(
109 // Low, so the gullies throw shadows of their own.
110 LightNode(name: 'sun', intensity: 2.8 * LightNode.legacyUnit)
111 ..setLocalForward(Vector3(-0.8, -0.5, -0.3)),
112 );
113 }
115 void _again() {
116 _after = _erode(_before);
117 _right.mesh = DeviceMesh.upload(_context.device, _meshOf(_after));
118 }
120 /// The field as triangles, two a cell, each vertex with the field's own
121 /// normal there.
122 static MeshData _meshOf(Heightfield field) {
123 final MeshBuilder builder = MeshBuilder(VertexLayout.standard);
124 final Vector3 normal = Vector3.zero();
125 for (var z = 0; z < field.rows; z++) {
126 for (var x = 0; x < field.columns; x++) {
127 final double wx = field.origin.x + x * field.cellSize;
128 final double wz = field.origin.z + z * field.cellSize;
129 field.normalAt(wx, wz, normal);
130 builder.addVertex(
131 position: Vector3(wx, field.sample(x, z), wz),
132 normal: normal.clone(),
133 );
134 }
135 }
136 for (var z = 0; z + 1 < field.rows; z++) {
137 for (var x = 0; x + 1 < field.columns; x++) {
138 final int a = z * field.columns + x;
139 final int b = a + 1;
140 final int c = a + field.columns;
141 final int d = c + 1;
142 builder
143 ..addTriangle(a, c, b)
144 ..addTriangle(b, c, d);
145 }
146 }
147 return builder.build();
148 }
151 List<DemoControl> controls(DemoContext context) => <DemoControl>[
152 ChoiceControl(
153 'Erosion',
154 options: const <String>['Thermal', 'Hydraulic', 'Both'],
155 index: () => kind,
156 onChanged: (int i) {
157 kind = i;
158 _again();
159 },
160 ),
161 SliderControl(
162 'Droplets',
163 min: 500,
164 max: 8000,
165 divisions: 15,
166 value: () => droplets,
167 onChanged: (double v) {
168 droplets = v;
169 _again();
170 },
171 format: (double v) => v.round().toString(),
172 ),
173 SliderControl(
174 'Seed',
175 min: 1,
176 max: 20,
177 divisions: 19,
178 value: () => seed.toDouble(),
179 onChanged: (double v) {
180 seed = v.round();
181 _again();
182 },
183 format: (double v) => v.round().toString(),
184 ),
185 ];
187 /// Every sample added up: the ground's volume, in cubic metres here.
188 static double _total(Heightfield f) =>
189 f.copyOfSamples().fold(0.0, (double a, double b) => a + b);
191 /// The volume of the samples at least [from] metres from the hill's top.
192 static double _foot(Heightfield f, {double from = 12.0}) {
193 var sum = 0.0;
194 for (var z = 0; z < f.rows; z++) {
195 for (var x = 0; x < f.columns; x++) {
196 final double dx = x - 16.0, dz = z - 16.0;
197 if (dx * dx + dz * dz >= from * from) sum += f.sample(x, z);
198 }
199 }
200 return sum;
201 }
203 /// The highest sample.
204 static double _peak(Heightfield f) => f.copyOfSamples().reduce(math.max);
207 void verify(Scene scene, FrameResult frame) {
208 // Each kind on its own, and both: the top is lower, the foot is higher,
209 // and none of the ground went anywhere.
210 for (var k = 0; k < 3; k++) {
211 kind = k;
212 final Heightfield after = _erode(_before);
213 final double was = _total(_before);
214 final double drift = (_total(after) - was).abs();
215 if (drift > was * 1e-4) {
216 throw StateError('erosion $k lost ${drift.toStringAsFixed(3)} m³');
217 }
218 if (!(_peak(after) < _peak(_before))) {
219 throw StateError('erosion $k left the top where it was');
220 }
221 if (!(_foot(after) > _foot(_before))) {
222 throw StateError('erosion $k put nothing down at the foot');
223 }
224 }
225 kind = 2;
226 if (frame.drawCalls < 2) throw StateError('the two hills were not drawn');
227 }
228}