@luma.gl/engine 10.0.0-alpha.13 → 10.0.0-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,348 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
3
+
4
+ import {assert} from '@luma.gl/core';
5
+ import {Matrix4, Vector3} from '@math.gl/core';
6
+ import {Geometry, type GeometryAttribute} from '../geometry/geometry';
7
+
8
+ export type LightmapAtlasInput = {
9
+ /** Stable application-owned identity; unique within an atlas. */
10
+ id: string;
11
+ geometry: Geometry;
12
+ /** Used only to measure world-space texel density. Output positions stay in object space. */
13
+ modelMatrix?: Matrix4;
14
+ };
15
+ export type LightmapAtlasOptions = {
16
+ width: number;
17
+ height: number;
18
+ texelsPerUnit: number;
19
+ padding?: number;
20
+ uvSet?: 0 | 1;
21
+ /** Join consecutive coplanar triangles that form a quad. */
22
+ mergeCoplanarPairs?: boolean;
23
+ };
24
+ export type LightmapAtlasChart = {
25
+ id: number;
26
+ meshId: string;
27
+ firstVertex: number;
28
+ vertexCount: number;
29
+ /** Integer pixel rectangle including padding, measured from the atlas top left. */
30
+ rectangle: {x: number; y: number; width: number; height: number};
31
+ worldArea: number;
32
+ };
33
+ export type LightmapAtlas = Required<Omit<LightmapAtlasOptions, 'mergeCoplanarPairs'>> & {
34
+ meshes: {id: string; geometry: Geometry}[];
35
+ charts: LightmapAtlasChart[];
36
+ /** Independent row-major r32float data, suitable for LightmapBaker chartTexture. Zero is unused. */
37
+ chartOwners: Float32Array;
38
+ /** Fraction of atlas pixels reserved by chart rectangles, including gutters. */
39
+ occupancy: number;
40
+ };
41
+ type PendingChart = LightmapAtlasChart & {coordinates: number[]; meshIndex: number};
42
+
43
+ /**
44
+ * Prepare an independent CPU atlas. Each triangle receives a planar chart; no seam heuristics,
45
+ * GPU allocation, texture upload, submission, or source mutation occurs here.
46
+ */
47
+ export function createLightmapAtlas(
48
+ inputs: readonly LightmapAtlasInput[],
49
+ options: LightmapAtlasOptions
50
+ ): LightmapAtlas {
51
+ const {width, height, texelsPerUnit, padding = 2, uvSet = 1} = options;
52
+ // Dimensions, density and gutters must be explicit and finite. Chart IDs stay exact in float16.
53
+ assert(Number.isSafeInteger(width) && width > 0 && Number.isSafeInteger(height) && height > 0);
54
+ assert(Number.isFinite(texelsPerUnit) && texelsPerUnit > 0);
55
+ assert(Number.isInteger(padding) && padding >= 0 && padding <= 16);
56
+ assert(uvSet === 0 || uvSet === 1);
57
+ assert(new Set(inputs.map(input => input.id)).size === inputs.length);
58
+ const charts: PendingChart[] = [];
59
+ const meshes = inputs.map((input, meshIndex) => {
60
+ const source = input.geometry;
61
+ const positions = source.attributes['POSITION'];
62
+ // Only tightly packed, per-vertex triangle-list attributes are supported.
63
+ assert(source.topology === 'triangle-list' && positions?.size === 3 && !positions.normalized);
64
+ const indices = source.indices?.value;
65
+ const vertexCount = source.vertexCount;
66
+ assert(!indices || vertexCount <= indices.length);
67
+ assert(vertexCount > 0 && vertexCount % 3 === 0);
68
+ const attributes: Record<string, GeometryAttribute> = {};
69
+ for (const [name, attribute] of Object.entries(source.attributes)) {
70
+ const {size, value} = attribute;
71
+ assert(
72
+ size &&
73
+ !attribute.constant &&
74
+ value.length === (positions.value.length / 3) * size &&
75
+ !attribute['byteStride'] &&
76
+ !attribute['byteOffset'] &&
77
+ !attribute['divisor']
78
+ );
79
+ const copied = value.slice(0, 0);
80
+ // Keep the original numeric storage type, including normalized integer attributes.
81
+ const expanded = new (copied.constructor as typeof Float32Array)(vertexCount * size);
82
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
83
+ const sourceVertex = indices ? indices[vertex] : vertex;
84
+ assert(
85
+ Number.isInteger(sourceVertex) && sourceVertex >= 0 && sourceVertex < value.length / size
86
+ );
87
+ for (let component = 0; component < size; component++)
88
+ expanded[vertex * size + component] = value[sourceVertex * size + component];
89
+ }
90
+ attributes[name] = {...attribute, value: expanded};
91
+ }
92
+ const coordinates = new Float32Array(vertexCount * 2);
93
+ attributes[`TEXCOORD_${uvSet}`] = {size: 2, value: coordinates};
94
+ const matrix = input.modelMatrix ?? new Matrix4();
95
+ // Affine transforms only; a projective matrix has no uniform world-space density.
96
+ assert(
97
+ matrix.every(Number.isFinite) &&
98
+ matrix[3] === 0 &&
99
+ matrix[7] === 0 &&
100
+ matrix[11] === 0 &&
101
+ matrix[15] === 1
102
+ );
103
+ const getPoints = (firstVertex: number) =>
104
+ [0, 1, 2].map(offset => {
105
+ const vertex = indices ? indices[firstVertex + offset] : firstVertex + offset;
106
+ const point = new Vector3(positions.value.slice(vertex * 3, vertex * 3 + 3));
107
+ assert(point.every(Number.isFinite));
108
+ return point.transformAsPoint(matrix);
109
+ });
110
+ for (let firstVertex = 0; firstVertex < vertexCount; ) {
111
+ const points = getPoints(firstVertex);
112
+ const edges = points.map((point, index) =>
113
+ new Vector3(points[(index + 1) % 3]).subtract(point)
114
+ );
115
+ const lengths = edges.map(edge => edge.len());
116
+ const start = lengths.indexOf(Math.max(...lengths));
117
+ const end = (start + 1) % 3;
118
+ const third = (start + 2) % 3;
119
+ const horizontal = edges[start].clone().normalize();
120
+ const relative = new Vector3(points[third]).subtract(points[start]);
121
+ const projected = relative.dot(horizontal);
122
+ const altitude = new Vector3(edges[start]).cross(relative).len() / lengths[start];
123
+ // Degenerate transformed triangles cannot receive lightmap samples.
124
+ assert(Number.isFinite(altitude) && altitude > 0 && lengths[start] > 0);
125
+ const local = new Array<number>(6).fill(0);
126
+ local[end * 2] = lengths[start] * texelsPerUnit;
127
+ local[third * 2] = projected * texelsPerUnit;
128
+ local[third * 2 + 1] = altitude * texelsPerUnit;
129
+ let worldArea = (lengths[start] * altitude) / 2;
130
+ if (options.mergeCoplanarPairs && firstVertex + 6 <= vertexCount) {
131
+ const second = getPoints(firstVertex + 3);
132
+ const shared = second.map(point =>
133
+ points.findIndex(candidate =>
134
+ candidate.every((component, index) => component === point[index])
135
+ )
136
+ );
137
+ if (shared.filter(index => index >= 0).length === 2 && new Set(shared).size === 3) {
138
+ const normal = edges[start].clone().cross(relative).normalize();
139
+ const vertical = normal.clone().cross(horizontal);
140
+ const opposite = shared.indexOf(-1);
141
+ const delta = second[opposite].clone().subtract(points[start]);
142
+ const projectedPoint = [delta.dot(horizontal), delta.dot(vertical)];
143
+ const [sharedFirst, sharedSecond] = shared.filter(index => index >= 0);
144
+ const unshared = [0, 1, 2].find(index => !shared.includes(index))!;
145
+ const side = (x: number, y: number) =>
146
+ (local[sharedSecond * 2] - local[sharedFirst * 2]) * (y - local[sharedFirst * 2 + 1]) -
147
+ (local[sharedSecond * 2 + 1] - local[sharedFirst * 2 + 1]) *
148
+ (x - local[sharedFirst * 2]);
149
+ const secondArea = second[1]
150
+ .clone()
151
+ .subtract(second[0])
152
+ .cross(second[2].clone().subtract(second[0]));
153
+ if (
154
+ Math.abs(delta.dot(normal)) <= 1e-7 * delta.len() &&
155
+ secondArea.dot(normal) > 0 &&
156
+ side(local[unshared * 2], local[unshared * 2 + 1]) *
157
+ side(projectedPoint[0] * texelsPerUnit, projectedPoint[1] * texelsPerUnit) <
158
+ 0
159
+ ) {
160
+ for (const index of shared) {
161
+ if (index >= 0) local.push(local[index * 2], local[index * 2 + 1]);
162
+ else local.push(projectedPoint[0] * texelsPerUnit, projectedPoint[1] * texelsPerUnit);
163
+ }
164
+ worldArea += secondArea.len() / 2;
165
+ }
166
+ }
167
+ }
168
+ const horizontalCoordinates = local.filter((_, index) => index % 2 === 0);
169
+ const verticalCoordinates = local.filter((_, index) => index % 2 === 1);
170
+ const chartVertexCount = local.length / 2;
171
+ const minimumX = chartVertexCount === 3 ? 0 : Math.min(...horizontalCoordinates);
172
+ const minimumY = chartVertexCount === 3 ? 0 : Math.min(...verticalCoordinates);
173
+ charts.push({
174
+ id: charts.length + 1,
175
+ meshId: input.id,
176
+ meshIndex,
177
+ firstVertex,
178
+ vertexCount: chartVertexCount,
179
+ rectangle: {
180
+ x: 0,
181
+ y: 0,
182
+ width:
183
+ Math.ceil(
184
+ chartVertexCount === 3
185
+ ? lengths[start] * texelsPerUnit
186
+ : Math.max(...horizontalCoordinates) - minimumX
187
+ ) +
188
+ 1 +
189
+ padding * 2,
190
+ height: Math.ceil(Math.max(...verticalCoordinates) - minimumY) + 1 + padding * 2
191
+ },
192
+ worldArea,
193
+ coordinates: local.map((value, index) => value - (index % 2 ? minimumY : minimumX))
194
+ });
195
+ firstVertex += chartVertexCount;
196
+ }
197
+ return {
198
+ id: input.id,
199
+ geometry: new Geometry({
200
+ id: `${source.id}-lightmap`,
201
+ topology: 'triangle-list',
202
+ vertexCount,
203
+ attributes
204
+ })
205
+ };
206
+ });
207
+ // Positive integer chart IDs must survive the default rgba16float bake target exactly.
208
+ assert(charts.length <= 2048);
209
+ let cursorX = 0;
210
+ let cursorY = 0;
211
+ let shelfHeight = 0;
212
+ let allocatedPixels = 0;
213
+ for (const chart of [...charts].sort(
214
+ (left, right) =>
215
+ right.rectangle.height - left.rectangle.height ||
216
+ right.rectangle.width - left.rectangle.width ||
217
+ left.id - right.id
218
+ )) {
219
+ const rectangle = chart.rectangle;
220
+ if (cursorX + rectangle.width > width) {
221
+ cursorX = 0;
222
+ cursorY += shelfHeight;
223
+ shelfHeight = 0;
224
+ }
225
+ // Packing never silently changes density. Increase dimensions or lower texelsPerUnit.
226
+ assert(rectangle.width <= width && cursorY + rectangle.height <= height);
227
+ rectangle.x = cursorX;
228
+ rectangle.y = cursorY;
229
+ cursorX += rectangle.width;
230
+ shelfHeight = Math.max(shelfHeight, rectangle.height);
231
+ allocatedPixels += rectangle.width * rectangle.height;
232
+ const coordinates = meshes[chart.meshIndex].geometry.attributes[`TEXCOORD_${uvSet}`].value;
233
+ for (let vertex = 0; vertex < chart.vertexCount; vertex++) {
234
+ coordinates[(chart.firstVertex + vertex) * 2] =
235
+ (rectangle.x + padding + 0.5 + chart.coordinates[vertex * 2]) / width;
236
+ coordinates[(chart.firstVertex + vertex) * 2 + 1] =
237
+ (rectangle.y + padding + 0.5 + chart.coordinates[vertex * 2 + 1]) / height;
238
+ }
239
+ }
240
+ const chartOwners = new Float32Array(width * height);
241
+ for (const {id, rectangle} of charts)
242
+ for (let row = rectangle.y; row < rectangle.y + rectangle.height; row++)
243
+ chartOwners.fill(id, row * width + rectangle.x, row * width + rectangle.x + rectangle.width);
244
+ return {
245
+ width,
246
+ height,
247
+ texelsPerUnit,
248
+ padding,
249
+ uvSet,
250
+ meshes,
251
+ charts: charts.map(({coordinates, meshIndex, ...chart}) => chart),
252
+ chartOwners,
253
+ occupancy: allocatedPixels / (width * height)
254
+ };
255
+ }
256
+
257
+ /** Explicit diagnostic pass; returns actionable chart errors without allocating GPU resources. */
258
+ export function validateLightmapAtlas(atlas: LightmapAtlas): string[] {
259
+ const errors: string[] = [];
260
+ if (
261
+ !Number.isSafeInteger(atlas.width) ||
262
+ atlas.width <= 0 ||
263
+ !Number.isSafeInteger(atlas.height) ||
264
+ atlas.height <= 0 ||
265
+ atlas.chartOwners.length !== atlas.width * atlas.height
266
+ )
267
+ return ['Invalid atlas dimensions or ownership data length'];
268
+ const occupied = new Uint8Array(atlas.width * atlas.height);
269
+ const identifiers = new Set<number>();
270
+ for (const chart of atlas.charts) {
271
+ const {x, y, width, height} = chart.rectangle;
272
+ if (
273
+ !Number.isInteger(chart.id) ||
274
+ chart.id <= 0 ||
275
+ chart.id > 2048 ||
276
+ identifiers.has(chart.id)
277
+ )
278
+ errors.push(`Invalid chart ID ${chart.id}`);
279
+ identifiers.add(chart.id);
280
+ if (
281
+ ![x, y, width, height].every(Number.isInteger) ||
282
+ x < 0 ||
283
+ y < 0 ||
284
+ width <= 0 ||
285
+ height <= 0 ||
286
+ x + width > atlas.width ||
287
+ y + height > atlas.height
288
+ ) {
289
+ errors.push(`Chart ${chart.id} is outside the atlas`);
290
+ continue;
291
+ }
292
+ let overlaps = false;
293
+ let ownershipMismatch = false;
294
+ for (let row = y; row < y + height; row++)
295
+ for (let column = x; column < x + width; column++) {
296
+ const pixel = row * atlas.width + column;
297
+ overlaps ||= Boolean(occupied[pixel]);
298
+ occupied[pixel] = 1;
299
+ ownershipMismatch ||= atlas.chartOwners[pixel] !== chart.id;
300
+ }
301
+ if (overlaps) errors.push(`Chart ${chart.id} overlaps another chart`);
302
+ if (ownershipMismatch) errors.push(`Chart ${chart.id} has inconsistent gutter ownership`);
303
+ const mesh = atlas.meshes.find(candidate => candidate.id === chart.meshId);
304
+ const coordinates = mesh?.geometry.attributes[`TEXCOORD_${atlas.uvSet}`]?.value;
305
+ if (
306
+ !coordinates ||
307
+ !Number.isInteger(chart.firstVertex) ||
308
+ !Number.isInteger(chart.vertexCount) ||
309
+ chart.vertexCount <= 0 ||
310
+ chart.firstVertex < 0 ||
311
+ chart.firstVertex + chart.vertexCount > coordinates.length / 2
312
+ ) {
313
+ errors.push(`Chart ${chart.id} has an invalid draw range`);
314
+ continue;
315
+ }
316
+ for (let vertex = chart.firstVertex; vertex < chart.firstVertex + chart.vertexCount; vertex++) {
317
+ const horizontal = coordinates[vertex * 2] * atlas.width;
318
+ const vertical = coordinates[vertex * 2 + 1] * atlas.height;
319
+ if (
320
+ !Number.isFinite(horizontal) ||
321
+ !Number.isFinite(vertical) ||
322
+ horizontal < x + atlas.padding ||
323
+ horizontal > x + width - atlas.padding ||
324
+ vertical < y + atlas.padding ||
325
+ vertical > y + height - atlas.padding
326
+ ) {
327
+ errors.push(`Chart ${chart.id} has UVs outside its padded rectangle`);
328
+ break;
329
+ }
330
+ }
331
+ }
332
+ if (atlas.chartOwners.some((owner, pixel) => !occupied[pixel] && owner !== 0))
333
+ errors.push('Unallocated pixels have chart owners');
334
+ return errors;
335
+ }
336
+
337
+ /** Independent RGBA8 chart-ownership preview. Unallocated pixels are opaque black. */
338
+ export function getLightmapAtlasDebugData(atlas: LightmapAtlas): Uint8ClampedArray {
339
+ const pixels = new Uint8ClampedArray(atlas.width * atlas.height * 4);
340
+ for (let pixel = 0; pixel < atlas.chartOwners.length; pixel++) {
341
+ const identifier = atlas.chartOwners[pixel];
342
+ pixels[pixel * 4] = identifier ? 64 + ((identifier * 67) % 192) : 0;
343
+ pixels[pixel * 4 + 1] = identifier ? 64 + ((identifier * 103) % 192) : 0;
344
+ pixels[pixel * 4 + 2] = identifier ? 64 + ((identifier * 137) % 192) : 0;
345
+ pixels[pixel * 4 + 3] = 255;
346
+ }
347
+ return pixels;
348
+ }