Build a mesh in code: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: builder (line 22), faces (line 33), scene (line 64), check (line 83).
1/// A pyramid, written vertex by vertex instead of generated from a shape.
2library;
4import 'package:flutter3d/flutter3d.dart';
5import 'package:flutter3d_showcase/src/demo/demo.dart';
7/// The `mesh-builder` page: a pyramid written vertex by vertex. Its check is
8/// that it reached the frame.
9final class MeshBuilderDemo extends ShowcaseDemo {
10 late final MeshData _pyramid;
13 void configureView(DemoContext context) {
14 context.orbit
15 ..distance = 5.5
16 ..pitch = 0.28
17 ..yaw = 0.5;
18 }
21 Scene build(DemoContext context) {
22 final MeshBuilder builder = MeshBuilder(VertexLayout.standard);
23 const double half = 0.9;
24 const double apexHeight = 1.3;
25 final Vector3 apex = Vector3(0.0, apexHeight, 0.0);
26 final List<Vector3> base = <Vector3>[
27 Vector3(-half, 0.0, -half),
28 Vector3(half, 0.0, -half),
29 Vector3(half, 0.0, half),
30 Vector3(-half, 0.0, half),
31 ];
33 final int apexIndex = builder.addVertex(
34 position: apex,
35 normal: Vector3(0.0, 1.0, 0.0),
36 texcoord: Vector2(0.5, 0.0),
37 color: const LinearColor(1.0, 0.92, 0.6),
38 );
39 final List<int> baseIndices = <int>[];
40 for (var i = 0; i < base.length; i++) {
41 final Vector3 edge = base[(i + 1) % base.length] - base[i];
42 final Vector3 toApex = apex - base[i];
43 final Vector3 normal = edge.cross(toApex)..normalize();
44 baseIndices.add(
45 builder.addVertex(
46 position: base[i],
47 normal: normal,
48 texcoord: Vector2(i / base.length, 1.0),
49 color: const LinearColor(0.65, 0.7, 0.8),
50 ),
51 );
52 }
53 for (var i = 0; i < base.length; i++) {
54 builder.addTriangle(baseIndices[i], baseIndices[(i + 1) % 4], apexIndex);
55 }
56 builder.addQuad(
57 baseIndices[3],
58 baseIndices[2],
59 baseIndices[1],
60 baseIndices[0],
61 );
62 _pyramid = builder.build();
64 final Scene scene = Scene()
65 ..ambientColor = LinearColor(0.42, 0.5, 0.66)
66 ..ambientIntensity = 0.16 * LightNode.legacyUnit
67 ..add(
68 MeshNode(
69 DeviceMesh.upload(context.device, _pyramid),
70 RenderMaterial(name: 'pyramid', roughness: 0.6),
71 name: 'pyramid',
72 ),
73 )
74 ..add(
75 LightNode(name: 'key', intensity: 3.2 * LightNode.legacyUnit)
76 ..setLocalForward(Vector3(-0.42, -0.78, -0.4)),
77 );
78 return scene;
79 }
82 void verify(Scene scene, FrameResult frame) {
83 if (_pyramid.vertexCount != 5 ||
84 _pyramid.indexCount != 18 ||
85 frame.drawCalls < 1) {
86 throw StateError('the hand-built pyramid did not reach the frame');
87 }
88 }
89}