Normal maps: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: texture (line 42), upload (line 67), material (line 76), tangents (line 85), live (line 102).
1/// A normal map: fine surface relief painted into a texture, with no extra
2/// triangles.
3///
4/// Quoted by `normal_mapping.md` and shown whole in the Source tab.
5library;
7import 'dart:math' as math;
8import 'dart:typed_data';
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_hardware/flutter3d_hardware.dart' show MipChain;
12import 'package:flutter3d_showcase/src/demo/demo.dart';
14/// The `normal-mapping` page: a ball wearing a cobblestone normal map. Its
15/// check is that the map is bound and the mesh carries tangents.
16final class NormalMappingDemo extends ShowcaseDemo {
17 /// How strongly the map bends the normals, 0 to 3.
18 double normalScale = 1.0;
20 /// Whether the normal map is bound at all.
21 bool useMap = true;
23 /// The sun's turn around the vertical, in radians, -1.4 to 1.4, to rake the
24 /// relief from either side.
25 double sunTurn = 0.6;
27 static const int _size = 128;
28 static const int _cobbles = 4;
30 late final RenderMaterial _ball;
31 late final LightNode _sun;
32 late final TextureHandle _normalMap;
35 void configureView(DemoContext context) {
36 context.orbit
37 ..distance = 3.2
38 ..yaw = 0.0
39 ..pitch = 0.1;
40 }
42 /// A grid of round cobbles. Each texel stores the direction the surface
43 /// faces there, x, y and z scaled from -1..1 into 0..255.
44 ByteData _cobbleNormals() {
45 final Uint8List bytes = Uint8List(_size * _size * 4);
46 const int cell = _size ~/ _cobbles;
47 for (var y = 0; y < _size; y++) {
48 for (var x = 0; x < _size; x++) {
49 final double u = ((x % cell) + 0.5) / cell * 2.0 - 1.0;
50 final double v = 1.0 - ((y % cell) + 0.5) / cell * 2.0;
51 final double r2 = u * u + v * v;
52 final Vector3 n = r2 < 0.85
53 ? Vector3(u * 0.9, v * 0.9, math.sqrt(1.0 - r2 * 0.81)).normalized()
54 : Vector3(0.0, 0.0, 1.0);
55 final int at = (y * _size + x) * 4;
56 bytes[at] = ((n.x * 0.5 + 0.5) * 255).round();
57 bytes[at + 1] = ((n.y * 0.5 + 0.5) * 255).round();
58 bytes[at + 2] = ((n.z * 0.5 + 0.5) * 255).round();
59 bytes[at + 3] = 255;
60 }
61 }
62 return bytes.buffer.asByteData();
63 }
66 Scene build(DemoContext context) {
67 final ByteData pixels = _cobbleNormals();
68 _normalMap = context.device.createTextureFromPixels(
69 width: _size,
70 height: _size,
71 format: TextureFormat.r8g8b8a8UNormInt,
72 pixels: pixels,
73 mipLevels: MipChain.build(pixels, _size, _size),
74 );
76 _ball = RenderMaterial(
77 name: 'cobbles',
78 baseColor: LinearColor.fromSrgb(0.62, 0.6, 0.56, 1.0),
79 roughness: 0.55,
80 normal: _normalMap,
81 normalSampler: SamplerDescriptor.trilinearRepeat,
82 normalScale: normalScale,
83 );
85 final MeshData data = SphereShape(segments: 64, rings: 32)
86 .build(layout: VertexLayout.positionNormalTexcoord)
87 .withGeneratedTangents(target: VertexLayout.standard);
88 final MeshNode ball = MeshNode(
89 DeviceMesh.upload(context.device, data),
90 _ball,
91 name: 'ball',
92 );
94 _sun = LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit);
95 return Scene()
96 ..add(ball)
97 ..add(_sun);
98 }
101 void update(DemoContext context, double dt) {
102 _ball
103 ..normal = useMap ? _normalMap : null
104 ..normalScale = normalScale;
105 _sun.setLocalForward(Vector3(-math.sin(sunTurn), -0.3, -math.cos(sunTurn)));
106 }
109 List<DemoControl> controls(DemoContext context) => <DemoControl>[
110 SliderControl(
111 'Normal scale',
112 min: 0,
113 max: 3,
114 value: () => normalScale,
115 onChanged: (double v) => normalScale = v,
116 ),
117 ToggleControl(
118 'Normal map',
119 value: () => useMap,
120 onChanged: (bool v) => useMap = v,
121 ),
122 SliderControl(
123 'Sun direction',
124 min: -1.4,
125 max: 1.4,
126 value: () => sunTurn,
127 onChanged: (double v) => sunTurn = v,
128 ),
129 ];
132 void verify(Scene scene, FrameResult frame) {
133 final RenderMaterial material = scene.meshes.first.material;
134 if (material.normal == null) {
135 throw StateError('the ball has no normal map bound');
136 }
137 final MeshData? source = (scene.meshes.first.mesh as DeviceMesh).source;
138 if (source == null || !source.layout.has(VertexLayout.tangent)) {
139 throw StateError('the mesh carries no tangents for the map to use');
140 }
141 if (frame.drawCalls < 1) throw StateError('the ball was not drawn');
142 }
143}