A level is a scene, and the camera frames the whole party: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: levels (line 47), camera (line 182), frame (line 208), next (line 241).
1/// A Flame game that moves from one level to the next with
2/// `replaceScene3d`, and a `ViewCamera` that frames the whole party as it
3/// walks.
4///
5/// Quoted by `flame_level_scene.md` and shown whole in the Source tab.
6library;
8import 'dart:math' as math;
10import 'package:flame/components.dart' show Component, TextComponent;
11import 'package:flame/game.dart';
12import 'package:flame_flutter3d/flame_flutter3d.dart';
13import 'package:flutter/widgets.dart';
14import 'package:flutter3d/flutter3d.dart';
15import 'package:flutter3d_showcase/src/demo/demo.dart';
16import 'package:flutter3d_showcase/src/demo/flame_layer.dart';
18/// Seconds on each level before the party moves on.
19const double _stay = 6.0;
21/// The `flame-level-scene` page: a party walking across a level of rocks
22/// that Flame swaps for the next with `replaceScene3d`. Its check is that
23/// the page opens on the first level and draws it.
24final class FlameLevelSceneDemo extends ShowcaseDemo {
25 late final _Tour _game;
26 late final Widget _body = Flutter3dFlameWidget(
27 game: _game,
28 existing: BorrowedRenderer(
29 device: _context.device,
30 renderer: _context.renderer,
31 ),
32 );
33 late final DemoContext _context;
36 void configureView(DemoContext context) {
37 context.orbit
38 ..distance = 14.0
39 ..pitch = 0.7
40 ..yaw = 0.0;
41 context.orbit.target.setValues(0.0, 0.0, 0.0);
42 }
45 Scene build(DemoContext context) {
46 _context = context;
47 // Two levels, each a scene of its own: its floor, its light, its air.
48 // The first is the one the game opens on; the second waits unseen.
49 final List<Scene> levels = <Scene>[
50 _level(
51 context.device,
52 floor: Vector4(0.36, 0.5, 0.3, 1.0),
53 air: Vector3(0.55, 0.6, 0.7),
54 rocks: Vector4(0.6, 0.58, 0.52, 1.0),
55 seed: 1,
56 ),
57 _level(
58 context.device,
59 floor: Vector4(0.3, 0.28, 0.34, 1.0),
60 air: Vector3(0.35, 0.3, 0.5),
61 rocks: Vector4(0.45, 0.4, 0.6, 1.0),
62 seed: 2,
63 ),
64 ];
65 _game = _Tour(context.camera, levels)
66 ..open3d(context.device, scene: levels.first);
67 return levels.first;
68 }
70 /// A floor, a sun and a scatter of rocks.
71 static Scene _level(
72 GraphicsDevice device, {
73 required Vector4 floor,
74 required Vector3 air,
75 required Vector4 rocks,
76 required int seed,
77 }) {
78 final math.Random random = math.Random(seed);
79 final DeviceMesh rock = DeviceMesh.upload(
80 device,
81 CuboidShape(size: Vector3(0.8, 1.2, 0.8)).build(),
82 );
83 final RenderMaterial stone = RenderMaterial(
84 name: 'rock',
85 baseColor: _fromSrgb(rocks),
86 );
87 final Scene level = Scene()
88 ..ambientColor = air.toLinearColor()
89 ..ambientIntensity = 0.35 * LightNode.legacyUnit
90 ..add(
91 MeshNode(
92 DeviceMesh.upload(
93 device,
94 CuboidShape(size: Vector3(20.0, 0.1, 20.0)).build(),
95 ),
96 RenderMaterial(name: 'floor', baseColor: _fromSrgb(floor)),
97 name: 'floor',
98 )..setPosition(0.0, -0.05, 0.0),
99 )
100 ..add(
101 LightNode(name: 'sun', intensity: 2.4 * LightNode.legacyUnit)
102 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
103 );
104 for (var i = 0; i < 14; i++) {
105 level.add(
106 MeshNode(rock, stone, name: 'rock $i')..setPosition(
107 random.nextDouble() * 18.0 - 9.0,
108 0.6,
109 random.nextDouble() * 18.0 - 9.0,
110 ),
111 );
112 }
113 return level;
114 }
117 void update(DemoContext context, double dt) =>
118 context.orbit.syncProjectionDepth(context.camera);
120 /// The Flame game the page runs, for a test that steps it without a window.
122 FlameGame get game => _game;
124 /// The two levels, in the order the party visits them.
126 List<Scene> get levels => _game.levels;
128 /// The level the game draws now.
130 Scene get level => _game.scene;
132 /// The camera the view camera moves.
134 CameraNode get camera => _game.camera3d;
136 /// The party's markers.
138 List<MeshNode> get party => _game.party;
140 /// Where the view camera wants to be this frame.
142 Vector3 get wantedEye {
143 final Vector3 eye = Vector3.zero();
144 _game.frameParty(eye, Vector3.zero());
145 return eye;
146 }
149 Widget? customBody(BuildContext buildContext, DemoContext context) => _body;
152 void verify(Scene scene, FrameResult frame) {
153 if (frame.drawCalls < 1) throw StateError('the first level was not drawn');
154 if (!identical(scene, _game.levels.first)) {
155 throw StateError('the page should open on the first level');
156 }
157 }
158}
160/// The party's colours, one a member.
161final List<Vector4> _colors = <Vector4>[
162 Vector4(0.95, 0.55, 0.2, 1.0),
163 Vector4(0.3, 0.7, 0.95, 1.0),
164 Vector4(0.6, 0.9, 0.35, 1.0),
165 Vector4(0.9, 0.4, 0.75, 1.0),
166];
168final class _Tour extends FlameGame with HasFlutter3d {
169 _Tour(this._eye, this.levels);
171 final CameraNode _eye;
172 final List<Scene> levels;
173 final List<MeshNode> party = <MeshNode>[];
174 late final TextComponent _caption = flameCaption('level one');
176 int _level = 0;
177 double _clock = 0.0;
180 CameraNode createCamera3d() => _eye;
183 void onOpen3d() {
184 final DeviceMesh ball = DeviceMesh.upload(
185 device,
186 SphereShape(segments: 20, radius: 0.4).build(),
187 );
188 for (var i = 0; i < _colors.length; i++) {
189 final MeshNode member = MeshNode(
190 ball,
191 RenderMaterial(name: 'member $i', baseColor: _fromSrgb(_colors[i])),
192 name: 'member $i',
193 );
194 party.add(member);
195 scene.add(member);
196 }
197 _walk();
198 // Eased each frame towards wherever `frameParty` says, after the party
199 // has walked: no one member decides where the camera goes.
200 addAll(<Component>[
201 ViewCameraComponent(
202 ViewCamera(camera: camera3d, view: frameParty, stiffness: 2.5),
203 ),
204 _caption,
205 ]);
206 }
208 /// Above and behind the party's middle, further back the more it spreads.
209 bool frameParty(Vector3 eye, Vector3 target) {
210 if (party.isEmpty) return false;
211 final Vector3 middle = party.fold(
212 Vector3.zero(),
213 (Vector3 sum, MeshNode m) => sum..add(m.readPosition()),
214 )..scale(1.0 / party.length);
215 final double spread = party.fold(
216 0.0,
217 (double far, MeshNode m) =>
218 math.max(far, m.readPosition().distanceTo(middle)),
219 );
220 target.setFrom(middle);
221 eye.setValues(
222 middle.x,
223 middle.y + 3.5 + spread * 1.5,
224 middle.z + 5.0 + spread * 1.5,
225 );
226 return true;
227 }
230 void update(double dt) {
231 // The party walks before the camera, which is one of the children
232 // `super.update` runs.
233 if (has3d && party.isNotEmpty) {
234 _clock += dt;
235 if (_clock >= _stay) _nextLevel();
236 _walk();
237 }
238 super.update(dt);
239 }
241 /// The next level: the party is carried across, then the scene is
242 /// replaced, and the camera goes with it. What the old level holds stays
243 /// there for the next visit.
244 void _nextLevel() {
245 _clock = 0.0;
246 _level = (_level + 1) % levels.length;
247 final Scene next = levels[_level];
248 for (final MeshNode member in party) {
249 member.removeFromParent();
250 next.add(member);
251 }
252 replaceScene3d(next);
253 _caption.text = _level == 0 ? 'level one' : 'level two';
254 }
256 /// Each level has its own walk: across the first, round the second, the
257 /// party spreading and closing as it goes.
258 void _walk() {
259 final double t = _clock / _stay;
260 final Vector3 middle = _level == 0
261 ? Vector3(-3.0, 0.4, 6.0 - 12.0 * t)
262 : Vector3(
263 5.0 * math.cos(t * 2.0 * math.pi),
264 0.4,
265 5.0 * math.sin(t * 2.0 * math.pi),
266 );
267 final double spread = 1.0 + 0.8 * math.sin(_clock * 1.3);
268 for (var i = 0; i < party.length; i++) {
269 final double angle = _clock * 0.8 + i * 2.0 * math.pi / party.length;
270 party[i].setPosition(
271 middle.x + spread * math.cos(angle),
272 middle.y,
273 middle.z + spread * math.sin(angle),
274 );
275 }
276 }
277}
279/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
280LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);