flutter3d
Showcase Changelog 62 packages API reference

Generate tangent frames: the source

since 0.7.0 Scene and geometry

Regions the guide quotes: undressed (line 25), compare (line 32), bump (line 37), check (line 77).

1/// One torus left with a flat, constant tangent and one with tangents
2/// generated from its UVs, both lit by the same tilted normal map.
3library;
4
5import 'package:flutter3d/flutter3d.dart';
6import 'package:flutter3d_showcase/src/demo/demo.dart';
7
8/// The `tangents` page: two tori under one tilted normal map, one with a
9/// constant tangent and one with tangents from its UVs. Its check is that
10/// the generated tangents follow the surface.
11final class TangentsDemo extends ShowcaseDemo {
12 late final MeshData _flatMesh;
13 late final MeshData _generatedMesh;
15 @override
16 void configureView(DemoContext context) {
17 context.orbit
18 ..distance = 6.5
19 ..pitch = 0.2
20 ..yaw = 0.4;
21 }
23 @override
24 Scene build(DemoContext context) {
25 final MeshData undressed = const TorusShape(
26 radius: 0.85,
27 tubeRadius: 0.34,
28 segments: 40,
29 tubeSegments: 20,
30 ).build(layout: VertexLayout.positionNormalTexcoord);
32 _flatMesh = undressed.convertedTo(VertexLayout.standard);
33 _generatedMesh = undressed.withGeneratedTangents(
34 target: VertexLayout.standard,
35 );
37 // A normal, not a colour: its texels are written as they are.
38 final TextureHandle tilt = const SolidColorTexture.texel(
39 0.78,
40 0.5,
41 0.86,
42 ).upload(context.device);
43 RenderMaterial bumpMaterial(String name) => RenderMaterial(
44 name: name,
45 baseColor: LinearColor.fromSrgb(0.6, 0.64, 0.7, 1.0),
46 metallic: 0.85,
47 roughness: 0.2,
48 normal: tilt,
49 );
51 final Scene scene = Scene()
52 ..ambientColor = LinearColor(0.4, 0.48, 0.64)
53 ..ambientIntensity = 0.14 * LightNode.legacyUnit
54 ..add(
55 MeshNode(
56 DeviceMesh.upload(context.device, _flatMesh),
57 bumpMaterial('flat tangent'),
58 name: 'flat',
59 )..setPosition(-1.3, 1.0, 0.0),
60 )
61 ..add(
62 MeshNode(
63 DeviceMesh.upload(context.device, _generatedMesh),
64 bumpMaterial('generated tangent'),
65 name: 'generated',
66 )..setPosition(1.3, 1.0, 0.0),
67 )
68 ..add(
69 LightNode(name: 'key', intensity: 3.4 * LightNode.legacyUnit)
70 ..setLocalForward(Vector3(-0.4, -0.7, -0.5)),
71 );
72 return scene;
73 }
75 @override
76 void verify(Scene scene, FrameResult frame) {
77 final int stride = VertexLayout.standard.floatsPerVertex;
78 final int tangentOffset = VertexLayout.standard.floatOffsetOf(
79 VertexLayout.tangent.name,
80 );
81 bool tangentVaries(MeshData mesh) {
82 double? firstX;
83 for (var v = 0; v < mesh.vertexCount; v++) {
84 final double x = mesh.vertices[v * stride + tangentOffset];
85 firstX ??= x;
86 if ((x - firstX).abs() > 1e-4) return true;
87 }
88 return false;
89 }
91 if (tangentVaries(_flatMesh) ||
92 !tangentVaries(_generatedMesh) ||
93 frame.drawCalls < 2) {
94 throw StateError('the generated tangents did not follow the surface');
95 }
96 }