flutter3d
Showcase Changelog 62 packages API reference

Walking on terrain: the source

since 0.5.1 Physics and particles

Regions the guide quotes: field (line 55), walk (line 66), patrol (line 148), check (line 165).

1/// A character controller falling onto sloped ground and walking across it,
2/// its feet tracking a surface that is not flat.
3///
4/// Quoted by `heightfield_collision.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_physics/flutter3d_physics.dart';
12import 'package:flutter3d_showcase/src/demo/demo.dart';
13import 'package:flutter3d_showcase/src/demo/run_physics.dart';
15/// The `heightfield-collision` page: a walker landing on hilly ground and
16/// walking across it. Its check is that it landed on the slope and crossed
17/// the hills.
18final class HeightfieldCollisionDemo extends ShowcaseDemo {
19 late final CollisionWorld _world;
20 late final CollisionHeightfield _field;
21 late final CharacterController _controller;
22 late final MeshNode _body;
24 static const int _columns = 25;
25 static const int _rows = 25;
26 static const double _cellSize = 1.0;
27 static const double _step = 1 / 60;
28 static const int _steps = 60;
30 /// Rolling hills: a few metres of wavelength and about half a metre of
31 /// height, gentle enough to walk everywhere.
32 Float32List _heights() => Float32List.fromList(<double>[
33 for (var row = 0; row < _rows; row++)
34 for (var col = 0; col < _columns; col++)
35 0.55 * math.sin(col * 0.45) * math.cos(row * 0.38) +
36 0.25 * math.sin(col * 0.9 + row * 0.7),
37 ]);
39 /// Where the walker is heading, on a circle round the middle of the field.
40 static const double _ring = 6.0;
42 @override
43 void configureView(DemoContext context) {
44 context.orbit
45 ..distance = 7.0
46 ..pitch = 0.35
47 ..yaw = 0.6;
48 }
50 @override
51 Scene build(DemoContext context) {
52 _world = onRunPhysics(CollisionWorld());
53 final Float32List heights = _heights();
55 // Rolling hills, one height sample to the metre. `CollisionHeightfield`
56 // is the fifth shape and the first that is not one convex solid — it
57 // hands a query the triangles near it.
58 _field = CollisionHeightfield(
59 columns: _columns,
60 rows: _rows,
61 cellSize: _cellSize,
62 heights: heights,
63 );
64 _world.add(Collider(shape: _field, position: Vector3.zero()));
66 _controller = CharacterController(
67 world: _world,
68 position: Vector3(-_ring, 1.6, 0.0),
69 );
70 for (var i = 0; i < _steps; i++) {
71 _controller.step(_step, wishDirection: Vector3(0.0, 0.0, 1.0));
72 }
74 _body = MeshNode(
75 DeviceMesh.upload(
76 context.device,
77 CuboidShape(size: Vector3(0.7, 1.8, 0.7)).build(),
78 ),
79 RenderMaterial(
80 name: 'walker',
81 baseColor: LinearColor.fromSrgb(0.8, 0.5, 0.3, 1.0),
82 ),
83 name: 'walker',
84 )..setPositionFrom(_controller.position);
86 return Scene()
87 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
88 ..ambientIntensity = 0.3 * LightNode.legacyUnit
89 ..add(_terrain(context, heights))
90 ..add(_body)
91 ..add(
92 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
93 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
94 );
95 }
97 /// A visual grid matching [heights], for the same reason the collision
98 /// shape is: physics and rendering are separate packages here, so nothing
99 /// draws a `CollisionShape` for you.
100 MeshNode _terrain(DemoContext context, Float32List heights) {
101 final MeshBuilder builder = MeshBuilder(VertexLayout.standard);
102 final double width = (_columns - 1) * _cellSize;
103 final double depth = (_rows - 1) * _cellSize;
104 double at(int col, int row) =>
105 heights[row.clamp(0, _rows - 1) * _columns +
106 col.clamp(0, _columns - 1)];
107 final List<int> indices = <int>[];
108 for (var row = 0; row < _rows; row++) {
109 for (var col = 0; col < _columns; col++) {
110 indices.add(
111 builder.addVertex(
112 position: Vector3(
113 col * _cellSize - width * 0.5,
114 heights[row * _columns + col],
115 row * _cellSize - depth * 0.5,
116 ),
117 // The slope either side of the sample, turned into a normal.
118 normal: Vector3(
119 at(col - 1, row) - at(col + 1, row),
120 2.0 * _cellSize,
121 at(col, row - 1) - at(col, row + 1),
122 )..normalize(),
123 ),
124 );
125 }
126 }
127 for (var row = 0; row + 1 < _rows; row++) {
128 for (var col = 0; col + 1 < _columns; col++) {
129 final int tl = indices[row * _columns + col];
130 final int tr = indices[row * _columns + col + 1];
131 final int bl = indices[(row + 1) * _columns + col];
132 final int br = indices[(row + 1) * _columns + col + 1];
133 builder.addQuad(tl, bl, br, tr);
134 }
135 }
136 return MeshNode(
137 DeviceMesh.upload(context.device, builder.build()),
138 RenderMaterial(
139 name: 'ground',
140 baseColor: LinearColor.fromSrgb(0.6, 0.55, 0.4, 1.0),
141 ),
142 name: 'ground',
143 );
144 }
146 @override
147 void update(DemoContext context, double dt) {
148 // Chase a point that keeps a little ahead of the walker on the circle;
149 // the controller does the rest, up every hill and down again.
150 final Vector3 at = _controller.position;
151 final double ahead = math.atan2(at.z, at.x) + 0.35;
152 final Vector3 wish = Vector3(
153 _ring * math.cos(ahead) - at.x,
154 0.0,
155 _ring * math.sin(ahead) - at.z,
156 )..normalize();
157 _controller.step(_step, wishDirection: wish);
158 _body.setPositionFrom(_controller.position);
159 context.orbit.target.setFrom(_controller.position);
160 context.orbit.apply();
161 }
163 @override
164 void verify(Scene scene, FrameResult frame) {
165 if (!_controller.isGrounded) {
166 throw StateError('the walker should have landed on the slope');
167 }
168 final Vector3 at = _controller.position;
169 final double ground = _field.heightAt(Vector3.zero(), at.x, at.z);
170 final double feet = at.y - _controller.halfExtents.y;
171 if ((feet - ground).abs() > 0.15) {
172 throw StateError(
173 'the walker\'s feet should track the slope: feet $feet, ground $ground',
174 );
175 }
176 if (at.z <= 0.5) {
177 throw StateError('the walker should have walked across the hills');
178 }
179 if (frame.drawCalls < 2) {
180 throw StateError(
181 'the ground and the walker did not both reach the frame',
182 );
183 }
184 }