File size: 20,478 Bytes
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c36e12e
 
 
 
95a7e69
 
 
 
 
c36e12e
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40798b3
d9a54f4
 
 
 
95a7e69
 
 
 
 
c36e12e
95a7e69
 
d9a54f4
95a7e69
 
 
 
d9a54f4
 
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c36e12e
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
c36e12e
 
 
 
 
 
 
 
 
 
 
 
 
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a54f4
 
 
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c36e12e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// The scenery of a scene, as the renderer (view.js) draws it and the light baker (tools/bake_light.mjs)
// lights it: which geoms are scenery, their triangles in world coordinates, and where each surface lies
// in the light map. The page and the baker must build the same triangles and the same light map layout,
// so both build them here, with three.js, in the same order.
import * as THREE from "three";
import { RoundedBoxGeometry } from "three/addons/geometries/RoundedBoxGeometry.js";
import { toCreasedNormals } from "three/addons/utils/BufferGeometryUtils.js";
import { lookFor, surfaceColour } from "./materials.js";

export const GEOM = { PLANE: 0, SPHERE: 2, CAPSULE: 3, ELLIPSOID: 4, CYLINDER: 5, BOX: 6, MESH: 7 };
export const STATIC = new Set(["floor", "proxy", "env", "decor"]);
const CREASE_ANGLE = Math.PI / 6;
// Boxes are drawn with their edges rounded this much (metres), less on thin ones: a sharp edge catches
// no light, and real furniture has none.
const BEVEL = 0.006;

/** A geom's colour as MuJoCo shows it: its own rgba when set, otherwise its material's. */
export function geomRgba(model, i) {
  const g = model.geom_rgba.subarray(4 * i, 4 * i + 4);
  const m = model.geom_matid[i];
  const unset = g[0] === 0.5 && g[1] === 0.5 && g[2] === 0.5 && g[3] === 1;
  return Array.from(m >= 0 && unset ? model.mat_rgba.subarray(4 * m, 4 * m + 4) : g);
}

/**
 * What a geom is to the renderer: "floor" (a plane), "robot", "decor" (a modelled stand-in for a 3DGS
 * splat), "proxy" (MuJoCo-GS-Web's invisible collision boxes), "object" (a free body), "env" (fixed
 * furniture), "part" (a moving part of the furniture: doors, drawers), or null (not drawn).
 */
export function geomRole(sim, i, robotRoots) {
  const { model } = sim;
  if (model.geom_type[i] === GEOM.PLANE) return "floor";
  const body = model.geom_bodyid[i];
  const root = model.body_rootid[body];
  if (robotRoots.includes(root)) return model.geom_group[i] >= 3 ? null : "robot";
  const static_ = model.body_weldid[body] === 0;
  if (static_ && sim.bodyNames[body].startsWith("decor_")) return "decor";
  const alpha = geomRgba(model, i)[3];
  if (static_ && (model.geom_group[i] >= 3 || alpha < 0.1)) return "proxy"; // MuJoCo-GS-Web collision boxes
  if (!static_ && model.body_parentid[root] === 0 && model.body_jntadr[root] >= 0 && model.jnt_type[model.body_jntadr[root]] === 0) return "object";
  if (model.geom_group[i] >= 3) return null;
  return static_ ? "env" : "part";
}

/** A geom's pose now, as a matrix. */
export function geomMatrix(data, i) {
  const { geom_xpos: pos, geom_xmat: mat } = data;
  const r = 9 * i;
  const p = 3 * i;
  return new THREE.Matrix4().set(mat[r], mat[r + 1], mat[r + 2], pos[p], mat[r + 3], mat[r + 4], mat[r + 5], pos[p + 1], mat[r + 6], mat[r + 7], mat[r + 8], pos[p + 2], 0, 0, 0, 1);
}

/**
 * A geom's geometry in its own frame. `coarse` halves the segments: the decor has hundreds of small
 * pieces. A box's edges are rounded by `bevel` metres at most.
 */
export function geomGeometry(model, i, meshCache, coarse = false, bevel = BEVEL) {
  const s = [model.geom_size[3 * i], model.geom_size[3 * i + 1], model.geom_size[3 * i + 2]];
  const k = coarse ? 2 : 1;
  switch (model.geom_type[i]) {
    case GEOM.SPHERE:
      return new THREE.SphereGeometry(s[0], 32 / k, 16 / k);
    case GEOM.ELLIPSOID:
      return new THREE.SphereGeometry(1, 32 / k, 16 / k).scale(s[0], s[1], s[2]);
    case GEOM.CAPSULE:
      return new THREE.CapsuleGeometry(s[0], 2 * s[1], 8 / k, 24 / k).rotateX(Math.PI / 2);
    case GEOM.CYLINDER:
      return new THREE.CylinderGeometry(s[0], s[0], 2 * s[1], 32 / k).rotateX(Math.PI / 2);
    case GEOM.BOX: {
      const r = Math.min(bevel, 0.3 * Math.min(s[0], s[1], s[2]));
      return r >= 0.001 ? new RoundedBoxGeometry(2 * s[0], 2 * s[1], 2 * s[2], 1, r) : new THREE.BoxGeometry(2 * s[0], 2 * s[1], 2 * s[2]);
    }
    case GEOM.MESH: {
      const id = model.geom_dataid[i];
      if (!meshCache.has(id)) meshCache.set(id, meshGeometry(model, id));
      return meshCache.get(id);
    }
    default:
      return null;
  }
}

function meshGeometry(model, id) {
  const va = model.mesh_vertadr[id];
  const vn = model.mesh_vertnum[id];
  const fa = model.mesh_faceadr[id];
  const fn = model.mesh_facenum[id];
  const geometry = new THREE.BufferGeometry();
  geometry.setAttribute("position", new THREE.BufferAttribute(Float32Array.from(model.mesh_vert.subarray(3 * va, 3 * (va + vn))), 3));
  geometry.setIndex(new THREE.BufferAttribute(Uint32Array.from(model.mesh_face.subarray(3 * fa, 3 * (fa + fn))), 1));
  return toCreasedNormals(geometry, CREASE_ANGLE);
}

/**
 * A wall: a static box in a body named like a wall, upright, standing on the floor, at least 40 cm tall
 * and at most 40 cm thick (not a picture or a window hung on one).
 */
export function isWall(sim, i, role) {
  const { model, data } = sim;
  if ((role !== "env" && role !== "proxy") || model.geom_type[i] !== GEOM.BOX) return false;
  if (!/wall/i.test(sim.bodyNames[model.geom_bodyid[i]])) return false;
  const s = model.geom_size.subarray(3 * i, 3 * i + 3);
  return Math.abs(data.geom_xmat[9 * i + 8]) > 0.99 && 2 * s[2] >= 0.4 && Math.min(s[0], s[1]) <= 0.2 && data.geom_xpos[3 * i + 2] - s[2] < 0.05;
}

/** A static geom's geometry in world coordinates, with its colour per vertex, ready to merge. */
export function worldPart(sim, geometry, i, colour) {
  const g = geometry.index ? geometry.toNonIndexed() : geometry.clone();
  for (const name of Object.keys(g.attributes)) if (!["position", "normal", "uv"].includes(name)) g.deleteAttribute(name);
  const n = g.attributes.position.count;
  if (!g.attributes.uv) g.setAttribute("uv", new THREE.BufferAttribute(new Float32Array(2 * n), 2));
  g.applyMatrix4(geomMatrix(sim.data, i));
  const c = new Float32Array(3 * n);
  for (let k = 0; k < n; k++) c.set([colour.r, colour.g, colour.b], 3 * k);
  g.setAttribute("color", new THREE.BufferAttribute(c, 3));
  g.userData.geom = i;
  return g;
}

/**
 * The scenery of a scene, geom by geom in model order: static geoms grouped by role and look (to be merged
 * into one mesh each), walls (each with the low stub shown in its place when the camera is outside it),
 * and planes (with a floor cut to the room where there are walls). Moving geoms go to `onMoving(i, role,
 * matName, rgba, geometry)` in the same order.
 *
 * `dressing` (dressing.json, e.g. tools/make_appliances.py's) puts furniture models in place of the static
 * geoms wholly inside each item's region (those whose names match its `geoms` pattern, if it has one: an
 * appliance's shell, not what is inside it): those geoms form groups of their own (`dressed`: the item's
 * index), outside the light map, and each item gets the bounds of its geoms (`dressing`: [{ item, box }])
 * for its model to fit.
 */
export function collectScenery(sim, robotRoots, onMoving = null, dressing = null) {
  const { model, data } = sim;
  const meshCache = new Map();
  const groups = new Map();
  const parts = []; // static geoms, grouped once the walls are known
  const walls = [];
  const planes = [];
  const items = (dressing?.items ?? []).map((item) => ({ item, box: new THREE.Box3(), names: item.geoms ? new RegExp(item.geoms) : null }));
  const dressedBy = (part) => {
    part.computeBoundingBox();
    const b = part.boundingBox;
    const e = 0.001; // a millimetre's slack: a box standing on the floor reaches a hair below it
    const named = (names) => !names || names.test(model.geom(part.userData.geom).name ?? "");
    return items.findIndex(({ item: { region: r }, names }) => b.min.x >= r[0] - e && b.min.y >= r[1] - e && b.min.z >= r[2] - e && b.max.x <= r[3] + e && b.max.y <= r[4] + e && b.max.z <= r[5] + e && named(names));
  };
  for (let i = 0; i < model.ngeom; i++) {
    const role = geomRole(sim, i, robotRoots);
    if (!role) continue;
    const matId = model.geom_matid[i];
    const matName = matId >= 0 ? model.mat(matId).name : "";
    const rgba = geomRgba(model, i);
    if (model.geom_type[i] === GEOM.PLANE) {
      planes.push({ i, role, matName, rgba });
      continue;
    }
    // surfaces made of several boxes (a worktop round a sink, a wall) keep sharp edges: no seams between them
    const geometry = geomGeometry(model, i, meshCache, role === "decor", lookFor(matName)?.bevel ?? BEVEL);
    if (!geometry) continue;
    const own = model.geom_type[i] !== GEOM.MESH; // mesh geometries are shared through the cache
    if (STATIC.has(role) && isWall(sim, i, role)) {
      walls.push(wallParts(sim, i, role, matName, rgba, geometry));
      if (own) geometry.dispose();
      continue;
    }
    if (STATIC.has(role)) {
      let look = lookFor(matName);
      let colour = surfaceColour(look, rgba);
      let opacity = rgba[3];
      if (role === "proxy") {
        // MuJoCo-GS-Web's invisible collision boxes, shown where there is no decor: tables solid, walls faint.
        const wall = /wall/i.test(sim.bodyNames[model.geom_bodyid[i]]);
        look = null;
        colour = new THREE.Color(wall ? 0xd9dde3 : 0xc9a27e);
        opacity = wall ? 0.22 : 1;
      }
      const part = worldPart(sim, geometry, i, colour);
      const dressed = items.length ? dressedBy(part) : -1;
      if (dressed >= 0) items[dressed].box.union(part.boundingBox);
      parts.push({ role, look, matName, opacity, part, dressed });
      if (own) geometry.dispose();
    } else {
      onMoving?.(i, role, matName, rgba, geometry);
    }
  }
  // Which side of each wall is outside: away from the middle of the walls (from the robot, for one wall).
  if (walls.length) {
    const mid = new THREE.Vector3();
    if (walls.length > 1) {
      for (const w of walls) mid.add(w.center);
      mid.divideScalar(walls.length);
    } else if (robotRoots.length) mid.set(...sim.bodyPos(robotRoots[0]));
    for (const w of walls) if ((w.center.x - mid.x) * w.out.x + (w.center.y - mid.y) * w.out.y < 0) w.out.negate();
  }
  // Static geoms in groups by role and look, in model order; what hangs on a wall (a picture, a window, its
  // curtains) in groups of its own, cut down with the wall (view.js). A body hangs on the walls only if all
  // of it does: the back of a microwave standing against one does not.
  const near = parts.map((p) => (p.dressed < 0 ? attachedTo(walls, p.part) : -1));
  const bodyOf = (p) => model.geom_bodyid[p.part.userData.geom];
  const hung = new Map();
  parts.forEach((p, k) => hung.set(bodyOf(p), (hung.get(bodyOf(p)) ?? true) && near[k] >= 0));
  for (const [k, { role, look, matName, opacity, part, dressed }] of parts.entries()) {
    const attached = hung.get(bodyOf(parts[k])) ? near[k] : -1;
    const key = `${dressed >= 0 ? `dressed ${dressed}|` : ""}${attached >= 0 ? `wall ${attached}|` : ""}${role}|${look ? matName : ""}|${opacity.toFixed(2)}`;
    if (!groups.has(key)) groups.set(key, { role, look, matName, opacity, parts: [], dressed: dressed >= 0 ? dressed : null, attached: attached >= 0 ? attached : null });
    groups.get(key).parts.push(part);
  }
  // Where there are walls, the floor is drawn out to them, and no further, where a light map lights it.
  const room = roomOf(walls);
  for (const p of planes) {
    if (!room || p.role !== "floor") continue;
    const z = data.geom_xpos[3 * p.i + 2];
    const g = new THREE.PlaneGeometry(room.x1 - room.x0, room.y1 - room.y0).toNonIndexed().translate((room.x0 + room.x1) / 2, (room.y0 + room.y1) / 2, z);
    const c = new Float32Array(3 * g.attributes.position.count).fill(1);
    g.setAttribute("color", new THREE.BufferAttribute(c, 3));
    g.userData.geom = p.i;
    p.room = g;
  }
  return { groups: [...groups.values()], walls, planes, room, meshCache, dressing: items };
}

/**
 * Where a dressing model goes: the matrix that takes it from its glTF frame (y up, front +z) to its item's
 * place (or a part's, in its body's frame). `box` is the model's bounds once turned z up and by the item's
 * yaw (dressingTurn); `target` the bounds of the geoms it stands in for. "box" fits each axis to them,
 * "height" scales uniformly to their height, standing on their bottom at their centre.
 */
export function dressingTurn(item) {
  return new THREE.Matrix4().makeRotationZ(THREE.MathUtils.degToRad(item.yaw ?? 0)).multiply(new THREE.Matrix4().makeRotationX(Math.PI / 2));
}

export function dressingMatrix(item, box, target) {
  const size = box.getSize(new THREE.Vector3());
  const want = target.getSize(new THREE.Vector3());
  const scale = item.fit === "height" ? new THREE.Vector3().setScalar(want.z / size.z) : new THREE.Vector3(want.x / size.x, want.y / size.y, want.z / size.z);
  const from = box.getCenter(new THREE.Vector3()).multiply(scale);
  const to = target.getCenter(new THREE.Vector3());
  const shift = new THREE.Vector3(to.x - from.x, to.y - from.y, target.min.z - box.min.z * scale.z);
  return new THREE.Matrix4().makeTranslation(shift.x, shift.y, shift.z).multiply(new THREE.Matrix4().makeScale(scale.x, scale.y, scale.z)).multiply(dressingTurn(item));
}

/** A wall's geometry and its stub's, in world coordinates, and which way its thin side faces. */
function wallParts(sim, i, role, matName, rgba, geometry) {
  const { model, data } = sim;
  const proxy = role === "proxy";
  const look = proxy ? null : lookFor(matName);
  const colour = proxy ? new THREE.Color(0xd9dde3) : surfaceColour(look, rgba);
  const opacity = proxy ? 0.22 : rgba[3];
  const s = model.geom_size.subarray(3 * i, 3 * i + 3);
  const stubHalf = Math.min(0.06, s[2]);
  const stubShape = new THREE.BoxGeometry(2 * s[0], 2 * s[1], 2 * stubHalf).translate(0, 0, -s[2] + stubHalf);
  const full = worldPart(sim, geometry, i, colour);
  const stub = worldPart(sim, stubShape, i, colour);
  stub.userData.stub = true; // lit as if its wall were cut down (tools/bake_light.mjs)
  stubShape.dispose();
  // across it: its thin side
  const k = s[0] < s[1] ? 0 : 1;
  const R = data.geom_xmat.subarray(9 * i, 9 * i + 9);
  const p = data.geom_xpos.subarray(3 * i, 3 * i + 3);
  return { i, role, matName, look, colour, opacity, full, stub, center: new THREE.Vector3(p[0], p[1], p[2]), out: new THREE.Vector3(R[k], R[3 + k], 0).normalize() };
}

/**
 * The wall a static part hangs on, or -1: thin and within 12 cm of the wall's inside face, over its length,
 * above its stub. A wall the camera is outside of is cut down, and what hangs on it with it.
 */
function attachedTo(walls, part) {
  part.computeBoundingBox();
  const b = part.boundingBox;
  for (let k = 0; k < walls.length; k++) {
    const w = walls[k];
    w.full.computeBoundingBox();
    const box = w.full.boundingBox;
    const a = Math.abs(w.out.x) > Math.abs(w.out.y) ? "x" : "y"; // across the wall
    const t = a === "x" ? "y" : "x"; // along it
    const face = w.out[a] > 0 ? box.min[a] : box.max[a]; // its inside face
    const into = w.out[a] > 0 ? -1 : 1; // the room's side of it
    const near = into > 0 ? b.min[a] - face : face - b.max[a]; // how far the part keeps off the face
    const far = into > 0 ? b.max[a] - face : face - b.min[a]; // how far it reaches into the room
    if (near < -0.005 || far > 0.12 || b.max[a] - b.min[a] > 0.08) continue;
    if (b.min.z < 0.15 || b.max[t] < box.min[t] || b.min[t] > box.max[t]) continue;
    return k;
  }
  return -1;
}

/** The walls' extent on the floor, or null without walls. */
function roomOf(walls) {
  if (walls.length < 3) return null;
  const box = new THREE.Box3();
  for (const w of walls) {
    w.full.computeBoundingBox();
    box.union(w.full.boundingBox);
  }
  return { x0: box.min.x, x1: box.max.x, y0: box.min.y, y1: box.max.y };
}

// ---------------------------------------------------------------------------------------------------
// The light map's layout. Every surface of the scenery gets its own rectangle (a chart) in one atlas: a
// box face, a cylinder's side or cap, a sphere or capsule whole, unrolled by three.js's own texture
// coordinates, at DENSITY texels per metre. The charts are packed in rows, with PAD texels around each
// for filtering; their atlas coordinates go in the "uv1" attribute.

export const LIGHTMAP = { density: 40, pad: 2, minTexels: 2, maxTexels: 1024 };

/** The scenery's surfaces in a fixed order: what the light map covers (not what dressing stands in for). */
export function lightmapSurfaces(scenery) {
  const out = [];
  for (const g of scenery.groups) if (g.dressed === null || g.dressed === undefined) for (const p of g.parts) out.push(p);
  for (const w of scenery.walls) out.push(w.full, w.stub);
  for (const p of scenery.planes) if (p.room) out.push(p.room);
  return out;
}

/** The charts of one surface geometry: its groups (box faces, cylinder caps), or all of it. */
function chartsOf(geometry, { density, minTexels, maxTexels }) {
  const pos = geometry.attributes.position;
  const uv = geometry.attributes.uv;
  const ranges = geometry.groups.length ? geometry.groups : [{ start: 0, count: pos.count }];
  const charts = [];
  for (const { start, count } of ranges) {
    // metres per unit of u and of v: the largest over the chart's triangles
    let su = 0;
    let sv = 0;
    for (let t = start; t + 2 < start + count; t += 3) {
      const u0 = uv.getX(t), v0 = uv.getY(t);
      const du1 = uv.getX(t + 1) - u0, dv1 = uv.getY(t + 1) - v0;
      const du2 = uv.getX(t + 2) - u0, dv2 = uv.getY(t + 2) - v0;
      const det = du1 * dv2 - du2 * dv1;
      if (Math.abs(det) < 1e-12) continue;
      const e1 = [pos.getX(t + 1) - pos.getX(t), pos.getY(t + 1) - pos.getY(t), pos.getZ(t + 1) - pos.getZ(t)];
      const e2 = [pos.getX(t + 2) - pos.getX(t), pos.getY(t + 2) - pos.getY(t), pos.getZ(t + 2) - pos.getZ(t)];
      const dpdu = [0, 1, 2].map((k) => (e1[k] * dv2 - e2[k] * dv1) / det);
      const dpdv = [0, 1, 2].map((k) => (e2[k] * du1 - e1[k] * du2) / det);
      su = Math.max(su, Math.hypot(...dpdu));
      sv = Math.max(sv, Math.hypot(...dpdv));
    }
    const size = (m) => Math.min(maxTexels, Math.max(minTexels, Math.ceil(m * density)));
    charts.push({ geometry, start, count, w: size(su), h: size(sv), flat: su === 0 || sv === 0 });
  }
  return charts;
}

/** FNV-1a over numbers: the layout's fingerprint, to tell a light map baked for another layout. */
function fingerprint(numbers) {
  let h = 0x811c9dc5;
  for (const n of numbers) {
    let v = Math.round(n) >>> 0;
    for (let b = 0; b < 4; b++) {
      h ^= v & 0xff;
      h = Math.imul(h, 0x01000193) >>> 0;
      v >>>= 8;
    }
  }
  return h.toString(16).padStart(8, "0");
}

/**
 * Lay the scenery's surfaces out in a light map: writes "uv1" on each surface geometry and returns the
 * atlas size, the charts (with their place: x, y of the inner rectangle, w x h texels) and a fingerprint.
 */
export function layoutLightmap(scenery, options = {}) {
  const o = { ...LIGHTMAP, ...options };
  const surfaces = lightmapSurfaces(scenery);
  const charts = surfaces.flatMap((g) => chartsOf(g, o));
  const area = charts.reduce((a, c) => a + (c.w + 2 * o.pad) * (c.h + 2 * o.pad), 0);
  let width = 256;
  while (width < 4096 && width * width < area * 1.25) width *= 2;
  // Shelves of charts, tallest first (ties in their order: the same layout every time).
  const order = charts.map((c, k) => k).sort((a, b) => charts[b].h - charts[a].h || charts[b].w - charts[a].w || a - b);
  let x = 0;
  let y = 0;
  let row = 0;
  for (const k of order) {
    const c = charts[k];
    const W = c.w + 2 * o.pad;
    const H = c.h + 2 * o.pad;
    if (x + W > width) {
      x = 0;
      y += row;
      row = 0;
    }
    c.x = x + o.pad;
    c.y = y + o.pad;
    x += W;
    row = Math.max(row, H);
  }
  const height = Math.ceil((y + row) / 4) * 4;
  for (const g of surfaces) {
    if (!g.attributes.uv1) g.setAttribute("uv1", new THREE.BufferAttribute(new Float32Array(2 * g.attributes.position.count), 2));
  }
  for (const c of charts) {
    const uv = c.geometry.attributes.uv;
    const uv1 = c.geometry.attributes.uv1;
    for (let v = c.start; v < c.start + c.count; v++) {
      const u = c.flat ? 0.5 : Math.min(1, Math.max(0, uv.getX(v)));
      const t = c.flat ? 0.5 : Math.min(1, Math.max(0, uv.getY(v)));
      uv1.setXY(v, (c.x + u * c.w) / width, (c.y + t * c.h) / height);
    }
  }
  const hash = fingerprint([width, height, o.density, o.pad, charts.length, ...charts.flatMap((c) => [c.w, c.h, c.x, c.y, c.count])]);
  return { width, height, density: o.density, pad: o.pad, charts, surfaces, hash };
}