flutter3d
Showcase Changelog 62 packages API reference

Terrain in tiles: the source

since 0.7.0 Simulation, audio and XR

Regions the guide quotes: live (line 56), choose (line 132), pick (line 143), field (line 211), tiles (line 225), lod (line 229).

1/// Ground cut into tiles, each buildable at several levels of detail, with a
2/// skirt closing the seam between a fine tile and a coarse neighbour.
3///
4/// Quoted by `terrain_tiles.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_showcase/src/demo/demo.dart';
12import 'package:flutter3d_sim/flutter3d_sim.dart';
14/// The `terrain-tiles` page: ground cut into tiles at several levels of
15/// detail around a moving eye. Its check is that a near tile picks the fine
16/// level and a far one the coarse.
17final class TerrainTilesDemo extends ShowcaseDemo {
18 late final String _report;
20 /// The distance within which tiles take the finest level, in metres, 4 to 16.
21 double nearest = 8.0;
23 /// Whether the eye circles the ground on its own; dragging the slider stops
24 /// it.
25 bool moving = true;
27 /// Where the eye stands on its circle round the ground, in radians, 0 to
28 /// 6.28.
29 double eyeAngle = 0.0;
31 late final HeightfieldTiles _tiles;
32 late final MeshNode _eye;
33 late final DemoContext _context;
34 final List<MeshNode> _nodes = <MeshNode>[];
35 final List<int?> _levels = <int?>[];
36 late final List<RenderMaterial> _paint;
37 double _clock = 0.0;
39 static const int _side = 33;
40 static const int _tileCells = 8;
42 @override
43 void configureView(DemoContext context) {
44 context.orbit
45 ..distance = 42.0
46 ..pitch = 0.95
47 ..yaw = 0.0;
48 context.orbit.target.setValues(16.0, 0.0, 16.0);
49 }
51 @override
52 Scene build(DemoContext context) {
53 _report = _run();
54 _context = context;
56 // A hilly field of 32 by 32 cells, cut into sixteen tiles, each of which
57 // can be drawn at three levels of detail. Which level is a question put
58 // to the chooser, tile by tile, every time the eye moves.
59 final Float32List heights = Float32List(_side * _side);
60 for (var row = 0; row < _side; row++) {
61 for (var col = 0; col < _side; col++) {
62 heights[row * _side + col] =
63 1.6 * math.sin(col * 0.28) * math.cos(row * 0.23) +
64 0.35 * math.sin(col * 1.1 + row * 0.9);
65 }
66 }
67 _tiles = HeightfieldTiles(
68 Heightfield(columns: _side, rows: _side, cellSize: 1.0, heights: heights),
69 tileCells: _tileCells,
70 levels: 3,
71 );
73 // One colour a level, so the choice can be seen.
74 _paint = <RenderMaterial>[
75 RenderMaterial(
76 name: 'fine',
77 baseColor: LinearColor.fromSrgb(0.45, 0.75, 0.4, 1.0),
78 ),
79 RenderMaterial(
80 name: 'middle',
81 baseColor: LinearColor.fromSrgb(0.85, 0.8, 0.35, 1.0),
82 ),
83 RenderMaterial(
84 name: 'coarse',
85 baseColor: LinearColor.fromSrgb(0.85, 0.5, 0.35, 1.0),
86 ),
87 ];
88 for (var i = 0; i < _tiles.tilesX * _tiles.tilesZ; i++) {
89 _levels.add(null);
90 _nodes.add(
91 MeshNode(
92 DeviceMesh.upload(
93 context.device,
94 MeshBuilder(VertexLayout.standard).build(),
95 ),
96 _paint[0],
97 name: 'tile $i',
98 ),
99 );
100 }
101 _eye = MeshNode(
102 DeviceMesh.upload(
103 context.device,
104 SphereShape(segments: 16, radius: 0.6).build(),
105 ),
106 RenderMaterial(
107 name: 'eye',
108 baseColor: LinearColor.fromSrgb(0.45, 0.65, 0.95, 1.0),
109 ),
110 name: 'eye',
111 );
112 final Scene scene = Scene()
113 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
114 ..ambientIntensity = 0.35 * LightNode.legacyUnit
115 ..add(_eye);
116 for (final MeshNode node in _nodes) {
117 scene.add(node);
118 }
119 return scene..add(
120 LightNode(name: 'sun', intensity: 2.6 * LightNode.legacyUnit)
121 ..setLocalForward(Vector3(-0.35, -1.0, -0.45)),
122 );
123 }
125 @override
126 void update(DemoContext context, double dt) {
127 _clock += dt;
128 if (moving) eyeAngle = _clock * 0.35;
129 final double ex = 16.0 + 11.0 * math.cos(eyeAngle);
130 final double ez = 16.0 + 11.0 * math.sin(eyeAngle);
131 _eye.setPosition(ex, 2.5, ez);
132 // Rebuilt from the slider each frame; a tile only changes when the answer
133 // does, and the band round each threshold keeps it from flickering.
134 final TileLevelChooser chooser = TileLevelChooser(
135 nearest: nearest,
136 levels: 3,
137 );
138 for (var tz = 0; tz < _tiles.tilesZ; tz++) {
139 for (var tx = 0; tx < _tiles.tilesX; tx++) {
140 final int i = tz * _tiles.tilesX + tx;
141 final double dx = (tx + 0.5) * _tileCells - ex;
142 final double dz = (tz + 0.5) * _tileCells - ez;
143 final int level = chooser.choose(
144 math.sqrt(dx * dx + dz * dz),
145 _levels[i],
146 );
147 if (level == _levels[i]) continue;
148 _levels[i] = level;
149 final BrushSurface tile = _tiles.build(
150 tx,
151 tz,
152 level: level,
153 material: 'ground',
154 );
155 _nodes[i]
156 ..mesh = DeviceMesh.upload(_context.device, _meshOf(tile))
157 ..material = _paint[level];
158 }
159 }
160 }
162 MeshData _meshOf(BrushSurface tile) {
163 final MeshBuilder builder = MeshBuilder(VertexLayout.standard);
164 final Float32List p = tile.positions;
165 final Float32List n = tile.normals;
166 for (var v = 0; v < p.length ~/ 3; v++) {
167 builder.addVertex(
168 position: Vector3(p[3 * v], p[3 * v + 1], p[3 * v + 2]),
169 normal: Vector3(n[3 * v], n[3 * v + 1], n[3 * v + 2]),
170 );
171 }
172 for (var i = 0; i + 2 < tile.indices.length; i += 3) {
173 builder.addTriangle(
174 tile.indices[i],
175 tile.indices[i + 1],
176 tile.indices[i + 2],
177 );
178 }
179 return builder.build();
180 }
182 @override
183 List<DemoControl> controls(DemoContext context) => <DemoControl>[
184 SliderControl(
185 'Fine detail within',
186 min: 4,
187 max: 16,
188 value: () => nearest,
189 onChanged: (double v) => nearest = v,
190 format: (double v) => '${v.toStringAsFixed(0)} m',
191 ),
192 ToggleControl(
193 'Move the eye',
194 value: () => moving,
195 onChanged: (bool v) => moving = v,
196 ),
197 SliderControl(
198 'Eye position',
199 min: 0,
200 max: 6.28,
201 value: () => eyeAngle % 6.28,
202 onChanged: (double v) {
203 moving = false;
204 eyeAngle = v;
205 },
206 format: (double v) => '${(v * 57.3).round()}°',
207 ),
208 ];
210 static String _run() {
211 // A gentle nine-by-nine slope, eight cells on a side.
212 final heights = Float32List(9 * 9);
213 for (var row = 0; row < 9; row++) {
214 for (var col = 0; col < 9; col++) {
215 heights[row * 9 + col] = (col + row) * 0.1;
216 }
217 }
218 final field = Heightfield(
219 columns: 9,
220 rows: 9,
221 cellSize: 1.0,
222 heights: heights,
223 );
225 final tiles = HeightfieldTiles(field, tileCells: 4, levels: 2);
226 final fine = tiles.build(0, 0, level: 0, material: 'ground');
227 final coarse = tiles.build(0, 0, level: 1, material: 'ground');
229 final chooser = TileLevelChooser(nearest: 20.0, levels: 2);
230 final near = chooser.choose(5.0, null);
231 final far = chooser.choose(60.0, null);
233 return '${tiles.tilesX}x${tiles.tilesZ} tiles, skirt depth '
234 '${tiles.skirtDepth.toStringAsFixed(3)} m\n'
235 'the fine build has ${fine.positions.length ~/ 3} vertices, the '
236 'coarse one has ${coarse.positions.length ~/ 3}\n'
237 'a tile 5 m away chooses level $near, one 60 m away chooses level $far';
238 }
240 @override
241 void verify(Scene scene, FrameResult frame) {
242 if (frame.drawCalls < 1) {
243 throw StateError('the ground marker was not drawn');
244 }
245 if (!_report.contains('chooses level 0') ||
246 !_report.contains('chooses level 1')) {
247 throw StateError(
248 'a near tile should choose the fine level and a far '
249 'one the coarse level',
250 );
251 }
252 }