Draw order, alpha to coverage and index windows: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: panels (line 56), grille (line 77), order (line 133), windows (line 142), check (line 164).
1/// Three controls over a single draw: which of two meshes in the same place
2/// is drawn first, how a masked surface's edge is cut, and which part of an
3/// index buffer a draw reads.
4///
5/// Quoted by `draw_control.md` and shown whole in the Source tab.
6library;
8import 'dart:math' as math;
9import 'dart:typed_data';
11import 'package:flutter3d/flutter3d.dart';
12// The page shows the engine's own draw list, which is not its API.
13// ignore: implementation_imports
14import 'package:flutter3d_core/src/engine/render/render_list.dart';
15import 'package:flutter3d_hardware/flutter3d_hardware.dart'
16 show IndexWindow, indexWindow;
17import 'package:flutter3d_showcase/src/demo/demo.dart';
19/// The `draw-control` page: two panels in one place drawn in a set order, a
20/// masked grille, and faces drawn from parts of one index buffer. Its check
21/// is the draw order, a declined coverage that the frame reports, and an
22/// index window past the binding refused.
23final class DrawControlDemo extends ShowcaseDemo {
24 /// Whether the red panel is drawn first, and so keeps the shared pixels.
25 bool redFirst = true;
27 /// Whether the grille cuts its masked edge with alpha to coverage rather
28 /// than a hard test; a device without it declines and the frame says so.
29 bool coverage = true;
31 late final MeshNode _red;
32 late final MeshNode _blue;
33 late final RenderMaterial _grille;
34 late final DeviceMesh _panel;
35 late final CameraNode _camera;
36 late final GraphicsDevice _device;
39 void configureView(DemoContext context) {
40 context.orbit
41 ..distance = 5.5
42 ..pitch = 0.2
43 ..yaw = 0.0;
44 context.orbit.target.setValues(0.0, 1.0, 0.0);
45 }
48 Scene build(DemoContext context) {
49 _camera = context.camera;
50 _device = context.device;
51 _panel = DeviceMesh.upload(
52 context.device,
53 CuboidShape(size: Vector3(1.4, 1.4, 0.04)).build(),
54 );
56 // Two panels of one mesh at one place: every pixel of one is a pixel of
57 // the other, at exactly the same depth. The depth test keeps the first
58 // fragment and refuses an equal one after it, so whichever is drawn first
59 // is the one seen.
60 _red = MeshNode(
61 _panel,
62 RenderMaterial(
63 name: 'red',
64 baseColor: LinearColor.fromSrgb(0.85, 0.2, 0.15, 1.0),
65 ),
66 name: 'red panel',
67 )..setPosition(-0.9, 1.0, 0.0);
68 _blue = MeshNode(
69 _panel,
70 RenderMaterial(
71 name: 'blue',
72 baseColor: LinearColor.fromSrgb(0.15, 0.35, 0.9, 1.0),
73 ),
74 name: 'blue panel',
75 )..setPosition(-0.9, 1.0, 0.0);
77 // A grille: a small texture whose alpha is a grid of round holes, cut at
78 // a half and turned into multisample coverage where the device can.
79 const int size = 16;
80 final Uint8List texels = Uint8List(size * size * 4);
81 for (var y = 0; y < size; y++) {
82 for (var x = 0; x < size; x++) {
83 final double dx = (x % 4) - 1.5;
84 final double dy = (y % 4) - 1.5;
85 final int i = (y * size + x) * 4;
86 texels.setAll(i, <int>[230, 230, 220, 255]);
87 texels[i + 3] = math.sqrt(dx * dx + dy * dy) < 1.4 ? 0 : 255;
88 }
89 }
90 _grille = RenderMaterial(
91 name: 'grille',
92 albedo: context.device.createTextureFromPixels(
93 width: size,
94 height: size,
95 format: TextureFormat.r8g8b8a8UNormInt,
96 pixels: ByteData.sublistView(texels),
97 ),
98 alphaMode: MaterialAlphaMode.mask,
99 alphaCutoff: 0.5,
100 alphaToCoverage: coverage,
101 doubleSided: true,
102 );
104 return Scene()
105 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
106 ..ambientIntensity = 0.3 * LightNode.legacyUnit
107 ..add(
108 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
109 ..setLocalForward(Vector3(-0.3, -0.6, -0.8)),
110 )
111 ..add(
112 MeshNode(
113 DeviceMesh.upload(
114 context.device,
115 const PlaneShape(width: 8.0, depth: 6.0).build(),
116 ),
117 RenderMaterial(
118 name: 'floor',
119 baseColor: LinearColor.fromSrgb(0.55, 0.55, 0.5, 1.0),
120 ),
121 name: 'floor',
122 ),
123 )
124 ..add(_red)
125 ..add(_blue)
126 ..add(
127 MeshNode(_panel, _grille, name: 'grille')..setPosition(0.9, 1.0, 0.0),
128 );
129 }
132 void update(DemoContext context, double dt) {
133 // Lower draws first. The order is added to the material's `drawBucket`
134 // and outranks every other term of the sort, depth included.
135 _red.drawOrder = redFirst ? -1 : 0;
136 _blue.drawOrder = redFirst ? 0 : -1;
137 _grille.alphaToCoverage = coverage;
138 }
140 /// The six faces of the panel's cube as windows of its one index buffer,
141 /// six indices each.
142 List<IndexWindow> _faces() => <IndexWindow>[
143 for (var face = 0; face < 6; face++)
144 indexWindow(_panel.indexCount, firstIndex: face * 6, indexCount: 6),
145 ];
148 List<DemoControl> controls(DemoContext context) => <DemoControl>[
149 ChoiceControl(
150 'Drawn first, and so seen',
151 options: const <String>['Red', 'Blue'],
152 index: () => redFirst ? 0 : 1,
153 onChanged: (int i) => redFirst = i == 0,
154 ),
155 ToggleControl(
156 'Alpha to coverage on the grille',
157 value: () => coverage,
158 onChanged: (bool v) => coverage = v,
159 ),
160 ];
163 void verify(Scene scene, FrameResult frame) {
164 // The sorted list puts the panel with the lower order first.
165 final CameraView view = CameraView(camera: _camera);
166 final RenderList list = RenderList()
167 ..build(
168 scene,
169 view,
170 viewMatrix: _camera.viewMatrix,
171 frustum: Frustum.matrix(
172 _camera.viewProjection(frame.frame.width / frame.frame.height),
173 ),
174 )
175 ..sort(view);
176 final List<MeshNode> drawn = <MeshNode>[
177 for (final int i in list.opaque) list.itemAt(i).requireNode,
178 ];
179 final MeshNode first = redFirst ? _red : _blue;
180 final MeshNode second = redFirst ? _blue : _red;
181 if (!drawn.contains(first) ||
182 !drawn.contains(second) ||
183 drawn.indexOf(first) > drawn.indexOf(second)) {
184 throw StateError('${first.name} is not drawn before ${second.name}');
185 }
187 // A device without coverage draws the hard cutoff and says so.
188 if (coverage && !_device.features.has(DeviceFeature.alphaToCoverage)) {
189 if (!frame.alphaToCoverageDeclined) {
190 throw StateError('coverage was declined and the frame did not say so');
191 }
192 }
194 // Six windows tile the cube's 36 indices; one past the end is refused.
195 final List<IndexWindow> faces = _faces();
196 if (faces.last.first + faces.last.count != _panel.indexCount) {
197 throw StateError('the faces do not cover the index buffer');
198 }
199 try {
200 indexWindow(_panel.indexCount, firstIndex: 30, indexCount: 12);
201 throw StateError('a window past the binding was accepted');
202 } on RangeError {
203 // Refused before any driver sees it, which is the claim.
204 }
205 }
206}