flutter3d
Showcase Changelog 62 packages API reference

A Flame game that owns its 3D world: the source

since 0.8.3 The Flame bridge

Regions the guide quotes: open (line 79), world (line 139), crate (line 169).

1/// A Flame game that owns its 3D world through `HasFlutter3d`, with crates
2/// that hear a tap on what the camera shows.
3///
4/// Quoted by `flame_owned_world.md` and shown whole in the Source tab.
5library;
6
7import 'dart:math' as math;
8
9import 'package:flame/collisions.dart' show RectangleHitbox;
10import 'package:flame/components.dart';
11import 'package:flame/effects.dart';
12import 'package:flame/game.dart';
13import 'package:flame_flutter3d/flame_flutter3d.dart';
14import 'package:flutter/widgets.dart';
15import 'package:flutter3d/flutter3d.dart';
16import 'package:flutter3d_showcase/src/demo/demo.dart';
17import 'package:flutter3d_showcase/src/demo/flame_layer.dart';
19/// The `flame-owned-world` page: crates on a floor in a world the Flame game
20/// owns through `HasFlutter3d`. Its check is that a tap where a crate is
21/// drawn finds it.
22final class FlameOwnedWorldDemo extends ShowcaseDemo {
23 late final DemoContext _context;
24 late final Scene _scene;
25 late final _Yard _game;
26 late final Widget _body = flameOrbit(
27 _context,
28 Flutter3dFlameWidget(
29 game: _game,
30 existing: BorrowedRenderer(
31 device: _context.device,
32 renderer: _context.renderer,
33 ),
34 ),
35 );
37 late final bool _tapFound;
38 late final bool _flameMissed;
39 double _clock = 0.0;
40 int _next = 0;
42 @override
43 void configureView(DemoContext context) {
44 context.orbit
45 ..distance = 9.0
46 ..pitch = 0.75
47 ..yaw = 0.3;
48 context.orbit.target.setValues(0.0, 0.0, 0.0);
49 }
51 @override
52 Scene build(DemoContext context) {
53 _context = context;
54 final (bool found, bool missed) = _run(context.device);
55 _tapFound = found;
56 _flameMissed = missed;
58 _scene = Scene()
59 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
60 ..ambientIntensity = 0.3 * LightNode.legacyUnit
61 ..add(
62 MeshNode(
63 DeviceMesh.upload(
64 context.device,
65 CuboidShape(size: Vector3(9.0, 0.1, 9.0)).build(),
66 ),
67 RenderMaterial(
68 name: 'floor',
69 baseColor: LinearColor.fromSrgb(0.36, 0.4, 0.38, 1.0),
70 ),
71 name: 'floor',
72 )..setPosition(0.0, -0.05, 0.0),
73 )
74 ..add(
75 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
76 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
77 );
79 // The game is handed the page's device and scene; it builds the rest
80 // itself, in onOpen3d, once Flame has loaded it.
81 _game = _Yard(context.camera)..open3d(context.device, scene: _scene);
82 return _scene;
83 }
85 @override
86 void update(DemoContext context, double dt) {
87 context.orbit.syncProjectionDepth(context.camera);
88 // A tap every second and a half, on the next crate, through the same
89 // path a finger takes: the crate's place on screen, then the nearest
90 // crate drawn under it.
91 _clock += dt;
92 if (_clock < 1.5 || _game.crates.isEmpty) return;
93 _clock = 0.0;
94 final crate = _game.crates[_next++ % _game.crates.length];
95 final screen = _game.projector.toScreen(crate.scenePosition);
96 if (screen != null) _game.taps.nearestAt(screen)?.onTap3d(screen);
97 }
99 /// Checks, with no window, that a tap on where a crate is drawn finds it,
100 /// and that Flame's own test on the same point does not.
101 static (bool, bool) _run(GraphicsDevice device) {
102 final camera = CameraNode()
103 ..setPosition(0.0, 6.0, 6.0)
104 ..lookAt(Vector3(0.0, 0.0, -2.0));
105 final projector = BridgeProjector(
106 camera: camera,
107 viewSize: () => Vector2(800.0, 600.0),
108 );
109 final crate = _Crate(device, Scene(), Vector2(1.0, -3.0))..update(0.0);
110 final screen = projector.toScreen(crate.scenePosition)!;
111 return (
112 crate.hitAt3d(Tap3dProbe(screen: screen, projector: projector)),
113 !crate.containsPoint(screen),
114 );
115 }
117 /// The Flame game the page runs, for a test that steps it without a window.
118 @visibleForTesting
119 FlameGame get game => _game;
121 @override
122 Widget? customBody(BuildContext buildContext, DemoContext context) => _body;
124 @override
125 void verify(Scene scene, FrameResult frame) {
126 if (frame.drawCalls < 1) throw StateError('the floor was not drawn');
127 if (!_tapFound) {
128 throw StateError('a tap on where a crate is drawn did not find it');
129 }
130 if (!_flameMissed) {
131 throw StateError(
132 'Flame\'s own test found the crate at its drawn place, so this page '
133 'shows nothing Flame could not do',
134 );
135 }
136 }
139/// The game, owning its world: the page hands it a device and a scene, and
140/// it adds the crates, the tap layer and the hitbox lines itself.
141final class _Yard extends FlameGame with HasFlutter3d {
142 _Yard(this._eye);
144 final CameraNode _eye;
145 final List<_Crate> crates = <_Crate>[];
146 final Taps3dComponent taps = Taps3dComponent();
148 /// The page's own orbiting camera, so the projector sees what is drawn.
149 @override
150 CameraNode createCamera3d() => _eye;
152 @override
153 void onOpen3d() {
154 for (var i = 0; i < 3; i++) {
155 final angle = i * 2.0 * math.pi / 3.0;
156 crates.add(
157 _Crate(
158 device,
159 scene,
160 Vector2(2.4 * math.cos(angle), 2.4 * math.sin(angle)),
161 ),
162 );
163 }
164 addAll(<Component>[...crates, taps]);
165 debugHitboxes3d = true;
166 }
169/// A crate that hears a tap on what the camera shows of it, flashes, and
170/// says so over itself.
171final class _Crate extends Object3dComponent with Tap3dCallbacks {
172 _Crate(GraphicsDevice device, Scene scene, Vector2 at)
173 : super(
174 node: MeshNode(
175 DeviceMesh.upload(
176 device,
177 CuboidShape(size: Vector3.all(1.0)).build(),
178 ),
179 RenderMaterial(
180 name: 'crate',
181 baseColor: LinearColor.fromSrgb(0.8, 0.65, 0.4, 1.0),
182 ),
183 ),
184 scene: scene,
185 plane: BridgePlane.ground(),
186 direction: SyncDirection.flameToScene,
187 elevation: 0.5,
188 position: at,
189 size: Vector2.all(1.0),
190 anchor: Anchor.center,
191 children: <Component>[RectangleHitbox()],
192 );
194 @override
195 void onTap3d(Vector2 screen) {
196 // A red flash over the material the other crates share: the tint is
197 // this crate's alone.
198 tint = const LinearColor(1.0, 0.3, 0.25);
199 add(
200 TimerComponent(
201 period: 0.25,
202 removeOnFinish: true,
203 onTick: () => tint = LinearColor.white,
204 ),
205 );
206 // "+1" over the crate, placed through the projector, in Flame's layer.
207 final game = findGame()! as HasFlutter3d;
208 game.add(
209 TextComponent(
210 text: '+1',
211 position: game.projector.toScreen(scenePosition)!,
212 anchor: Anchor.center,
213 )..addAll(<Component>[
214 MoveByEffect(Vector2(0.0, -40.0), EffectController(duration: 0.8)),
215 RemoveEffect(delay: 0.8),
216 ]),
217 );
218 }