File size: 28,215 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
// Render kit: physically based look for three.js browser games.
//
// One call wires image-based lighting, ACES/AgX tone mapping, ambient occlusion, bloom,
// anti-aliasing and an optional colour-grade LUT, and gives the game a library of CC0 PBR
// textures with world-scale UVs. It uses no DOM API, so it runs on the main thread and in a
// worker rendering to an OffscreenCanvas alike. See README.md next to this file.
//
// Every import goes through ./three.js, which the installer points at the game's own copy of
// three.js so the kit and the game share one module instance.

import * as THREE from './three.js';
import { EffectComposer } from './jsm/postprocessing/EffectComposer.js';
import { RenderPass } from './jsm/postprocessing/RenderPass.js';
import { GTAOPass } from './jsm/postprocessing/GTAOPass.js';
import { UnrealBloomPass } from './jsm/postprocessing/UnrealBloomPass.js';
import { OutputPass } from './jsm/postprocessing/OutputPass.js';
import { SMAAPass } from './jsm/postprocessing/SMAAPass.js';
import { LUTPass } from './jsm/postprocessing/LUTPass.js';
import { HDRLoader } from './jsm/loaders/HDRLoader.js';
import { LUTCubeLoader } from './jsm/loaders/LUTCubeLoader.js';

export { THREE };

// Quality presets. "off" renders exactly as a plain renderer.render() would, for A/B checks.
// post: render through the postprocessing chain (needed for AO, bloom, SMAA and the LUT); without
// it the renderer tone-maps straight to the canvas. aoScale is the AO resolution relative to the
// drawing buffer; msaa is the scene target's sample count; smaa runs in linear color before tone mapping.
export const QUALITY = {
  off: { enabled: false },
  low: { enabled: true, post: false, ibl: 'sh', pixelRatio: 1, anisotropy: 1, shadowMap: 1024, shadowType: 'pcf' },
  medium: { enabled: true, post: true, ibl: 'pmrem', pixelRatio: 1, msaa: 0, smaa: true, ao: true, aoScale: 0.5, aoSamples: 12, bloom: true, anisotropy: 4, shadowMap: 2048, shadowType: 'pcfsoft' },
  high: { enabled: true, post: true, ibl: 'pmrem', pixelRatio: 1.5, msaa: 4, smaa: false, ao: true, aoScale: 0.75, aoSamples: 16, bloom: true, anisotropy: 8, shadowMap: 2048, shadowType: 'pcfsoft' },
  ultra: { enabled: true, post: true, ibl: 'pmrem', pixelRatio: 2, msaa: 4, smaa: true, ao: true, aoScale: 1, aoSamples: 16, bloom: true, anisotropy: 8, shadowMap: 4096, shadowType: 'pcfsoft' },
};
// ibl: 'pmrem' lights every material from the prefiltered environment (diffuse and specular);
// 'sh' uses a 9-coefficient light probe for diffuse light and gives the prefiltered map only to
// glossy materials, which keeps software rendering (SwiftShader replays) fast.
const GLOSSY_ROUGHNESS = 0.45;
const SHADOW_TYPE = { basic: THREE.BasicShadowMap, pcf: THREE.PCFShadowMap, pcfsoft: THREE.PCFSoftShadowMap };

// Named environments shipped in the PBR library (assets/pbr/library.json).
const TONE_MAPPING = { aces: THREE.ACESFilmicToneMapping, agx: THREE.AgXToneMapping, neutral: THREE.NeutralToneMapping, none: THREE.NoToneMapping };

/** True when WebGL runs on a CPU rasterizer (SwiftShader, llvmpipe), as headless replays do. */
export function isSoftwareRenderer(renderer) {
  try {
    const gl = renderer.getContext();
    const info = gl.getExtension('WEBGL_debug_renderer_info');
    const name = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER));
    return /swiftshader|llvmpipe|softpipe|software|basic render/i.test(name);
  } catch {
    return false;
  }
}

/** Quality name from a URL query (?render=auto|off|low|medium|high|ultra), else ``fallback``. */
export function qualityFromQuery(search, fallback = 'auto') {
  try {
    const value = new URLSearchParams(search || '').get('render');
    return value && (value === 'auto' || value in QUALITY) ? value : fallback;
  } catch {
    return fallback;
  }
}

/** Joins a base URL and a relative path without the DOM's document.baseURI. */
function resolveUrl(base, path) {
  return new URL(path, base.endsWith('/') ? base : base + '/').href;
}

/**
 * Project an equirectangular float image (HDRLoader output, flipY) onto 3rd-order spherical
 * harmonics, as LightProbeGenerator does for cube maps; ``rotationY`` matches environmentRotation.
 */
function shFromEquirect({ data, width, height }, rotationY = 0) {
  const sh = new THREE.SphericalHarmonics3();
  const basis = new Array(9).fill(0);
  const direction = new THREE.Vector3();
  const channels = data.length / (width * height);
  const value = data instanceof Uint16Array ? (i) => THREE.DataUtils.fromHalfFloat(data[i]) : (i) => data[i];
  const step = Math.max(1, Math.floor(width / 256));
  let total = 0;
  for (let y = 0; y < height; y += step) {
    const latitude = (0.5 - (y + 0.5) / height) * Math.PI;  // row 0 is the top of the sky
    const cosLatitude = Math.cos(latitude);
    for (let x = 0; x < width; x += step) {
      const angle = ((x + 0.5) / width - 0.5) * 2 * Math.PI + rotationY;
      direction.set(Math.cos(angle) * cosLatitude, Math.sin(latitude), Math.sin(angle) * cosLatitude);
      THREE.SphericalHarmonics3.getBasisAt(direction, basis);
      const i = (y * width + x) * channels;
      const r = value(i), g = value(i + 1), b = value(i + 2);
      for (let k = 0; k < 9; k++) {
        const weight = basis[k] * cosLatitude;
        sh.coefficients[k].x += r * weight;
        sh.coefficients[k].y += g * weight;
        sh.coefficients[k].z += b * weight;
      }
      total += cosLatitude;
    }
  }
  const norm = (4 * Math.PI) / total;
  for (const coefficient of sh.coefficients) coefficient.multiplyScalar(norm);
  return sh;
}

// GTAO renders its depth/normal and AO targets at a fraction of the drawing buffer.
class ScaledGTAOPass extends GTAOPass {
  constructor(scene, camera, width, height, scale) {
    super(scene, camera, Math.max(1, Math.round(width * scale)), Math.max(1, Math.round(height * scale)));
    this.aoScale = scale;
  }
  setSize(width, height) {
    super.setSize(Math.max(1, Math.round(width * this.aoScale)), Math.max(1, Math.round(height * this.aoScale)));
  }
}

/**
 * Creates the kit for one renderer.
 *
 * @param {object} o
 * @param {THREE.WebGLRenderer} o.renderer
 * @param {THREE.Scene} o.scene            World scene (AO and bloom apply to it).
 * @param {THREE.Camera} o.camera
 * @param {number} o.width                 CSS-pixel width of the canvas.
 * @param {number} o.height
 * @param {string} o.assetBase             URL of the game's assets/ folder (e.g. new URL('../assets/', import.meta.url).href).
 * @param {string} [o.quality='auto']      auto | off | low | medium | high | ultra. auto = low on a
 *                                         software rasterizer (headless replays), high on a GPU.
 * @param {string|null} [o.environment]    Library environment id or an .hdr URL; null keeps the scene's lighting only.
 * @param {number} [o.environmentIntensity=1]
 * @param {boolean} [o.environmentBackground=false] Also use the HDR as the visible sky.
 * @param {string} [o.toneMapping='aces']  aces | agx | neutral | none.
 * @param {number} [o.exposure=1]
 * @param {object|false} [o.ao]            { radius, distanceExponent, thickness, scale, intensity } or false.
 * @param {object|false} [o.bloom]         { strength, radius, threshold } or false.
 * @param {string|THREE.Texture|null} [o.lut] URL of a .cube grade or a loaded 3D LUT texture.
 * @param {number} [o.lutIntensity=1]
 * @param {number} [o.maxPixelRatio]       Device pixel ratio supplied by the page (workers have none).
 */
export async function createRenderKit(o) {
  const kit = new RenderKit(o);
  await kit.ready;
  return kit;
}

export class RenderKit {
  constructor({
    renderer, scene, camera, width, height, assetBase,
    quality = 'auto', environment = undefined, environmentIntensity = 1, environmentBackground = false,
    toneMapping = 'aces', exposure = 1, ao = {}, bloom = {}, lut = null, lutIntensity = 1, maxPixelRatio = 1,
    tune = {}, depth = false,
  }) {
    if (!renderer || !scene || !camera) throw new Error('render kit needs renderer, scene and camera');
    // Keep the same visual profile across desktop and software replay. A slower backend must
    // not silently remove AO, reflections or resolution from the evidence being reviewed.
    if (quality === 'auto') quality = 'high';
    if (!(quality in QUALITY)) throw new Error(`unknown render quality "${quality}"`);
    this.THREE = THREE;
    this.renderer = renderer;
    this.scene = scene;
    this.camera = camera;
    this.assetBase = assetBase || '';
    this.quality = quality;
    this.preset = { ...QUALITY[quality], ...tune };  // tune: per-game preset overrides
    this.width = Math.max(1, width | 0);
    this.height = Math.max(1, height | 0);
    this.maxPixelRatio = maxPixelRatio;
    this.overlays = [];
    this.stats = { frames: 0, frameMs: 0, renderMs: 0 };
    this._lastFrame = 0;
    this._textures = new Map();
    this._materials = new Map();
    this._library = null;
    this._options = { ao, bloom, lutIntensity, depth };

    this.maxAnisotropy = Math.min(this.preset.anisotropy ?? 1, renderer.capabilities.getMaxAnisotropy());
    // "off" leaves the renderer exactly as the game configured it, for faithful A/B checks.
    this.enabled = Boolean(this.preset.enabled);
    if (this.enabled) {
      renderer.outputColorSpace = THREE.SRGBColorSpace;
      renderer.toneMapping = TONE_MAPPING[toneMapping] ?? THREE.ACESFilmicToneMapping;
      renderer.toneMappingExposure = exposure;
      renderer.shadowMap.enabled = true;
      renderer.shadowMap.type = SHADOW_TYPE[this.preset.shadowType] ?? THREE.PCFSoftShadowMap;
      if (this.preset.post) this._buildComposer();
      this.setSize(this.width, this.height, this.maxPixelRatio);
    }
    this.ready = Promise.all([
      this._loadLibrary(),
      this.smaaPass?.ready,
      lut && this.composer ? this.setLUT(lut, lutIntensity) : null,
    ]).then(() => (environment === null || !this.enabled ? null
      : this.setEnvironment(environment ?? this._library?.defaultEnvironment ?? null, { intensity: environmentIntensity, background: environmentBackground })))
      .then(() => this);
  }

  // ---------------------------------------------------------------- frame

  get pixelRatio() {
    return Math.min(this.preset.pixelRatio ?? 1, Math.max(1, this.maxPixelRatio));
  }

  _buildComposer() {
    const { renderer, scene, camera, preset } = this;
    const ratio = this.pixelRatio;
    const w = Math.round(this.width * ratio);
    const h = Math.round(this.height * ratio);
    // depth: passes after the scene pass can read the scene's depth (readBuffer.depthTexture).
    const target = new THREE.WebGLRenderTarget(w, h, {
      type: THREE.HalfFloatType, samples: preset.msaa || 0,
      ...(this._options.depth ? { depthTexture: new THREE.DepthTexture(w, h) } : {}),
    });
    const composer = new EffectComposer(renderer, target);
    composer.setPixelRatio(ratio);
    composer.setSize(this.width, this.height);
    this.renderPass = new RenderPass(scene, camera);
    composer.addPass(this.renderPass);

    const ao = this._options.ao;
    if (preset.ao && ao !== false) {
      this.aoPass = new ScaledGTAOPass(scene, camera, w, h, preset.aoScale);
      this.aoPass.updateGtaoMaterial({
        radius: ao.radius ?? 0.6, distanceExponent: ao.distanceExponent ?? 1.5,
        thickness: ao.thickness ?? 1.5, scale: ao.scale ?? 1, samples: preset.aoSamples,
      });
      this.aoPass.updatePdMaterial({ radius: 6, rings: 2, samples: 12 });
      this.aoPass.blendIntensity = ao.intensity ?? 1;
      composer.addPass(this.aoPass);
    }
    this._overlayIndex = composer.passes.length;  // overlays render after AO, before bloom

    const bloom = this._options.bloom;
    if (preset.bloom && bloom !== false) {
      // Linear HDR input: sunlit white surfaces reach ~2, so 2.5 keeps bloom on lamps, glints and screens.
      this.bloomPass = new UnrealBloomPass(new THREE.Vector2(w / 2, h / 2),
        bloom.strength ?? 0.2, bloom.radius ?? 0.4, bloom.threshold ?? 2.5);
      composer.addPass(this.bloomPass);
    }
    if (preset.smaa) {
      this.smaaPass = new SMAAPass();
      composer.addPass(this.smaaPass);
    }
    this.outputPass = new OutputPass();  // tone mapping + sRGB, from the renderer's settings
    composer.addPass(this.outputPass);
    this.lutPass = new LUTPass({ intensity: this._options.lutIntensity ?? 1 });
    this.lutPass.enabled = false;
    composer.addPass(this.lutPass);
    this.composer = composer;
  }

  /** Resize after the canvas changes; ``maxPixelRatio`` is the page's devicePixelRatio. */
  setSize(width, height, maxPixelRatio = this.maxPixelRatio) {
    this.width = Math.max(1, width | 0);
    this.height = Math.max(1, height | 0);
    this.maxPixelRatio = maxPixelRatio;
    this.renderer.setPixelRatio(this.enabled ? this.pixelRatio : Math.min(2, maxPixelRatio));
    this.renderer.setSize(this.width, this.height, false);
    if (this.composer) {
      this.composer.setPixelRatio(this.pixelRatio);
      this.composer.setSize(this.width, this.height);
    }
  }

  /**
   * Render a different world scene, e.g. one built after the kit (``pbr()`` needs the kit).
   * The environment lighting moves to the new scene unless it has its own.
   */
  setScene(scene) {
    const previous = this.scene;
    this.scene = scene;
    if (this.renderPass) this.renderPass.scene = scene;
    if (this.aoPass) this.aoPass.scene = scene;
    if (previous && previous !== scene && previous.environment && !scene.environment) {
      scene.environment = previous.environment;
      scene.environmentIntensity = previous.environmentIntensity;
      scene.environmentRotation.copy(previous.environmentRotation);
    }
    if (this.probe) scene.add(this.probe);
    scene.traverse((object) => this._glossyEnvironment(object));
  }

  /** Switch the camera that renders the world (and that AO reads depth from). */
  setCamera(camera) {
    this.camera = camera;
    if (this.renderPass) this.renderPass.camera = camera;
    if (this.aoPass) this.aoPass.camera = camera;
  }

  /**
   * Draw another scene over the world after AO and before bloom/tone mapping, e.g. a
   * first-person weapon (clearDepth: true) or world-space markers. Returns a handle with
   * ``enabled``.
   */
  addOverlay(scene, camera, { clearDepth = true } = {}) {
    const overlay = { scene, camera, clearDepth, enabled: true };
    if (this.composer) {
      const pass = new RenderPass(scene, camera);
      pass.clear = false;
      pass.clearDepth = clearDepth;
      Object.defineProperty(overlay, 'enabled', { get: () => pass.enabled, set: (v) => { pass.enabled = v; } });
      overlay.pass = pass;
      this.composer.insertPass(pass, this._overlayIndex++);
    }
    this.overlays.push(overlay);
    return overlay;
  }

  /** Render one frame. ``delta`` (seconds) is optional. */
  render(delta) {
    const now = performance.now();
    if (this._lastFrame) {
      const interval = now - this._lastFrame;
      this.stats.frameMs = this.stats.frameMs ? this.stats.frameMs * 0.9 + interval * 0.1 : interval;
    }
    this._lastFrame = now;
    if (this.composer) {
      this.composer.render(delta);
    } else {
      const { renderer } = this;
      renderer.render(this.scene, this.camera);
      const autoClear = renderer.autoClear;
      renderer.autoClear = false;
      for (const overlay of this.overlays) {
        if (!overlay.enabled) continue;
        if (overlay.clearDepth) renderer.clearDepth();
        renderer.render(overlay.scene, overlay.camera);
      }
      renderer.autoClear = autoClear;
    }
    const spent = performance.now() - now;
    this.stats.renderMs = this.stats.renderMs ? this.stats.renderMs * 0.9 + spent * 0.1 : spent;
    this.stats.frames++;
  }

  // ---------------------------------------------------------------- lighting

  /** Image-based lighting from a library environment id or an .hdr URL. */
  async setEnvironment(source, { intensity = 1, background = false, rotationY = 0 } = {}) {
    if (!source || !this.enabled) return null;
    const entry = this._library?.environments?.[source];
    const url = entry ? resolveUrl(this.assetBase, entry.hdr) : source;
    // Half float: full-float equirect input breaks PMREM on SwiftShader (NaN reflections).
    const hdr = await new HDRLoader().setDataType(THREE.HalfFloatType).loadAsync(url);
    hdr.mapping = THREE.EquirectangularReflectionMapping;
    const pmrem = new THREE.PMREMGenerator(this.renderer);
    const envMap = pmrem.fromEquirectangular(hdr).texture;
    pmrem.dispose();
    this._clearEnvironment();
    this.envMap = envMap;
    this.envIntensity = intensity;
    this.envRotationY = rotationY;
    if (this.preset.ibl === 'sh') {
      this.probe = new THREE.LightProbe(shFromEquirect(hdr.image, rotationY), intensity);
      this.probe.name = 'render-kit-environment';
      this.scene.add(this.probe);
      this.scene.traverse((object) => this._glossyEnvironment(object));
    } else {
      this.scene.environment = envMap;
      this.scene.environmentIntensity = intensity;
      this.scene.environmentRotation.set(0, rotationY, 0);
    }
    if (background) {
      this.scene.background = hdr;
      this.scene.backgroundRotation.set(0, rotationY, 0);
    } else {
      hdr.dispose();
    }
    return envMap;
  }

  _clearEnvironment() {
    if (this.probe) this.probe.removeFromParent();
    this.probe = null;
    if (this.envMap) {
      if (this.scene.environment === this.envMap) this.scene.environment = null;
      this.envMap.dispose();
    }
    this.envMap = null;
  }

  // In 'sh' mode only glossy materials sample the prefiltered map (reflections on paint, glass, metal).
  _glossyEnvironment(object) {
    if (this.preset.ibl !== 'sh' || !this.envMap || !object.isMesh) return;
    for (const material of Array.isArray(object.material) ? object.material : [object.material]) {
      if (!material?.isMeshStandardMaterial || material.envMap) continue;
      if (material.roughness > GLOSSY_ROUGHNESS && material.metalness < 0.5) continue;
      material.envMap = this.envMap;
      material.envMapIntensity = this.envIntensity;
      material.envMapRotation.set(0, this.envRotationY, 0);
      material.needsUpdate = true;
    }
  }

  /**
   * Configure a directional sun's shadow for a world of this size. Call ``followSun`` every
   * frame to keep the shadow box centred on the player without shimmering.
   */
  configureSun(light, { extent = 60, near = 1, far = 400, bias = -0.0002, normalBias = 0.02 } = {}) {
    light.castShadow = true;
    const size = this.preset.shadowMap ?? 2048;
    light.shadow.mapSize.set(size, size);
    const cam = light.shadow.camera;
    cam.left = -extent; cam.right = extent; cam.top = extent; cam.bottom = -extent;
    cam.near = near; cam.far = far;
    cam.updateProjectionMatrix();
    light.shadow.bias = bias;
    light.shadow.normalBias = normalBias;
    light.shadow.radius = 2;
    light.userData.renderKitSun = { extent, offset: light.position.clone().sub(light.target.position) };
    if (!light.target.parent) this.scene.add(light.target);
    return light;
  }

  /** Move a configured sun with ``focus`` (a Vector3), snapped to shadow texels. */
  followSun(light, focus) {
    const info = light.userData.renderKitSun;
    if (!info) return;
    const texel = (info.extent * 2) / light.shadow.mapSize.x;
    const x = Math.round(focus.x / texel) * texel;
    const z = Math.round(focus.z / texel) * texel;
    light.target.position.set(x, focus.y, z);
    light.position.copy(light.target.position).add(info.offset);
    light.target.updateMatrixWorld();
  }

  /** Load a .cube grade (or take a 3D LUT texture) and apply it after tone mapping. */
  async setLUT(source, intensity = 1) {
    let texture = source;
    if (typeof source === 'string') texture = (await new LUTCubeLoader().loadAsync(source)).texture3D;
    if (this.lutPass) {
      this.lutPass.lut = texture;
      this.lutPass.intensity = intensity;
      this.lutPass.enabled = Boolean(texture);
    }
    this.lut = texture;
    return texture;
  }

  // ---------------------------------------------------------------- materials

  async _loadLibrary() {
    if (!this.assetBase) return null;
    try {
      const response = await fetch(resolveUrl(this.assetBase, 'pbr/library.json'));
      if (response.ok) this._library = await response.json();
    } catch {
      this._library = null;
    }
    return this._library;
  }

  /** Ids of the PBR texture sets available to ``pbr()``. */
  get materials() {
    return Object.keys(this._library?.materials ?? {});
  }

  _texture(url, srgb) {
    const key = `${url}|${srgb}`;
    let entry = this._textures.get(key);
    if (!entry) {
      const texture = new THREE.Texture();
      texture.flipY = false;  // ImageBitmaps cannot be flipped on upload; they are decoded flipped
      texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
      texture.anisotropy = this.maxAnisotropy;
      texture.colorSpace = srgb ? THREE.SRGBColorSpace : THREE.NoColorSpace;
      const loaded = fetch(url)
        .then((r) => { if (!r.ok) throw new Error(`${r.status} ${url}`); return r.blob(); })
        .then((blob) => createImageBitmap(blob, { imageOrientation: 'flipY' }))
        .then((bitmap) => { texture.image = bitmap; texture.needsUpdate = true; return texture; });
      entry = { texture, loaded };
      this._textures.set(key, entry);
    }
    return entry;
  }

  /**
   * A MeshStandardMaterial from a library texture set. Returns at once; the maps appear when
   * loaded (``await material.userData.loaded`` to wait).
   *
   * @param {string} id               A library id (see ``materials``).
   * @param {object} [p]
   * @param {number} [p.tileMeters=2] World size of one texture tile when the geometry has world UVs
   *                                  (see ``worldUV``); otherwise use ``repeat``.
   * @param {number[]} [p.repeat]     UV repeat [u, v] for geometry with its own 0..1 UVs.
   * @param {THREE.ColorRepresentation} [p.tint=0xffffff] Multiplies the albedo, to match a reference colour.
   * @param {number} [p.roughness=1]  Multiplies the roughness map.
   * @param {number} [p.metalness=0]
   * @param {number} [p.normalScale=1]
   * @param {number} [p.aoIntensity=1]
   */
  pbr(id, { tileMeters = 2, repeat = null, tint = 0xffffff, roughness = 1, metalness = 0, normalScale = 1, aoIntensity = 1, ...rest } = {}) {
    const set = this._library?.materials?.[id];
    if (!set) throw new Error(`render kit: no PBR material "${id}" (have: ${this.materials.join(', ')})`);
    const scale = repeat ?? [1 / tileMeters, 1 / tileMeters];
    const key = JSON.stringify([id, scale, tint, roughness, metalness, normalScale, aoIntensity, rest]);
    const cached = this._materials.get(key);
    if (cached) return cached;
    if (!this.enabled) {  // the plain look the kit replaces: flat colour, no maps
      const flat = new THREE.MeshLambertMaterial({ color: new THREE.Color(tint), ...rest });
      flat.name = `pbr-off:${id}`;
      flat.userData.loaded = Promise.resolve(flat);
      this._materials.set(key, flat);
      return flat;
    }
    const material = new THREE.MeshStandardMaterial({
      color: new THREE.Color(tint), roughness, metalness, ...rest,
    });
    material.name = `pbr:${id}`;
    material.normalScale.set(normalScale, normalScale);
    material.aoMapIntensity = aoIntensity;
    const slots = { diff: ['map', true], nor_gl: ['normalMap', false], rough: ['roughnessMap', false], ao: ['aoMap', false] };
    const pending = [];
    for (const [kind, [slot, srgb]] of Object.entries(slots)) {
      const file = set.maps?.[kind];
      if (!file) continue;
      const { texture, loaded } = this._texture(resolveUrl(this.assetBase, file), srgb);
      const view = texture.clone();  // shares the image upload, own repeat
      view.repeat.set(scale[0], scale[1]);
      // Attach only once decoded: an empty map samples black and would flash dark frames.
      pending.push(loaded.then(() => {
        view.needsUpdate = true;
        material[slot] = view;
        material.needsUpdate = true;
      }));
    }
    material.userData.loaded = Promise.all(pending).then(() => material);
    this._glossyEnvironment({ isMesh: true, material });
    this._materials.set(key, material);
    return material;
  }

  /**
   * Replace a mesh's UVs with world-space box projection (``meters`` per unit UV), so tiled PBR
   * textures keep a constant real-world size on boxes and extrusions of any scale. Call after
   * the mesh is placed. The geometry is cloned so shared geometries stay untouched.
   */
  worldUV(mesh, meters = 1) {
    mesh.updateWorldMatrix(true, false);
    const geometry = mesh.geometry.clone();
    const position = geometry.attributes.position;
    const normal = geometry.attributes.normal ?? (geometry.computeVertexNormals(), geometry.attributes.normal);
    const uv = new Float32Array(position.count * 2);
    const p = new THREE.Vector3();
    const n = new THREE.Vector3();
    const normalMatrix = new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld);
    for (let i = 0; i < position.count; i++) {
      p.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);
      n.fromBufferAttribute(normal, i).applyMatrix3(normalMatrix);
      const ax = Math.abs(n.x), ay = Math.abs(n.y), az = Math.abs(n.z);
      let u, v;
      if (ay >= ax && ay >= az) { u = p.x; v = p.z; }
      else if (ax >= az) { u = p.z * Math.sign(n.x || 1); v = p.y; }
      else { u = -p.x * Math.sign(n.z || 1); v = p.y; }
      uv[i * 2] = u / meters;
      uv[i * 2 + 1] = v / meters;
    }
    geometry.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
    mesh.geometry = geometry;
    return mesh;
  }

  /**
   * Convert Lambert/Phong materials under ``root`` to MeshStandardMaterial so they respond to
   * the environment and AO consistently. Shared materials stay shared. Basic, line, point,
   * sprite and shader materials are left alone (HUD, sky, markers).
   */
  standardize(root, { roughness = 0.85, metalness = 0, skip = () => false } = {}) {
    if (!this.enabled) return 0;
    const converted = new Map();
    const convert = (material) => {
      if (!(material?.isMeshLambertMaterial || material?.isMeshPhongMaterial)) return material;
      if (converted.has(material)) return converted.get(material);
      const next = new THREE.MeshStandardMaterial({
        color: material.color, map: material.map, emissive: material.emissive,
        emissiveMap: material.emissiveMap, emissiveIntensity: material.emissiveIntensity,
        normalMap: material.normalMap ?? null, aoMap: material.aoMap ?? null, lightMap: material.lightMap ?? null,
        alphaMap: material.alphaMap, transparent: material.transparent, opacity: material.opacity,
        alphaTest: material.alphaTest, side: material.side, vertexColors: material.vertexColors,
        flatShading: material.flatShading ?? false, fog: material.fog, depthWrite: material.depthWrite,
        depthTest: material.depthTest, polygonOffset: material.polygonOffset,
        polygonOffsetFactor: material.polygonOffsetFactor, polygonOffsetUnits: material.polygonOffsetUnits,
        metalness,
        roughness: material.isMeshPhongMaterial ? Math.sqrt(2 / (material.shininess + 2)) : roughness,
      });
      next.name = material.name;
      next.userData = { ...material.userData, standardizedFrom: material.type };
      converted.set(material, next);
      return next;
    };
    root.traverse((object) => {
      if (!object.isMesh || skip(object)) return;
      object.material = Array.isArray(object.material) ? object.material.map(convert) : convert(object.material);
      this._glossyEnvironment(object);
    });
    for (const old of converted.keys()) old.dispose();
    return converted.size;
  }

  dispose() {
    this.composer?.dispose?.();
    this.aoPass?.dispose?.();
    this.bloomPass?.dispose?.();
    this.smaaPass?.dispose?.();
    for (const { texture } of this._textures.values()) texture.dispose();
    for (const material of this._materials.values()) material.dispose();
    this._clearEnvironment();
  }
}