Spaces:
Running
Running
Download src/render/baked.js from VectorW/xlerobot-sim: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/VectorW/xlerobot-sim/resolve/main/src/render/baked.js
- Command line
-
hf download hf://spaces/VectorW/xlerobot-sim/src/render/baked.js
-
curl -L -o baked.js https://huggingface.co/spaces/VectorW/xlerobot-sim/resolve/main/src/render/baked.js
13.2 kB
| // Baked light for the Lit renderer (tools/bake_light.mjs): the scenery shows its light map, and everything | |
| // that moves (the robot, the objects, doors and drawers) takes its diffuse light from the probe grid at | |
| // its place, so it darkens under a table or inside a cupboard as the scenery around it does. Reflections | |
| // come from an environment map captured in the room, dimmed where the baked light is dim (a corner does | |
| // not mirror the bright room). | |
| // | |
| // What moves is not in the bake, so it casts no shade there: SkyOcclusion draws it from above every frame | |
| // (coverage and height, mipmapped) and every lit surface below it loses part of its sky, over a penumbra | |
| // that widens with the height above it, as under the overcast sky the room was baked with. | |
| import * as THREE from "three"; | |
| import { download, json } from "../core/assets.js"; | |
| import { gunzip } from "../meshpack.js"; | |
| /** The layer of the meshes that cast sky occlusion (the moving ones). */ | |
| export const OCCLUSION_LAYER = 5; | |
| // Heights in the occlusion map's blue channel are stored as CEILING minus the height (metres). | |
| const CEILING = 4; | |
| /** Load an environment's bake: { meta, lightmap, probes, occlusion }, or null when baked for another layout. */ | |
| export async function loadBake(url, fingerprint) { | |
| const meta = await json(url); | |
| if (meta.fingerprint !== fingerprint) { | |
| console.warn(`${url}: baked for another layout (${meta.fingerprint}, this scene is ${fingerprint}); bake again (tools/bake_light.mjs)`); | |
| return null; | |
| } | |
| const base = url.slice(0, url.lastIndexOf("/") + 1); | |
| const [png, packed] = await Promise.all([download(base + meta.lightmap.file), download(base + meta.probes.file)]); | |
| const bitmap = await createImageBitmap(new Blob([png], { type: "image/png" }), { premultiplyAlpha: "none", colorSpaceConversion: "none" }); | |
| const lightmap = new THREE.Texture(bitmap); | |
| lightmap.flipY = false; | |
| lightmap.colorSpace = THREE.SRGBColorSpace; | |
| lightmap.channel = 1; // the "uv1" attribute (statics.js) | |
| lightmap.minFilter = THREE.LinearFilter; | |
| lightmap.magFilter = THREE.LinearFilter; | |
| lightmap.generateMipmaps = false; | |
| lightmap.needsUpdate = true; | |
| const bytes = await gunzip(packed); | |
| const [nx, ny, nz] = meta.probes.dims; | |
| const n = nx * ny * nz; | |
| const probes = Array.from({ length: 6 }, (_, d) => { | |
| const t = new THREE.Data3DTexture(bytes.slice(4 * d * n, 4 * (d + 1) * n), nx, ny, nz); | |
| t.format = THREE.RGBAFormat; | |
| t.type = THREE.UnsignedByteType; | |
| t.colorSpace = THREE.SRGBColorSpace; | |
| t.minFilter = THREE.LinearFilter; | |
| t.magFilter = THREE.LinearFilter; | |
| t.unpackAlignment = 1; | |
| t.needsUpdate = true; | |
| return t; | |
| }); | |
| const { origin, step } = meta.probes; | |
| const occlusion = new SkyOcclusion(origin[0], origin[1], origin[0] + step[0] * (nx - 1), origin[1] + step[1] * (ny - 1)); | |
| const dispose = () => { | |
| for (const t of [lightmap, ...probes]) t.dispose(); | |
| occlusion.dispose(); | |
| }; | |
| return { meta, lightmap, probes, occlusion, dispose }; | |
| } | |
| // A pose in a matrix's elements (column-major): the rotation's columns and the translation (12 to 14). | |
| const POSE = [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14]; | |
| /** | |
| * Whether meshes moved: `changed(movers, hz)` is true when any pose (or the set of meshes) differs from the | |
| * last time it was true, at most `hz` times a second. What only needs drawing again when something moved | |
| * (the sky occlusion map, the sun's shadow map) asks it each frame. | |
| */ | |
| export class MotionWatch { | |
| changed(movers, hz = 30) { | |
| const now = performance.now(); | |
| if (this.poses && now - this.last < 1000 / hz) return false; | |
| const n = POSE.length * movers.length; | |
| let moved = false; | |
| if (this.poses?.length !== n) { | |
| this.poses = new Float32Array(n); | |
| moved = true; | |
| } | |
| for (let k = 0; k < movers.length; k++) { | |
| const e = movers[k].matrix.elements; | |
| for (let j = 0; j < POSE.length; j++) { | |
| const v = e[POSE[j]]; // shown or not: a hidden shape stands for a model drawn on it | |
| if (Math.abs(v - this.poses[POSE.length * k + j]) > 1e-4) { | |
| this.poses[POSE.length * k + j] = v; | |
| moved = true; | |
| } | |
| } | |
| } | |
| if (moved) this.last = now; | |
| return moved; | |
| } | |
| invalidate() { | |
| this.poses = null; | |
| } | |
| } | |
| /** | |
| * What moves, drawn from straight above into a small map: whether it covers each texel (red), the height | |
| * of its top there (green) and of its bottom (blue, as CEILING minus the height), all three kept by a max | |
| * blend in one pass and zero where nothing is. Mipmapped, so a surface reads the coverage and the mean top | |
| * and bottom over any footprint in one lookup. | |
| */ | |
| export class SkyOcclusion { | |
| constructor(x0, y0, x1, y1, size = 512) { | |
| const pad = 0.3; | |
| [x0, y0, x1, y1] = [x0 - pad, y0 - pad, x1 + pad, y1 + pad]; | |
| this.target = new THREE.WebGLRenderTarget(size, size, { | |
| type: THREE.HalfFloatType, | |
| generateMipmaps: true, | |
| minFilter: THREE.LinearMipmapLinearFilter, | |
| magFilter: THREE.LinearFilter, | |
| }); | |
| this.camera = new THREE.OrthographicCamera(x0, x1, y1, y0, 0.05, 4); | |
| this.camera.position.set(0, 0, 3.5); | |
| this.camera.up.set(0, 1, 0); | |
| this.camera.lookAt(0, 0, 0); | |
| this.camera.updateMatrixWorld(); | |
| this.camera.layers.set(OCCLUSION_LAYER); | |
| this.material = new THREE.ShaderMaterial({ | |
| vertexShader: /* glsl */ ` | |
| varying float vZ; | |
| void main() { | |
| vec4 w = modelMatrix * vec4( position, 1.0 ); | |
| vZ = w.z; | |
| gl_Position = projectionMatrix * viewMatrix * w; | |
| }`, | |
| fragmentShader: /* glsl */ ` | |
| varying float vZ; | |
| void main() { gl_FragColor = vec4( 1.0, max( vZ, 0.0 ), ${CEILING.toFixed(1)} - vZ, 1.0 ); }`, | |
| side: THREE.DoubleSide, | |
| depthTest: false, | |
| depthWrite: false, | |
| blending: THREE.CustomBlending, | |
| blendEquation: THREE.MaxEquation, | |
| blendSrc: THREE.OneFactor, | |
| blendDst: THREE.OneFactor, | |
| }); | |
| this.uniforms = { | |
| skyMap: { value: this.target.texture }, | |
| skyRect: { value: new THREE.Vector4(x0, y0, 1 / (x1 - x0), 1 / (y1 - y0)) }, | |
| skyTexel: { value: (x1 - x0) / size }, | |
| skyStrength: { value: 0.7 }, | |
| }; | |
| this.clear = new THREE.Color(); | |
| this.watch = new MotionWatch(); | |
| } | |
| /** | |
| * Draw the moving meshes (those on OCCLUSION_LAYER) into the map when any of `movers` has moved since | |
| * the last time, at most `hz` times a second: soft shade a frame late is not seen, and a still scene | |
| * costs nothing. | |
| */ | |
| update(renderer, scene, movers, hz = 30) { | |
| if (!this.watch.changed(movers, hz)) return; | |
| this.drawn = performance.now(); | |
| const { overrideMaterial, background } = scene; | |
| const target = renderer.getRenderTarget(); | |
| renderer.getClearColor(this.clear); | |
| const alpha = renderer.getClearAlpha(); | |
| scene.overrideMaterial = this.material; | |
| scene.background = null; | |
| renderer.setRenderTarget(this.target); | |
| renderer.setClearColor(0x000000, 0); | |
| renderer.clear(); | |
| renderer.render(scene, this.camera); | |
| renderer.setRenderTarget(target); | |
| renderer.setClearColor(this.clear, alpha); | |
| scene.overrideMaterial = overrideMaterial; | |
| scene.background = background; | |
| } | |
| /** Draw again at the next update, moved or not (after the style or the scene changed). */ | |
| invalidate() { | |
| this.watch.invalidate(); | |
| } | |
| dispose() { | |
| this.target.dispose(); | |
| this.material.dispose(); | |
| } | |
| } | |
| const LUMA = "vec3( 0.2126, 0.7152, 0.0722 )"; | |
| // Irradiance over pi under the open sky (tools/bake_light.mjs): where a surface gets this much or more, | |
| // it reflects the room in full. | |
| const OPEN = "0.75"; | |
| const COMMON = /* glsl */ ` | |
| varying vec3 vBakedPos; | |
| uniform sampler2D skyMap; | |
| uniform vec4 skyRect; | |
| uniform float skyTexel; | |
| uniform float skyStrength; | |
| // The share of the sky that what moves hides from a surface at p facing n. Round about (30 cm), the movers' | |
| // mean top and bottom: how far above p the nearest of them is (their bottom when all of them is above p, | |
| // half their height above it when they stand beside it); then their coverage within cones of that | |
| // distance, as an overcast sky is hidden by a slab above. | |
| float skyOcclusion( vec3 p, vec3 n ) { | |
| vec2 uv = ( p.xy - skyRect.xy ) * skyRect.zw; | |
| if ( uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0 || n.z < -0.5 ) return 0.0; | |
| vec3 near = textureLod( skyMap, uv, log2( 0.3 / skyTexel ) ).rgb; | |
| if ( near.r < 0.002 ) return 0.0; | |
| float top = near.g / near.r - p.z; | |
| if ( top < 0.01 ) return 0.0; | |
| float bottom = ${CEILING.toFixed(1)} - near.b / near.r - p.z; | |
| float h = clamp( bottom > 0.01 ? bottom : 0.5 * top, 0.01, 1.0 ); | |
| float inner = textureLod( skyMap, uv, max( 0.0, log2( 2.0 * h / skyTexel ) ) ).r; | |
| float outer = textureLod( skyMap, uv, max( 0.0, log2( 6.0 * h / skyTexel ) ) ).r; | |
| return ( 0.65 * inner + 0.35 * outer ) * smoothstep( 0.01, 0.04, top ) * ( 0.6 + 0.4 * n.z ); | |
| }`; | |
| // three.js's light-map and environment chunk: the sky occlusion of what moves on the light map or on the | |
| // probes, the environment's diffuse light left out where those give it, and the environment's reflections | |
| // dimmed by them. | |
| const MAPS_CHUNK = THREE.ShaderChunk.lights_fragment_maps | |
| .replace( | |
| "#if defined( RE_IndirectDiffuse )", | |
| `#if defined( RE_IndirectDiffuse ) | |
| vec3 bakedNormal = inverseTransformDirection( geometryNormal, viewMatrix ); | |
| float skySeen = 1.0 - skyStrength * skyOcclusion( vBakedPos, bakedNormal ); | |
| #if defined( USE_PROBES ) | |
| vec3 probeE = probeIrradiance( vBakedPos, bakedNormal ) * skySeen; | |
| irradiance += probeE; | |
| #endif`, | |
| ) | |
| .replace("vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;", "vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity * skySeen;") | |
| .replace( | |
| "iblIrradiance += getIBLIrradiance( geometryNormal );", | |
| `#if !defined( USE_PROBES ) && !defined( USE_LIGHTMAP ) | |
| iblIrradiance += getIBLIrradiance( geometryNormal ); | |
| #endif`, | |
| ) | |
| .replace( | |
| "radiance += iblRadiance;", | |
| `#if defined( USE_PROBES ) | |
| iblRadiance *= clamp( dot( probeE, ${LUMA} ) / ( PI * ${OPEN} ), 0.0, 1.0 ); | |
| #elif defined( USE_LIGHTMAP ) | |
| iblRadiance *= clamp( dot( lightMapIrradiance, ${LUMA} ) / ( PI * ${OPEN} ), 0.0, 1.0 ); | |
| #endif | |
| radiance += iblRadiance;`, | |
| ); | |
| if (MAPS_CHUNK.split("skySeen").length !== 4 || !MAPS_CHUNK.includes("!defined( USE_LIGHTMAP )")) { | |
| console.warn("baked.js: three.js's lights_fragment_maps changed; baked light may look wrong"); | |
| } | |
| /** The world position, for the probes and the sky occlusion. */ | |
| function withPosition(shader, extra = "") { | |
| shader.vertexShader = shader.vertexShader | |
| .replace("#include <common>", "#include <common>\nvarying vec3 vBakedPos;") | |
| .replace("#include <project_vertex>", "#include <project_vertex>\n\tvBakedPos = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;"); | |
| shader.fragmentShader = shader.fragmentShader.replace("#include <common>", `#include <common>\n${COMMON}\n${extra}`).replace("#include <lights_fragment_maps>", MAPS_CHUNK); | |
| } | |
| /** A scenery material (with "uv1"): its light map instead of the environment's diffuse light. */ | |
| export function bakeScenery(material, bake) { | |
| material.lightMap = bake.lightmap; | |
| material.lightMapIntensity = Math.PI * bake.meta.scale; | |
| material.onBeforeCompile = (shader) => { | |
| Object.assign(shader.uniforms, bake.occlusion.uniforms); | |
| withPosition(shader); | |
| }; | |
| material.customProgramCacheKey = () => "baked-scenery"; | |
| material.needsUpdate = true; | |
| } | |
| /** A moving thing's material: diffuse light from the probes at each fragment's place. */ | |
| export function bakeMoving(material, bake) { | |
| const { origin, step, dims } = bake.meta.probes; | |
| const uniforms = { | |
| probeTex: { value: bake.probes }, | |
| probeOrigin: { value: new THREE.Vector3(...origin) }, | |
| probeSpan: { value: new THREE.Vector3(step[0] * (dims[0] - 1), step[1] * (dims[1] - 1), step[2] * (dims[2] - 1)) }, | |
| probeDims: { value: new THREE.Vector3(...dims) }, | |
| probeScale: { value: Math.PI * bake.meta.scale }, | |
| }; | |
| material.onBeforeCompile = (shader) => { | |
| Object.assign(shader.uniforms, uniforms, bake.occlusion.uniforms); | |
| shader.defines = { ...shader.defines, USE_PROBES: "" }; | |
| withPosition( | |
| shader, | |
| /* glsl */ ` | |
| uniform highp sampler3D probeTex[ 6 ]; | |
| uniform vec3 probeOrigin; | |
| uniform vec3 probeSpan; | |
| uniform vec3 probeDims; | |
| uniform float probeScale; | |
| // Irradiance at p for a surface facing n: the six directions' irradiance, weighted by n squared (an | |
| // ambient cube), looked up a little off the surface, so that a probe behind it counts less. | |
| vec3 probeIrradiance( vec3 p, vec3 n ) { | |
| vec3 g = clamp( ( p + n * 0.06 - probeOrigin ) / probeSpan, 0.0, 1.0 ); | |
| vec3 t = ( g * ( probeDims - 1.0 ) + 0.5 ) / probeDims; | |
| vec3 w = n * n; | |
| vec3 e = w.x * ( n.x > 0.0 ? texture( probeTex[ 0 ], t ).rgb : texture( probeTex[ 1 ], t ).rgb ) | |
| + w.y * ( n.y > 0.0 ? texture( probeTex[ 2 ], t ).rgb : texture( probeTex[ 3 ], t ).rgb ) | |
| + w.z * ( n.z > 0.0 ? texture( probeTex[ 4 ], t ).rgb : texture( probeTex[ 5 ], t ).rgb ); | |
| return e * probeScale; | |
| }`, | |
| ); | |
| }; | |
| material.customProgramCacheKey = () => "baked-moving"; | |
| material.needsUpdate = true; | |
| } | |