flutter3d
Showcase Changelog 62 packages API reference

CPU raycasting: the source

since 0.1.0 Views, picking and input

Regions the guide quotes: raycaster (line 16), cast (line 47).

1/// Finding which mesh a ray hits, entirely on the CPU: no frame, no readback,
2/// an answer the moment it is asked.
3///
4/// Quoted by `raycast.md` and shown whole in the Source tab.
5library;
6
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
9
10/// The `raycast` page: a ball hit by a ray cast on the CPU. Its check is
11/// that a ray through the centre of the screen hits the ball.
12final class RaycastDemo extends ShowcaseDemo {
13 late final CameraNode _camera;
14 late final Scene _scene;
16 final Raycaster _raycaster = Raycaster();
18 /// What the last ray through the centre of the screen hit, or null when it
19 /// missed.
20 HitResult? lastHit;
22 @override
23 Scene build(DemoContext context) {
24 _camera = context.camera;
25 final RenderMaterial stone = RenderMaterial(
26 name: 'stone',
27 baseColor: LinearColor.fromSrgb(0.7, 0.5, 0.4, 1.0),
28 roughness: 0.7,
29 );
30 final MeshNode ball = MeshNode(
31 DeviceMesh.upload(
32 context.device,
33 SphereShape(segments: 32, rings: 16).build(),
34 ),
35 stone,
36 name: 'ball',
37 );
38 _scene = Scene()
39 ..add(ball)
40 ..add(
41 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
42 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
43 );
44 return _scene;
45 }
47 void _castAtCentre() {
48 _raycaster.setFromNdc(_camera, 0.0, 0.0, aspect: 16 / 9);
49 lastHit = _raycaster.intersectScene(_scene);
50 }
52 @override
53 void update(DemoContext context, double dt) => _castAtCentre();
55 @override
56 void verify(Scene scene, FrameResult frame) {
57 if (frame.drawCalls < 1) {
58 throw StateError('the ball was not drawn');
59 }
60 // The ball sits on the camera's own axis, so a ray straight down the
61 // middle of the screen has to find it.
62 final HitResult? hit = lastHit;
63 if (hit == null || hit.node?.name != 'ball') {
64 throw StateError(
65 'a ray through the centre of the screen missed the ball',
66 );
67 }
68 }