CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
Raw History Blame Contribute Delete
28.2 kB
// 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();
}
}