Loading into a scene: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: document (line 15), upload (line 39), instantiate (line 47), check (line 63).
1/// Uploading a decoded document with `ModelAsset.fromDocument`, then
2/// placing it in a scene with `instantiate`.
3///
4/// Quoted by `model_asset.md` and shown whole in the Source tab.
5library;
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
9import 'package:vector_math/vector_math.dart';
11final class ModelAssetDemo extends ShowcaseDemo {
12 late final ModelAsset _asset;
13 ModelInstance? _instance;
15 // A decoded document, the shape every format in this package produces.
16 // `ModelAsset.fromDocument` does not care which one wrote it.
17 final _document = PlainModelDocument(
18 surfaces: <ModelSurface>[
19 ModelSurface(
20 mesh: SphereShape(segments: 32, rings: 16).build(),
21 materialIndex: 0,
22 ),
23 ],
24 materials: <SurfaceMaterial>[
25 SurfaceMaterial(
26 name: 'shell',
27 baseColor: Vector4(0.75, 0.4, 0.6, 1.0),
28 metallic: 0.2,
29 roughness: 0.4,
30 ),
31 ],
32 nodes: <ModelNode>[
33 ModelNode(surfaces: <int>[0]),
34 ],
35 );
38 Future<void> prepare(DemoContext context) async {
39 // Meshes and images are uploaded once, deduplicated by identity; a
40 // document's materials become the engine's own `Material`, ready to be
41 // placed as many times as a scene wants.
42 _asset = await ModelAsset.fromDocument(_document, device: context.device);
43 }
46 Scene build(DemoContext context) {
47 // `instantiate` rebuilds the asset's hierarchy as scene nodes and
48 // returns a `ModelInstance`: the node it hangs from, one scene node a
49 // decoded node, and a skeleton or an animation player when the asset
50 // carries one.
51 final scene = Scene();
52 _instance = _asset.instantiate(scene);
54 scene.add(
55 LightNode(name: 'sun', intensity: 3.0)
56 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
57 );
58 return scene;
59 }
62 void verify(Scene scene, FrameResult frame) {
63 if (_asset.vertexCount == 0) {
64 throw StateError('the asset uploaded no vertices');
65 }
66 if (_instance == null || _instance!.meshes.isEmpty) {
67 throw StateError('instantiate did not add a mesh to the scene');
68 }
69 if (frame.drawCalls < 1) {
70 throw StateError('the instance was not drawn');
71 }
72 }
73}