Download bench_builder/render_kit/web/README.md from CharlieDreemur/Recreate-AAA: direct link, hf CLI and curl.
- Browser
- Download file 16.3 kB
-
https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/bench_builder/render_kit/web/README.md
- Command line
-
hf download hf://CharlieDreemur/Recreate-AAA/bench_builder/render_kit/web/README.md
-
curl -L -o README.md https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/bench_builder/render_kit/web/README.md
Render kit
render-kit.js gives a three.js game a physically based look in a few calls. It runs on the main
thread and in a worker that renders to an OffscreenCanvas (it uses no DOM API).
three.js in this folder re-exports the game's own three.js so the kit, its addons (jsm/, from
three 0.185.1, MIT) and the game share one module instance. The installer regenerates this folder
every build round; configure the kit through its options instead of editing these files.
Setup
import { createRenderKit, qualityFromQuery } from '../lib/render-kit/render-kit.js';
const kit = await createRenderKit({
renderer, scene, camera,
width, height, // CSS pixels of the canvas
maxPixelRatio: devicePixelRatio,
assetBase: new URL('../assets/', import.meta.url).href,
quality: qualityFromQuery(location.search), // ?render=auto|off|low|medium|high|ultra, default auto
environment: 'wide_street_01', // id from assets/pbr/library.json, an .hdr URL, or null
environmentIntensity: 1,
toneMapping: 'aces', // aces | agx | neutral | none
exposure: 1,
ao: { radius: 0.6, intensity: 1 }, // or false
bloom: { strength: 0.2, threshold: 2.5 }, // or false; threshold is in linear HDR units
lut: null, // '.cube' URL of an existing grade, applied after tone mapping
});
Each frame call kit.render(dt) instead of renderer.render(scene, camera). On resize call
kit.setSize(width, height, devicePixelRatio). If the game switches cameras, call
kit.setCamera(camera). To build the world after the kit (pbr() needs the kit), create the kit
with an empty scene and call kit.setScene(world); the environment lighting moves with it.
quality: 'off' disables the kit's render effects: the renderer settings are left alone, standardize and
setEnvironment do nothing and pbr() returns a flat Lambert colour. Use it for A/B comparisons.
| quality | environment light | postprocessing | AA | ambient occlusion | bloom | shadow map |
|---|---|---|---|---|---|---|
| low | light probe; reflections on glossy materials only | none (tone-mapped directly) | canvas | off | off | 1024 PCF |
| medium | prefiltered, every material | yes | SMAA | half resolution | on | 2048 soft |
| high | prefiltered, every material | yes | MSAA 4x | 0.75 resolution | on | 2048 soft |
| ultra | prefiltered, every material | yes | MSAA 4x + SMAA | full resolution | on | 4096 soft |
auto (the default) uses high on both desktop and software renderers. It does not silently
remove effects or lower resolution for benchmark footage. Software rendering can be substantially
slower: measure a short trial before integrating. Preserve the verified build if the trial cannot
meet its input/render timing requirements. An explicit low run is diagnostic evidence for that
profile only, never acceptance of the high profile. Record backend, profile and drawing-buffer size.
For before/after comparisons, retain a frozen original build: off cannot undo caller changes to
materials, UVs, ambient lights or scene geometry.
Materials
kit.materials; // ids available in assets/pbr/library.json
const plaster = kit.pbr('white_plaster_02', { tileMeters: 3, tint: 0xe8dcc4 });
building.material = plaster;
kit.worldUV(building); // after the mesh is placed and scaled
pbr(id, options) returns a MeshStandardMaterial immediately and attaches the colour, normal,
roughness and AO maps once they are decoded (await material.userData.loaded to wait). Identical
requests return the same material. Options: tileMeters (world size of one tile when the geometry
has world UVs), repeat: [u, v] (for geometry with its own 0..1 UVs), tint (multiplies the
albedo; match the reference colour), roughness and normalScale (multipliers), metalness,
aoIntensity, plus any MeshStandardMaterial parameter.
worldUV(mesh, meters = 1) replaces the mesh's UVs with a world-space box projection so texel
size stays constant across boxes and extrusions of any scale. It clones the geometry.
standardize(root, { roughness: 0.85 }) converts every Lambert/Phong material under root to
MeshStandardMaterial, keeping colours, maps and emissive settings and sharing converted
materials where the originals were shared. Basic, line, sprite and shader materials (HUD, sky,
markers) are left alone; pass skip: (mesh) => boolean for others.
Lighting
setEnvironment(idOrUrl, { intensity, background = false, rotationY }): image-based lighting. Keepbackground: falsewhen the game draws its own sky. The environment is the ambient light: lower or remove the game's hemisphere/ambient lights, or the scene washes out.- A
THREE.Colorscene background is tone-mapped by the postprocessing chain (medium and up) but not atlow, so the sky looks paler on a GPU. Draw the sky as a mesh (it is tone-mapped at every quality) or pick the background colour for the quality that replays use. configureSun(light, { extent = 60 })sizes a directional light's shadow box; callfollowSun(light, focus)every frame to keep it centred on the player, snapped to shadow texels so edges do not shimmer.addOverlay(scene, camera, { clearDepth = true })draws a second scene after AO and before bloom and tone mapping, e.g. a first-person weapon.setLUT(urlOrTexture, intensity)sets or replaces the grade.
Look parameters (look.js) and fitting them to the reference
createLook() wraps the kit and keeps everything that decides how a frame looks in one JSON object,
so the numbers can be fitted to reference frames instead of tuned by hand:
import { createLook, qualityFromQuery } from '../lib/render-kit/look.js';
const look = await createLook({
renderer, scene, camera, width, height, maxPixelRatio: devicePixelRatio,
quality: qualityFromQuery(location.search),
look: 'look.json', // fitted numbers; a missing file means neutral defaults
});
road.material = look.surface('road', { type: 'asphalt', color: 0x55585c });
look.adopt(scene); // every remaining plain-colour material becomes a surface, colour kept
// frame: look.render(dt) resize: look.setSize(w, h, devicePixelRatio) camera swap: look.setCamera(c)
- What is a parameter.
sky(mode: 'sky'with sun azimuth/elevation, haze, clouds, brightness, ormode: 'room'with ceiling/wall/floor colours for enclosed places),fog(density, height),post(exposure, tone mapping, contrast, saturation, temperature, tint, lift, vignette, grain, bloom) and one entry per surface (colour, roughness, dirt, wear, rust, wet, scale). The sun, the ambient light and the reflections all come from the same sky, so they cannot disagree.look.paramsis the live object;look.set(patch)changes it without recompiling anything. - Defaults add nothing. No haze, clouds, grain, vignette, dirt or wetness appears unless a number asks for it. Remove the game's own sun, hemisphere/ambient lights, background colour and fog: the look provides them (add your own point/spot lights for lamps as usual).
- Surfaces. Types:
generic,concrete,asphalt,plaster,painted_metal,bare_metal,brick,tile,wood,glass,ground,grass,fabric. They are procedural (no textures, no UVs) and drawn in world space; passspace: 'object'for things that move.adopt()picks a type frommesh.userData.surface, else from words in the material or mesh name (road, concrete, brick, wood, glass, metal ...), elsegeneric. You decide what each surface is; its numbers are fitted. - Fitting. After a replay with the scene probe, call
mcp__reference_replay__look_fit. It renders the build from the replay's camera poses, compares with the reference at the same moments and searches every number above until the frames agree (a couple of thousand frames, one to three minutes on a GPU). It writeslook.jsonand a reference/before/after sheet. Then replay again and read the scorecard'slook. It cannot fix geometry, a wrong surface type or missing objects: those are what remains different in the sheet. - At quality
low(no postprocessing) haze becomes plain fog and the grade is skipped.
Checking the cost
kit.stats.frameMs is the smoothed interval between render() calls; kit.stats.renderMs is the
CPU time spent inside them. After integrating, compare a full replay's replay_clock.speed (game
seconds per real second; 1.0 is real time) and dark-frame count with the previous replay. If the
speed drops, lower quality before removing an effect.
Library
assets/pbr/library.json lists the texture sets and HDR environments with what each is for. All
are CC0 from Poly Haven. Add your own set by placing its maps under assets/pbr/textures/<id>/
and adding an entry with its licence.
Spatial helpers
spatial.js turns the video contract's measured space into a camera pose and correctly sized
geometry, and publishes the scene probe the replay records. It needs only three.js (through the
same ./three.js shim) and is installed for video builds even when the rest of the kit is off.
Conventions: metres, +Y up, -Z forward, X right; headings 0 = -Z, positive turns right; pitch
negative looks down; screen boxes normalised (x 0 left .. 1 right, y 0 top .. 1 bottom).
import * as spatial from '../lib/render-kit/spatial.js';
// Shot cameras from shot_list[].camera.rig (resolve keyframes at the clip time first).
const rig = spatial.rigAt(shot.camera.rig, clipSeconds, { start: shot.start_seconds });
spatial.placeShotCamera(camera, sedan, rig, { ground: 0, subjectForward: new THREE.Vector3(0, 0, -1) });
// Places from contract places[]: the road, what lines it, a vehicle interior.
const road = spatial.buildRoad(place.road); // road.userData.lanes: lane centre x offsets
const frontage = spatial.buildFrontage(place.frontage, { road: place.road, length_m: place.road.length_m });
const cabin = spatial.buildCabin(place.interior); // cabin.getObjectByName('mount.dash-left').add(camera)
// Report what is on screen: tag every object with its contract type_id, then install the probe once.
spatial.tagObject(sedanMesh, 'sedan', 'sedan-00');
spatial.installSceneProbe({ getCamera: () => activeCamera, scene, getShot: () => currentShotId,
groundHeightAt: (x, z) => terrainHeight(x, z) });
spatial.installTopDownProbe({ renderer, scene, getCentre: () => player.position });
placeShotCamera(camera, subject, rig, {ground, subjectForward}):azimuth_deg0 sits behind the subject looking the way it faces (90 = its right, 180 = in front);height_mis above the ground under the camera and the horizontal offset is solved so the 3D distance to the subject's box centre equalsdistance_m; withoutpitch_degthe camera looks at that centre;hfov_degsets the verticalfovthroughcamera.aspect. Models authored facing +Z needsubjectForward: new THREE.Vector3(0, 0, 1).rigAt(rig, t, {start}): keyframes hold unnamed fields; numbers interpolate linearly, angles along the shortest arc,subject_boxper coordinate.buildRoad(road): origin at the start of the centre line on the road surface, running to -Z. Width islanes * lane_width_m + 2 * shoulder_m + median.width_m + 2 * sidewalk_m. Elevated roads keep the surface at y = 0 with the ground at-deck_height_m(default 8,userData.ground_y). Curves are 500 m (gentle) or 80 m (sharp) radius arcs unlessradius_mis given;roadFrameAt(road, s, offset)gives the position and headingsmetres along it for placing vehicles. Meshes are namedroad.asphalt,road.markings.*,road.median.*,road.sidewalk.*,road.kerb.*,road.deck,road.railing.*,road.piers; replace their materials freely.buildFrontage(blocks, {road, length_m}):setback_mis from the road's outer edge to the front face;spacing_mis centre to centre; towers vary +/-20 % in height, deterministically.buildCabin(interior): origin at the cabin's centre in plan at floor level (seat cushions atuserData.hip_y), -Z toward the windshield.camera_mountsuse this frame; each becomes a childmount.<id>already aimed at itslook_at, anduserData.mountslists them.buildRooms(place): the floor plan of a contractroomsplace as grey boxes to size: a group in the place frame with one childroom.<id>per room (floor, ceiling, walls with every opening cut out, a lintel above doors, a sill below windows).userData.segmentslists the solid wall lines;resolveWalls(rooms, position, radius)pushes a walker's{x, z}out of them after each step, androomAt(place, x, z)names the room a point is in. Build this first and walk the replay through it before dressing anything: the recorded inputs put the camera wherever your walls let it go.installSceneProbe({..., getPlace}): a game the player walks through passesgetPlace: () => ({id, origin: [x, y, z], yaw_deg})(the current place and where its frame sits in your world); the probe then reportscamera.place: {id, x_m, z_m, yaw_deg}and the review checks it against the contract'sroute.installSceneProbe(...)defineswindow.__gbbSceneProbe(), returning{shot, camera: {hfov_deg, position, height_m, yaw_deg, pitch_deg, roll_deg, horizon_y}, objects}with one{type_id, instance_id, box, distance_m, visible}per tagged object on screen (boxes of objects partly behind the camera are clipped at the near plane). It caches each object's bounds: callprobe.invalidate(object)after swapping its geometry. It costs well under 1 ms for 200 tagged objects and never throws. A game rendering in a worker calls the returned function there and posts the result to the page, whosewindow.__gbbSceneProbereturns the latest one.captureTopDown(renderer, scene, {centre, size_m, pixels})andwindow.__gbbTopDown(opts)return a PNG data URL of an orthographic view from above (-Z at the top), or null in a worker.
People: humanoid.js
A procedural person instead of a sliding capsule: one skinned mesh (about 2.7k triangles, 22 bones with Mixamo-style names) generated in code and animated without clips. Appearance is parameters only.
import { createHumanoid, gaitFor } from '../lib/render-kit/humanoid.js';
const person = createHumanoid({ height: 1.75, build: 0.5, // build: 0 slim .. 1 heavy
colors: { skin: 0xc58c66, hair: 0x2a1d15, top: 0x4b6b8c, bottom: 0x2f3542, shoes: 0x1d1d20 },
hair: 'short' /* 'none' | 'long' */, sleeves: 'long' /* 'short' */, seed: 3 });
scene.add(person.root); // feet at y = 0, faces -z; look.adopt(scene) treats it like any mesh
// each frame: move the root yourself, say what it is doing, then update
person.root.rotation.y += turn * dt; person.root.translateZ(-speed * dt);
person.set({ speed, turn, action: 'none', aimPitch: 0, lookAt: null });
person.update(dt);
- Gait rule.
speedis the root's real ground speed in m/s along its facing (0 idle, 1.4 walk, 3.5 jog, 6 run, negative backs up);turnis the rate ofroot.rotation.yin rad/s. The feet are planted by IK for exactly that motion: move the root at the speed you report or they slide.gaitFor(speed, height)returns{ strideLength, stepLength, cadence, duty }(cadence in steps/s,speed = stepLength * cadence);person.footDown.left/rightandperson.phasetime footsteps. - Actions blend in and out:
talk,wave,point(alongaimPitch, or atlookAt),aim(two hands,aimPitchup positive),crouch(can walk),sit(hips over the root, seat 0.26 x height orseat: metres),hit(a flinch, once per change to'hit'),fall(onto its back behind the root; any other action gets up).lookAtis a worldVector3for the head, or null. - Deterministic and cheap. The pose depends only on the
set()/update(dt)calls andseed. People with equal height/build/hair/sleeves share one geometry; 20 cost about 1 ms a frame.person.dispose()when done;person.bones.Headetc. andperson.meshare there to attach to.