CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
|
Raw History Blame Contribute Delete
16.3 kB

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. Keep background: false when 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.Color scene background is tone-mapped by the postprocessing chain (medium and up) but not at low, 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; call followSun(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, or mode: '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.params is 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; pass space: 'object' for things that move. adopt() picks a type from mesh.userData.surface, else from words in the material or mesh name (road, concrete, brick, wood, glass, metal ...), else generic. 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 writes look.json and a reference/before/after sheet. Then replay again and read the scorecard's look. 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_deg 0 sits behind the subject looking the way it faces (90 = its right, 180 = in front); height_m is above the ground under the camera and the horizontal offset is solved so the 3D distance to the subject's box centre equals distance_m; without pitch_deg the camera looks at that centre; hfov_deg sets the vertical fov through camera.aspect. Models authored facing +Z need subjectForward: new THREE.Vector3(0, 0, 1).
  • rigAt(rig, t, {start}): keyframes hold unnamed fields; numbers interpolate linearly, angles along the shortest arc, subject_box per coordinate.
  • buildRoad(road): origin at the start of the centre line on the road surface, running to -Z. Width is lanes * 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 unless radius_m is given; roadFrameAt(road, s, offset) gives the position and heading s metres along it for placing vehicles. Meshes are named road.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_m is from the road's outer edge to the front face; spacing_m is centre to centre; towers vary +/-20 % in height, deterministically.
  • buildCabin(interior): origin at the cabin's centre in plan at floor level (seat cushions at userData.hip_y), -Z toward the windshield. camera_mounts use this frame; each becomes a child mount.<id> already aimed at its look_at, and userData.mounts lists them.
  • buildRooms(place): the floor plan of a contract rooms place as grey boxes to size: a group in the place frame with one child room.<id> per room (floor, ceiling, walls with every opening cut out, a lintel above doors, a sill below windows). userData.segments lists the solid wall lines; resolveWalls(rooms, position, radius) pushes a walker's {x, z} out of them after each step, and roomAt(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 passes getPlace: () => ({id, origin: [x, y, z], yaw_deg}) (the current place and where its frame sits in your world); the probe then reports camera.place: {id, x_m, z_m, yaw_deg} and the review checks it against the contract's route.
  • installSceneProbe(...) defines window.__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: call probe.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, whose window.__gbbSceneProbe returns the latest one.
  • captureTopDown(renderer, scene, {centre, size_m, pixels}) and window.__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. speed is 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); turn is the rate of root.rotation.y in 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/right and person.phase time footsteps.
  • Actions blend in and out: talk, wave, point (along aimPitch, or at lookAt), aim (two hands, aimPitch up positive), crouch (can walk), sit (hips over the root, seat 0.26 x height or seat: metres), hit (a flinch, once per change to 'hit'), fall (onto its back behind the root; any other action gets up). lookAt is a world Vector3 for the head, or null.
  • Deterministic and cheap. The pose depends only on the set()/update(dt) calls and seed. People with equal height/build/hair/sleeves share one geometry; 20 cost about 1 ms a frame. person.dispose() when done; person.bones.Head etc. and person.mesh are there to attach to.