Identical-draw batching: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: crates (line 29), settings (line 60), check (line 74).
1/// `RenderSettings.batchIdenticalDraws`: a run of nodes sharing a mesh and a
2/// material collapses into one instanced call.
3///
4/// Quoted by `draw_batching.md` and shown whole in the Source tab.
5library;
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
10/// The `draw-batching` page: a grid of crates sharing a mesh and a material.
11/// Its check is that the draws are merged with batching on and not merged
12/// with it off.
13final class DrawBatchingDemo extends ShowcaseDemo {
14 /// Whether identical draws are merged into instanced calls.
15 bool batch = true;
17 static const int _rows = 3;
18 static const int _columns = 4;
21 void configureView(DemoContext context) {
22 context.orbit
23 ..distance = 9.0
24 ..pitch = 0.35;
25 }
28 Scene build(DemoContext context) {
29 final DeviceMesh crateMesh = DeviceMesh.upload(
30 context.device,
31 CuboidShape(size: Vector3(0.8, 0.8, 0.8)).build(),
32 );
33 final RenderMaterial crateMaterial = RenderMaterial(
34 name: 'crate',
35 baseColor: LinearColor.fromSrgb(0.7, 0.55, 0.3, 1.0),
36 roughness: 0.7,
37 );
38 final Scene scene = Scene();
39 for (var row = 0; row < _rows; row++) {
40 for (var column = 0; column < _columns; column++) {
41 scene.add(
42 MeshNode(crateMesh, crateMaterial, name: 'crate $row-$column')
43 ..setPosition(
44 (column - (_columns - 1) / 2) * 1.1,
45 0.0,
46 (row - (_rows - 1) / 2) * 1.1,
47 ),
48 );
49 }
50 }
52 return scene..add(
53 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
54 ..setLocalForward(Vector3(-0.4, -0.8, -0.5)),
55 );
56 }
59 RenderSettings settings(DemoContext context) => RenderSettings(
60 batchIdenticalDraws: batch,
61 );
64 List<DemoControl> controls(DemoContext context) => <DemoControl>[
65 ToggleControl(
66 'Batch identical draws',
67 value: () => batch,
68 onChanged: (bool v) => batch = v,
69 ),
70 ];
73 void verify(Scene scene, FrameResult frame) {
74 final int crates = _rows * _columns;
75 if (scene.meshes.length != crates) {
76 throw StateError('expected $crates crates, found ${scene.meshes.length}');
77 }
78 if (batch && frame.batchedDraws < RenderSettings.batchRunMinimum) {
79 throw StateError(
80 'batching was on but only ${frame.batchedDraws} draws were merged',
81 );
82 }
83 if (!batch && frame.batchedDraws != 0) {
84 throw StateError(
85 'batching was off but ${frame.batchedDraws} draws merged',
86 );
87 }
88 }
89}