Many copies in one draw: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: batch (line 32), instances (line 51), scene (line 71), motion (line 84), check (line 102).
1/// Sixty-four coloured copies stored in one `InstancedMeshNode`.
2library;
4import 'dart:math' as math;
6import 'package:flutter3d/flutter3d.dart';
7import 'package:flutter3d_showcase/src/demo/demo.dart';
9/// The `instancing` page: a field of coloured capsules in one
10/// `InstancedMeshNode`, turning. Its check is that all of them were drawn
11/// from it.
12final class InstancingDemo extends ShowcaseDemo {
13 /// How many capsules the field holds, and its capacity.
14 static const int instanceCount = 64;
16 /// How fast the field turns, in radians a second, 0 to 1.5.
17 double rotationSpeed = 0.25;
18 double _angle = 0.0;
20 late final InstancedMeshNode _field;
23 void configureView(DemoContext context) {
24 context.orbit
25 ..distance = 16.0
26 ..pitch = 0.52
27 ..yaw = 0.55;
28 }
31 Scene build(DemoContext context) {
32 _field = InstancedMeshNode(
33 DeviceMesh.upload(
34 context.device,
35 const CapsuleShape(
36 radius: 0.28,
37 height: 0.55,
38 segments: 20,
39 rings: 6,
40 ).build(),
41 ),
42 RenderMaterial(
43 name: 'instance material',
44 baseColor: LinearColor.fromSrgb(1.0, 1.0, 1.0, 1.0),
45 roughness: 0.48,
46 ),
47 capacity: instanceCount,
48 name: 'capsule field',
49 );
51 const int side = 8;
52 for (var i = 0; i < instanceCount; i++) {
53 final int x = i % side;
54 final int z = i ~/ side;
55 final double height = 0.7 + 0.3 * math.sin(x * 0.9 + z * 0.65);
56 final Matrix4 transform = Matrix4.identity()
57 ..setTranslationRaw((x - 3.5) * 1.35, height, (z - 3.5) * 1.35)
58 ..rotateY((x + z) * 0.24)
59 ..scaleByDouble(1.0, 0.85 + height * 0.2, 1.0, 1.0);
60 _field.addInstance(
61 transform,
62 color: LinearColor(
63 0.3 + x / 12.0,
64 0.32 + z / 13.0,
65 0.78 - (x + z) / 36.0,
66 1.0,
67 ),
68 );
69 }
71 final Scene scene = Scene()
72 ..ambientColor = LinearColor(0.45, 0.52, 0.68)
73 ..ambientIntensity = 0.13 * LightNode.legacyUnit
74 ..add(_field)
75 ..add(
76 LightNode(name: 'sun', intensity: 3.2 * LightNode.legacyUnit)
77 ..setLocalForward(Vector3(-0.5, -0.8, -0.32)),
78 );
79 return scene;
80 }
83 void update(DemoContext context, double dt) {
84 _angle = (_angle + dt * rotationSpeed) % (math.pi * 2.0);
85 _field.setRotationYawPitchRoll(_angle, 0.0, 0.0);
86 }
89 List<DemoControl> controls(DemoContext context) => <DemoControl>[
90 SliderControl(
91 'Field rotation',
92 min: 0.0,
93 max: 1.5,
94 value: () => rotationSpeed,
95 onChanged: (double value) => rotationSpeed = value,
96 format: (double value) => value.toStringAsFixed(2),
97 ),
98 ];
101 void verify(Scene scene, FrameResult frame) {
102 if (_field.count != instanceCount ||
103 _field.capacity < instanceCount ||
104 frame.instances < instanceCount ||
105 frame.drawCalls < 1) {
106 throw StateError('the instanced field was not drawn');
107 }
108 }
109}