// Builds the three.js scene from the city and draws a game state. The same state always draws // the same frame: everything that moves takes its place from the game, never from the clock. // // Two qualities. "high" (laptops): cascaded shadows across the whole city, a multisampled HDR // buffer, ground-truth ambient occlusion, bloom and a reflective bay. "low" (phones): one // shadow map around Claudia and the same look without the extra passes. import * as THREE from "three"; import { CSM } from "three/addons/csm/CSM.js"; import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js"; import { GTAOPass } from "three/addons/postprocessing/GTAOPass.js"; import { OutputPass } from "three/addons/postprocessing/OutputPass.js"; import { RenderPass } from "three/addons/postprocessing/RenderPass.js"; import { UnrealBloomPass } from "three/addons/postprocessing/UnrealBloomPass.js"; import { rng } from "./rng.js"; import { buildBuildings } from "./scene/buildings.js"; import { buildClaudia } from "./scene/claudia.js"; import { buildDistance } from "./scene/distance.js"; import { buildItems } from "./scene/items.js"; import { buildLandmarks } from "./scene/landmarks.js"; import { buildProps } from "./scene/props.js"; import { SUN_DIR, buildSky } from "./scene/sky.js"; import { buildStreets } from "./scene/streets.js"; import { buildVehicles } from "./scene/vehicles.js"; import { unify } from "./scene/unify.js"; import { buildWater } from "./scene/water.js"; // The grade: ACES, then warm highlights and cool shadows, a little more color. Golden hour. THREE.ShaderChunk.tonemapping_pars_fragment = THREE.ShaderChunk.tonemapping_pars_fragment.replace( "vec3 CustomToneMapping( vec3 color ) { return color; }", /* glsl */ `vec3 CustomToneMapping( vec3 color ) { vec3 c = ACESFilmicToneMapping( color * vec3( 1.04, 1.0, 0.95 ) ); float l = dot( c, vec3( 0.2126, 0.7152, 0.0722 ) ); c = mix( c * vec3( 0.95, 1.0, 1.07 ), c * vec3( 1.06, 1.0, 0.9 ), smoothstep( 0.12, 0.8, l ) ); c = mix( vec3( l ), c, 1.14 ); return clamp( c, 0.0, 1.0 ); }`, ); // The haze: distance fog that glows warm toward the sun and stays cool away from it. const sunLiteral = `vec3(${SUN_DIR.x.toFixed(5)}, ${SUN_DIR.y.toFixed(5)}, ${SUN_DIR.z.toFixed(5)})`; THREE.ShaderChunk.fog_fragment = /* glsl */ ` #ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif vec3 hazeColor = fogColor; #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) vec3 hazeView = normalize( -vViewPosition ); vec3 hazeSun = normalize( ( viewMatrix * vec4( ${sunLiteral}, 0.0 ) ).xyz ); float toSun = max( dot( hazeView, hazeSun ), 0.0 ); hazeColor = mix( fogColor, vec3( 1.0, 0.8, 0.58 ), pow( toSun, 4.0 ) * 0.75 ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, hazeColor, fogFactor ); #endif `; /** Construct something that draws on Math.random with a seeded generator instead, so the * noise it bakes is the same on every load (screenshots must not change between runs). */ function seeded(seed, make) { const saved = Math.random; Math.random = rng(seed); try { return make(); } finally { Math.random = saved; } } export function createView(canvas, { quality = "high" } = {}) { const high = quality === "high"; const renderer = new THREE.WebGLRenderer({ canvas, antialias: !high, preserveDrawingBuffer: true, powerPreference: "high-performance" }); renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, high ? 1.6 : 1.5)); renderer.toneMapping = THREE.CustomToneMapping; renderer.toneMappingExposure = 1.0; renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFShadowMap; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(55, 1, 0.3, 32000); const sky = buildSky(scene, renderer, { shadowSize: 1024, castShadow: !high }); const water = buildWater(scene, sky.env, { reflect: high }); buildStreets(scene); buildBuildings(scene); buildLandmarks(scene); const props = buildProps(scene); const distance = buildDistance(scene); const claudia = buildClaudia(scene); const items = buildItems(scene); // fewer shader programs for the same picture (see unify.js) unify(scene); let vehicles = null; let traffic = null; // Cascaded shadows: four maps from Claudia's feet out to a kilometer, so towers throw their // long morning shadows down every street, not just around her. let csm = null; const prepared = new WeakSet(); const prepare = (root) => { if (!csm) return; root.traverse((o) => { if (!o.material) return; for (const m of [].concat(o.material)) { if (prepared.has(m) || !(m.isMeshStandardMaterial || m.isMeshLambertMaterial || m.isMeshPhongMaterial)) continue; prepared.add(m); const before = m.onBeforeCompile; csm.setupMaterial(m); const hook = m.onBeforeCompile; m.onBeforeCompile = function (shader, r) { hook.call(this, shader, r); before.call(this, shader, r); }; m.needsUpdate = true; } }); }; if (high) { csm = new CSM({ camera, parent: scene, cascades: 4, maxFar: 1400, mode: "practical", shadowMapSize: 2048, shadowBias: -0.00025, lightDirection: SUN_DIR.clone().negate(), lightIntensity: sky.sun.intensity, lightNear: 1, lightFar: 4000, lightMargin: 500, }); csm.fade = true; for (const l of csm.lights) { l.color.copy(sky.sun.color); l.shadow.normalBias = 0.35; } sky.sun.intensity = 0; prepare(scene); } // Post: ambient occlusion grounds everything, a soft bloom lets the sun and the bright bits // glow, and the grade and tone mapping happen last. let composer = null; let gtao = null; let bloom = null; if (high) { const target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4 }); composer = new EffectComposer(renderer, target); composer.addPass(new RenderPass(scene, camera)); gtao = seeded(20261130, () => new GTAOPass(scene, camera, 1, 1)); gtao.updateGtaoMaterial({ radius: 2.4, distanceExponent: 1.4, thickness: 3, scale: 1.15, samples: 12, distanceFallOff: 1 }); gtao.updatePdMaterial({ lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 5, radiusExponent: 1, rings: 2, samples: 10 }); gtao.blendIntensity = 0.85; // AO from opaque surfaces only: no sprites, no glass, no glow, no hair ribbons' backsides const hideMore = gtao._overrideVisibility.bind(gtao); gtao._overrideVisibility = function () { hideMore(); scene.traverse((o) => { if (!o.visible) return; const m = o.material; if (o.isSprite || o.userData.noAO || (m && !Array.isArray(m) && (m.transparent || m.isShaderMaterial))) { o.visible = false; this._visibilityCache.push(o); } }); }; // run it at half resolution: soft occlusion does not need every pixel const sizeGtao = gtao.setSize.bind(gtao); gtao.setSize = (w, h) => sizeGtao(Math.max(1, Math.round(w / 2)), Math.max(1, Math.round(h / 2))); composer.addPass(gtao); bloom = new UnrealBloomPass(new THREE.Vector2(1, 1), 0.32, 0.55, 0.9); composer.addPass(bloom); composer.addPass(new OutputPass()); } function resize() { const w = canvas.clientWidth || window.innerWidth; const h = canvas.clientHeight || window.innerHeight; renderer.setSize(w, h, false); composer?.setPixelRatio(renderer.getPixelRatio()); composer?.setSize(w, h); camera.aspect = w / h; camera.updateProjectionMatrix(); csm?.updateFrustums(); } return { renderer, scene, camera, resize, quality, render(game) { if (game.traffic !== traffic) { if (vehicles) vehicles.dispose?.(); traffic = game.traffic; vehicles = buildVehicles(scene, traffic); unify(scene); prepare(scene); } const c = game.cam; camera.position.set(c.x, c.y, c.z); camera.lookAt(c.lx, c.ly, c.lz); camera.rotateZ(c.rollNow ?? 0); if (Math.abs(camera.fov - c.fov) > 0.01) { camera.fov = c.fov; camera.updateProjectionMatrix(); csm?.updateFrustums(); } camera.updateMatrixWorld(); const focus = c.blend > 0.5 ? game.p : { x: c.lx, y: c.ly, z: c.lz }; sky.follow(focus.x, focus.y, focus.z); csm?.update(); water.update(game.time); distance.update(game.time); props.update(camera); vehicles.update(game.poses); claudia.update(game); items.update(game, camera); if (composer) composer.render(); else renderer.render(scene, camera); }, }; }