Screen-space bounds: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: box (line 121), bounds (line 138).
1/// Where a box in the world lands on the glass, as a rectangle a focus ring
2/// or a label can use. Three things move about the scene and the rectangle
3/// `screenBoundsOfBox` returns for each is drawn over the picture.
4///
5/// Quoted by `screen_bounds.md` and shown whole in the Source tab.
6library;
8import 'dart:math' as math;
10import 'package:flutter/gestures.dart';
11import 'package:flutter/widgets.dart';
12import 'package:flutter3d/flutter3d.dart';
13import 'package:flutter3d/flutter3d.dart' as f3d show RenderMaterial;
14import 'package:flutter3d_app/flutter3d_app.dart';
15import 'package:flutter3d_showcase/src/demo/demo.dart';
17/// The `screen-bounds` page: a cube, a sphere and a pillar moving about, each
18/// ringed by the rectangle its box lands on. Its check is that each is in
19/// front of the camera, inside its own rectangle, which is not degenerate.
20final class ScreenBoundsDemo extends ShowcaseDemo {
21 /// Which thing is ringed: 0 the cube, 1 the sphere, 2 the pillar, 3 all
22 /// three.
23 int ringed = 3;
25 late final CameraNode _camera;
26 late final Scene _scene;
27 late final MeshNode _cube;
28 late final MeshNode _sphere;
29 late final MeshNode _pillar;
30 double _clock = 0.0;
32 static const List<String> _names = <String>['cube', 'sphere', 'pillar'];
33 static const List<Color> _colors = <Color>[
34 Color(0xFFFFB03B),
35 Color(0xFF5CD6FF),
36 Color(0xFFFF6B9A),
37 ];
40 void configureView(DemoContext context) {
41 context.orbit
42 ..distance = 9.0
43 ..pitch = 0.45
44 ..yaw = 0.4;
45 }
48 Scene build(DemoContext context) {
49 _camera = context.camera;
50 f3d.RenderMaterial color(String name, double r, double g, double b) =>
51 f3d.RenderMaterial(
52 name: name,
53 baseColor: LinearColor.fromSrgb(r, g, b, 1.0),
54 roughness: 0.6,
55 );
56 _cube = MeshNode(
57 DeviceMesh.upload(
58 context.device,
59 CuboidShape(size: Vector3.all(1.2)).build(),
60 ),
61 color('cube', 0.8, 0.55, 0.3),
62 name: 'cube',
63 );
64 _sphere = MeshNode(
65 DeviceMesh.upload(context.device, SphereShape(radius: 0.7).build()),
66 color('sphere', 0.35, 0.65, 0.8),
67 name: 'sphere',
68 );
69 _pillar = MeshNode(
70 DeviceMesh.upload(
71 context.device,
72 CuboidShape(size: Vector3(0.6, 2.4, 0.6)).build(),
73 ),
74 color('pillar', 0.8, 0.4, 0.55),
75 name: 'pillar',
76 )..setPosition(0.0, 1.2, -1.6);
78 _scene = Scene()
79 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
80 ..ambientIntensity = 0.25 * LightNode.legacyUnit
81 ..add(
82 MeshNode(
83 DeviceMesh.upload(
84 context.device,
85 const PlaneShape(width: 12.0, depth: 12.0).build(),
86 ),
87 color('floor', 0.36, 0.4, 0.38),
88 name: 'floor',
89 ),
90 )
91 ..add(_cube)
92 ..add(_sphere)
93 ..add(_pillar)
94 ..add(
95 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
96 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
97 );
98 _place();
99 return _scene;
100 }
102 void _place() {
103 _cube.setPosition(
104 2.4 * math.cos(_clock * 0.6),
105 0.6,
106 2.4 * math.sin(_clock * 0.6),
107 );
108 _sphere.setPosition(
109 1.4 * math.cos(-_clock * 0.9 + 2.0),
110 0.7 + 0.5 * math.sin(_clock * 1.7).abs(),
111 1.4 * math.sin(-_clock * 0.9 + 2.0),
112 );
113 }
116 void update(DemoContext context, double dt) {
117 _clock += dt;
118 _place();
119 }
121 /// What each thing occupies in the world, as the box `screenBoundsOfBox`
122 /// takes — the box a culling or picking system would already keep.
123 Aabb3 _boxOf(int which) => switch (which) {
124 0 => Aabb3.centerAndHalfExtents(
125 _cube.readPosition(),
126 Vector3(0.6, 0.6, 0.6),
127 ),
128 1 => Aabb3.centerAndHalfExtents(
129 _sphere.readPosition(),
130 Vector3(0.7, 0.7, 0.7),
131 ),
132 _ => Aabb3.centerAndHalfExtents(
133 _pillar.readPosition(),
134 Vector3(0.3, 1.2, 0.3),
135 ),
136 };
138 ScreenBounds? _measure(int which, double width, double height) =>
139 screenBoundsOfBox(
140 _camera.viewProjection(width / height),
141 _boxOf(which),
142 width: width,
143 height: height,
144 );
147 Widget? customBody(BuildContext buildContext, DemoContext context) =>
148 Listener(
149 onPointerMove: (PointerMoveEvent event) =>
150 context.orbit.rotate(event.delta.dx, event.delta.dy),
151 onPointerSignal: (PointerSignalEvent event) {
152 if (event is PointerScrollEvent) {
153 context.orbit.zoom(event.scrollDelta.dy > 0.0 ? 1.1 : 1.0 / 1.1);
154 }
155 },
156 child: Stack(
157 fit: StackFit.expand,
158 children: <Widget>[
159 SceneSurface(
160 renderer: context.renderer,
161 scene: _scene,
162 view: context.view,
163 settings: () => const RenderSettings(),
164 onBeforeDraw: () =>
165 context.orbit.syncProjectionDepth(context.camera),
166 presentFrame: presentFrame,
167 ),
168 IgnorePointer(child: CustomPaint(painter: _RingPainter(this))),
169 ],
170 ),
171 );
174 List<DemoControl> controls(DemoContext context) => <DemoControl>[
175 ChoiceControl(
176 'Ring around',
177 options: const <String>['cube', 'sphere', 'pillar', 'all three'],
178 index: () => ringed,
179 onChanged: (int i) => ringed = i,
180 ),
181 ];
184 void verify(Scene scene, FrameResult frame) {
185 if (frame.drawCalls < 1) {
186 throw StateError('the scene was not drawn');
187 }
188 const double width = 320.0;
189 const double height = 180.0;
190 final viewProjection = _camera.viewProjection(width / height);
191 for (var which = 0; which < 3; which++) {
192 final ScreenBounds? bounds = _measure(which, width, height);
193 if (bounds == null) {
194 throw StateError('${_names[which]} is behind the camera');
195 }
196 // A real rectangle, and one that holds the point its own centre
197 // projects to.
198 if (bounds.left >= bounds.right || bounds.top >= bounds.bottom) {
199 throw StateError('${_names[which]} got a degenerate rectangle');
200 }
201 final Vector3 center = _boxOf(which).center;
202 final Vector4 clip = viewProjection.transformed(
203 Vector4(center.x, center.y, center.z, 1.0),
204 );
205 final double x = (clip.x / clip.w * 0.5 + 0.5) * width;
206 final double y = (0.5 - clip.y / clip.w * 0.5) * height;
207 if (x < bounds.left ||
208 x > bounds.right ||
209 y < bounds.top ||
210 y > bounds.bottom) {
211 throw StateError(
212 '${_names[which]} is not inside the rectangle its own box gave',
213 );
214 }
215 }
216 }
217}
219/// Draws the rectangles, at whatever size the frame is being shown.
220final class _RingPainter extends CustomPainter {
221 _RingPainter(this._demo);
223 final ScreenBoundsDemo _demo;
226 void paint(Canvas canvas, Size size) {
227 final List<int> which = _demo.ringed == 3
228 ? const <int>[0, 1, 2]
229 : <int>[_demo.ringed];
230 for (final int i in which) {
231 final ScreenBounds? bounds = _demo._measure(i, size.width, size.height);
232 if (bounds == null) continue;
233 final Rect rect = Rect.fromLTRB(
234 bounds.left,
235 bounds.top,
236 bounds.right,
237 bounds.bottom,
238 );
239 canvas.drawRRect(
240 RRect.fromRectAndRadius(rect.inflate(3.0), const Radius.circular(4.0)),
241 Paint()
242 ..style = PaintingStyle.stroke
243 ..strokeWidth = 2.0
244 ..color = ScreenBoundsDemo._colors[i],
245 );
246 final TextPainter label = TextPainter(
247 text: TextSpan(
248 text:
249 '${ScreenBoundsDemo._names[i]} '
250 '${bounds.left.round()},${bounds.top.round()} '
251 '${rect.width.round()}x${rect.height.round()}',
252 style: TextStyle(
253 color: ScreenBoundsDemo._colors[i],
254 fontSize: 11.0,
255 fontFamily: 'RobotoMono',
256 ),
257 ),
258 textDirection: TextDirection.ltr,
259 )..layout();
260 label.paint(canvas, Offset(rect.left, math.max(rect.top - 20.0, 2.0)));
261 }
262 }
265 bool shouldRepaint(_RingPainter oldDelegate) => true;
266}