# DriftEngine manual The manual of DriftEngine, as published at https://driftengine.dev/docs, one chapter after another, then the articles published at https://driftengine.dev/blog. --- # Introduction Getting started. https://driftengine.dev/docs/start/introduction What DriftEngine is, what ships in it, how its packages divide, and where to start reading this manual. DriftEngine is a 3D game engine written in strict TypeScript. It draws with WebGPU, and falls back to WebGL2 when a browser can't give it a usable WebGPU device. Your game code doesn't change between the two: you ask for a renderer, and the engine tells you which backend it got and why. A game built on it ships as a web page. The same build can also be packaged as a desktop app for Linux, Windows or macOS, or as an Android app, and it can run on a native window with no browser in the process at all. You write a game as a program. You create a renderer on a canvas, build or load meshes, step a simulation on a fixed clock and draw frames. There is an editor, with a scene tree, an inspector and a timeline you can scrub backwards, but nothing in the engine requires you to use it. ## What ships **Rendering.** A forward renderer with clustered lighting, cascaded sun shadows, point and spot lights with their own shadows, rectangular area lights, physically based materials, ambient occlusion, bloom, colour grading and motion blur. On WebGPU there is more: a GPU-driven path that culls instances and clusters on the device and draws them with one indirect call, DriftTR temporal reconstruction, which renders below output resolution and resolves back up, DriftRay traced indirect light, and DriftLight, which lets thousands of fixed lights reach a frame. **Worlds.** Heightfield terrain whose levels of detail meet without cracks, worlds larger than single precision can address, hierarchical detail for distant geometry, streaming that does its work in slices of a frame, Gaussian splats, and DriftTexture, where a texture is a small compiled program over a learned field instead of an image. **Simulation.** A deterministic physics engine of its own: rigid bodies, seven kinds of joint, a character controller, raycast vehicles, ragdolls, cloth and buoyancy. Skeletal animation with blend trees, state machines, two-bone IK and retargeting. Navigation meshes, an entity component system, and agents. **Content.** Models import from glTF, OBJ, FBX, USD, STL, 3MF and Blender files, and bake into the `.drft` container, which streams a coarse outline of a model while its geometry downloads. Audio has a mix tree, positional sources, reverb zones, and a synthesised stand-in for every sound you haven't recorded yet. **Interaction.** Keyboard, mouse, touch and gamepads behind one action map. Cameras, including a third-person rig that won't put its lens inside a wall. A 2D layer for sprites and interface, and WebXR. **Systems.** The simulation runs on a fixed step with seeded randomness, so a run can be replayed exactly, and the networking is built on that: lockstep, and an authoritative host with prediction and rollback. Video capture, saves, and DriftScript, a scripting language whose modules reload while the game keeps running. **Shipping.** Desktop and Android apps from one manifest, Steam cloud saves and achievements, and a native host. ## Packages Install what you use and nothing else. `@driftengine/core` is the runtime every game needs: the loop, the renderer, input, cameras, the scene graph and geometry. It also re-exports the whole of `@driftengine/physics`. Every other package is optional and takes core as a peer dependency, so one you never install costs you nothing. ## The shape of the API The engine takes positions, colours, sizes and time, and it doesn't know what your game is. You won't find a player class to subclass or a level format to adopt: the rules, the world and the HUD are yours. That makes the first program a little longer than in an engine that decides those things for you, and it means you can replace any one piece when you outgrow it. Three rules run through every page of this manual, and the examples follow all of them. 1. **Import only from a package's top level.** `@driftengine/core` is the public surface. Anything you can't import from there is internal and can change without notice. 2. **Don't allocate in the frame.** Build meshes, nodes and buffers once, and rewrite them in place. 3. **Interpolate on `alpha`.** The simulation advances in fixed steps and the display doesn't, so anything that moves is drawn between its last two states. ## Where to start Read [Installation](https://driftengine.dev/docs/start/installation), then [Hello world](https://driftengine.dev/docs/start/hello-world), which puts a lit, turning cube on the screen in about a hundred lines. [The loop](https://driftengine.dev/docs/start/the-loop) and [Moving things](https://driftengine.dev/docs/start/moving-things) explain the two ideas every game here is built on, and [Your first game](https://driftengine.dev/docs/start/first-game) puts them together into a complete game you can play in this page. --- # Installation Getting started. https://driftengine.dev/docs/start/installation Add DriftEngine to a project, set up the page, TypeScript and DriftScript, pick a backend for testing, and know what the licence asks of you. DriftEngine is published to npm as separate packages under the `@driftengine` scope. Every game needs `@driftengine/core`; the rest you add when you reach for them. ```sh npm install @driftengine/core ``` ## What it needs - **A browser with WebGL2**, which is every current desktop and mobile browser. The engine uses WebGPU where the browser offers a device that can draw, and WebGL2 everywhere else. - **Node 22.12 or newer** for your toolchain. Nothing in the engine runs in Node at play time; Node is what builds and serves your game. - **An ES module bundler.** The examples in this manual use Vite, and webpack 5 and Parcel work the same way. The engine starts its workers with `new Worker(new URL('./worker.ts', import.meta.url))`, which those three bundle without configuration. ## A new project The quickest start is a project made for the engine, ready to run: ```sh npm create @driftengine@latest my-game cd my-game npm install npm run dev ``` It is a Vite and TypeScript project with the engine, DriftScript and the page below already set up, a test runner, and a command that looks at the game on both backends. It is also set up for a coding agent to work in, which [Working with a coding agent](https://driftengine.dev/docs/start/with-an-agent) describes. To add the engine to a project of your own instead, start from Vite's TypeScript template: ```sh npm create vite@latest my-game -- --template vanilla-ts cd my-game npm install @driftengine/core npm run dev ``` Replace the template's `index.html` with a page that holds one canvas. The engine reads the canvas's CSS size and sizes its drawing buffer to match, so the canvas only needs to be laid out. ```html My game ``` Then write `src/main.ts`. [Hello world](https://driftengine.dev/docs/start/hello-world) is the whole of a first one. ## TypeScript The template's settings are fine. What the engine relies on is a target that allows top-level `await`, since creating a renderer is asynchronous, and the DOM library: ```json { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "lib": ["ES2022", "DOM", "DOM.Iterable"], "strict": true, "noEmit": true } } ``` The packages ship compiled JavaScript with declaration files, so nothing else is needed to get types. ## DriftScript A game's rules are written in DriftScript, the engine's scripting language, and a project needs two packages beside the engine for it: ```sh npm install @driftengine/script driftscript ``` `driftscript` is the language: its compiler, its runtime and the Vite plugin. `@driftengine/script` is what connects it to the engine. The plugin goes in the Vite config: ```ts import { fileURLToPath } from 'node:url'; import { driftScript } from 'driftscript/vite'; import { defineConfig } from 'vite'; export default defineConfig(({ command }) => ({ plugins: [ driftScript({ /* The engine's capabilities, as data: every `drift/*` function, its types and its effects. */ capabilities: fileURLToPath(import.meta.resolve('@driftengine/script/capabilities.json')), /* The engine modules a script in this game may import. Add one here when a script needs it; an import of a module not named is refused when the file compiles, naming the module. */ manifest: { name: 'my-game', provides: ['drift/random', 'drift/scene', 'drift/input'] }, /* `vite build` compiles for shipping: the editor's metadata stays out of the bundle. */ mode: command === 'build' ? 'production' : 'development', }), ], build: { target: 'es2022', /* Just above the engine's WebGPU renderer, one module of about 2,100 kB minified that loads only where WebGPU does. Vite warns past 500 kB by default; anything larger than the renderer still warns. */ chunkSizeWarningLimit: 2200, }, })); ``` `capabilities` is the engine's description of every function a script can call, as data, which is what the compiler checks a call and infers its effects against. `manifest.provides` names the engine modules this game's scripts may import; a script that imports one not named is refused when it compiles, and the error names the module. [What a script can reach](https://driftengine.dev/docs/scripting/reach) lists them all. TypeScript resolves a `.drs` import through one declaration file anywhere in the project: ```ts /// ``` The editor extension for VS Code, `DriftTech.driftscript-vscode` on the marketplace, highlights `.drs` files and reports the build's own errors as you type. [Setting up scripts](https://driftengine.dev/docs/scripting/setting-up) covers loading, binding and hot reload. ## Choosing a backend while you test `createRenderer` picks the backend. You can force one from the address bar, which is the quickest way to check that a game looks the same on both: ```text http://localhost:5173/?backend=webgl2 http://localhost:5173/?backend=webgpu ``` `createRenderer` returns which backend it built and a `reason` in words. Show both somewhere while you develop: the first question about any picture is what drew it. ## Headers None are required. A plain static host serves a DriftEngine game. One feature asks for more: solving physics islands on worker threads needs `SharedArrayBuffer`, which browsers only offer to a cross-origin isolated page. If you turn that on, serve the page with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`. Without them physics still runs, on the main thread, and the world says why it didn't start the workers. ## Working against a checkout of the engine If you're changing the engine itself, or tracking its `main` branch, depend on it by path and npm will link it: ```json { "dependencies": { "@driftengine/core": "file:../driftengine/packages/core" } } ``` Add the `drift-source` condition to your bundler so it reads the engine's TypeScript, and an edit to the engine is live in your game with no build in between. In Vite, spread the defaults back in, because setting `resolve.conditions` replaces them: ```js import { defaultClientConditions, defineConfig } from 'vite'; export default defineConfig({ resolve: { conditions: ['drift-source', ...defaultClientConditions] }, }); ``` Reading the source also needs `"allowImportingTsExtensions": true` in the tsconfig that checks your project, because the engine's own imports name their `.ts` files. ## The engine badge `createRenderer` shows a small DriftEngine badge over the page while the game boots, and holds it for three seconds after the first frame reaches the screen. The fixed-step loop is held for that time too, so an intro or a music cue doesn't play behind it. **Keeping it is a request, and the licence doesn't require it.** Pass `{ splash: false }` as the third argument to `createRenderer` to turn it off, which is the right choice for anything that isn't a game booting: a canvas that is one section of a web page, an embed, a tool, a product page, a benchmark. `?splash=0` turns it off from the address bar without a code change. ## Licence Apache-2.0. You can use the engine for anything, including commercial games, and modify it. What the licence asks is that you reproduce the contents of the engine's `NOTICE` file somewhere a person can read it: in your source, your documentation, or a screen the game shows, such as a credits or licences page. Every package's entry point already carries that notice in a comment minifiers keep, so a bundled game includes it without any work on your part. Only one dependency anywhere in the engine is copyleft, and it reaches only the native host, which ships it as a separate, replaceable file. [Shipping to the web](https://driftengine.dev/docs/start/shipping-to-the-web) covers what goes into a web build. --- # Working with a coding agent Getting started. https://driftengine.dev/docs/start/with-an-agent Start a project a coding agent can build on, give the agent the engine's skill, and check every change by looking at the game on both backends. DriftEngine is built to be written by a coding agent as well as by a person. Each package has one typed entry point, and its exports carry their documentation with them as comments. A game's rules run in Node with no GPU, so a test of a rule is a test of the game. And a project can look at its own game on both backends and say in words what it saw. This page sets a project up so that an agent, such as Claude Code, Codex or Cursor, works with all three. ## Start a project ```sh npm create @driftengine@latest my-game cd my-game npm install npm run dev ``` That starts from a lit cube turning at a rate a DriftScript rule decides. For a complete 3D game to build on, with physics, a character, sound, shadows and a HUD, name the other template: ```sh npm create @driftengine@latest my-game -- --template first-game ``` The command asks nothing and installs nothing, so an agent can run it unattended. It writes a Vite and TypeScript project, its program under `src/`, and three things for an agent: ```text my-game/ AGENTS.md how this project works, and when a change is done .agents/skills/driftengine/ the engine's skill, where Codex, Cursor and others look .claude/skills/driftengine/ the same skill, where Claude Code looks scripts/look.mjs npm run look: the game photographed on both backends ``` `AGENTS.md` is the file most coding agents read on their own when they open a project, Claude Code among them unless the project gives it an instructions file of its own. It lists the commands, the rules the compiler cannot check, and what done means here. The skill is longer and is read when the work needs it: the shape of a program, the traps that look like problems in the engine, and where every page of this manual and every example is, at the version the project installed. ## Check every change ```sh npm run check ``` `check` runs `typecheck`, then `test`, which runs the project's tests in Node, then `look`. `look` starts the game, opens it once with `?backend=webgpu` and once with `?backend=webgl2` in Chrome, or in Edge where Chrome is not installed, on the machine's own GPU, and writes what it saw: ```text .driftengine/look/webgpu.png what a player sees on WebGPU .driftengine/look/webgl2.png and on WebGL2 .driftengine/look/look.json the report, with every console line ``` It fails on a console error or warning, on a canvas of one flat colour, and when the backend it asked for is not the one that drew. It exits with 2 when it cannot look at all: when it finds no browser, which `CHROME_PATH` answers, or no hardware GPU, which it refuses rather than trust a software rasteriser's picture. `npm run look -- --headed` opens a real browser window, which reaches the GPU on a machine where a headless browser does not. A report can say a frame is not empty. Only looking says it is the right frame, so the project's `AGENTS.md` tells the agent to open both pictures before it says a change works. Most agents can read an image. `look` runs on Windows, macOS and Linux. It has been measured on Linux; on Windows and macOS it uses each system's own graphics path through ANGLE, Direct3D 11 and Metal, and reports the GPU it found on its second line, which is the line to read the first time. ## Add the skill to a project you already have From the project's directory: ```sh npm create @driftengine@latest . -- --skill ``` That writes the skill into both folders and replaces an older copy of it, touching nothing else. Run it again after upgrading the engine, so the skill describes the version installed. The skill is also in the engine's repository, in `skills/driftengine/`, where tools that install skills from a repository find it: ```sh npx skills add drftrun/driftengine ``` That copy follows the repository's main branch rather than the version a project installed. To make the skill available in every project, copy the `driftengine` folder into `~/.claude/skills/` for Claude Code, or `~/.agents/skills/` for Codex and Cursor. ## What the agent can read - **The installed types.** `node_modules/@driftengine/core/dist/index.d.ts` names every export of the version the project runs and the module each comes from, whose own declarations document it, and so does each other package's. DriftScript's own reference is `node_modules/driftscript/docs/LANGUAGE.md`. - **This manual, at that version.** Each page is Markdown in the engine's repository, at the tag of every release, and the skill lists every page's address. - **The examples**, one capability each, at the same tag. [Hello world](https://driftengine.dev/docs/start/hello-world) and [Your first game](https://driftengine.dev/docs/start/first-game) are the two templates, explained. - **The whole manual as one file**, for an agent that searches rather than browses: `https://driftengine.dev/llms-full.txt`, with an index of every page at `https://driftengine.dev/llms.txt`. ## What still needs a person `look` sees the first seconds after the game starts. It does not play the game, so a level reached by playing, a menu behind a key press, and how the controls feel are not in its pictures. Nor is how fast the game runs on a phone, which only a phone can say: [Shipping to the web](https://driftengine.dev/docs/start/shipping-to-the-web) covers testing on one. --- # Hello world Getting started. https://driftengine.dev/docs/start/hello-world A complete first program. A renderer on a canvas, light, two meshes, a camera, a loop that turns a cube on a fixed clock, and a rule in DriftScript. The smallest DriftEngine program that is still a game draws a lit cube on a ground plane and turns it on a fixed clock. It's about a hundred lines, and every later page builds on the same pieces: a renderer, an environment, meshes, a scene, a loop, and a rule in DriftScript that the loop asks how fast to turn. (This chapter runs the `starter` example at https://driftengine.dev/docs/start/hello-world.) The program is `examples/starter/main.ts` and one rule beside it in `examples/starter/spin.drs`, and it is the folder to copy when you begin a project. This page walks through it from the top. ## The imports The engine comes from its packages' top level: `@driftengine/core` for everything drawn and simulated, `@driftengine/script` for binding scripts to it. `loadModule` and `patchModule` are DriftScript's own, and the `.drs` file is imported like any other module. ```ts import { Camera, MeshBuilder, SceneNode, createEnvironment, createRenderer, srgbColor, startLoop, } from '@driftengine/core'; import { bindModule } from '@driftengine/script'; import { loadModule, patchModule } from 'driftscript'; import * as spinScript from './spin.drs'; ``` ## A renderer on the canvas ```ts const canvas = document.querySelector('#stage'); if (canvas === null) throw new Error('the page must carry '); /* * Asynchronous because it has to be: asking for a WebGPU adapter returns a promise, and there * is no synchronous way to learn whether a usable device exists. The fall back to WebGL2 is * automatic and silent, so `reason` is the only thing that says why. Print it: the first * question asked about any picture is what drew it. */ const { renderer, backend, reason } = await createRenderer(canvas, { maxDevicePixelRatio: 1.75, }); const readout = document.querySelector('#backend'); if (readout !== null) readout.textContent = `${backend}: ${reason}`; renderer.resize(); addEventListener('resize', () => renderer.resize()); ``` `createRenderer` is asynchronous because asking the browser for a WebGPU adapter is. It tries WebGPU first and falls back to WebGL2 on its own, so a game never branches on the backend. What it hands back says what happened: `renderer` is the object you draw with, `backend` is `'webgpu'` or `'webgl2'`, and `reason` explains the choice in words. The second argument is the render quality profile. `maxDevicePixelRatio` caps how many pixels the drawing buffer gets per CSS pixel, which is the single biggest cost on a phone with a dense screen. Quality options are decided when the renderer is built, because most of them size GPU memory, and changing one means building a new renderer. `renderer.resize()` reads the canvas's CSS size and sets the drawing buffer to match. Call it once at the start and again whenever the window changes size. ## Light and air ```ts /** * Light, air and ground bounce. Chosen once, because these are allocation-sized decisions. * * Every colour here and below was picked by eye, so it goes through `srgbColor`: the renderer * lights in linear values and encodes them for the screen at the end, and a colour typed as it * looks would come out too light. The clear colour in the loop is one of them. */ const CLEAR = srgbColor(0.05, 0.06, 0.09); const ENV = createEnvironment({ directionalDir: [0.4, 0.7, 0.35], directionalColor: srgbColor(1, 0.96, 0.88), ambient: srgbColor(0.2, 0.22, 0.28), ambientGround: srgbColor(0.08, 0.08, 0.1), emissiveGain: 0, nightFactor: 0, fogColor: srgbColor(0.16, 0.18, 0.24), fogDensity: 0.004, fogHeightFalloff: 0.03, fogBaseY: 0, }); ``` An `Environment` is the lighting and atmosphere for a frame: a directional light that points **toward** the sun, an ambient fill from above and a separate one from the ground, and fog that thickens with distance and thins with height. `createEnvironment` fills every field you leave out with a value that means nothing special, so you only write the ones you care about. `nightFactor` is worth knowing about early, because its name misleads. It is the switch for emissive light: at 0 nothing in the world glows, however bright its emissive value. It has nothing to do with the clock. ## Meshes ```ts /* * Colour is vertex data here, which is what lets a whole world be flat-shaded draw calls. * `addBox` takes a centre and *half* extents, so this ground is 24 units across and the cube * is two units on a side. */ const shapes = new MeshBuilder(); shapes.addBox([0, 1, 0], [1, 1, 1], srgbColor(0.85, 0.45, 0.25)); const cube = renderer.createMesh(shapes.build()); const slab = new MeshBuilder(); slab.addBox([0, -0.25, 0], [12, 0.25, 12], srgbColor(0.3, 0.32, 0.36)); const ground = renderer.createMesh(slab.build()); ``` A `MeshBuilder` collects shapes into one mesh. `addBox` takes a centre, **half** extents and a colour, so the ground here is 24 metres across. Colour is per vertex, which is why neither mesh needs a texture. The builder also has spheres, capsules, cylinders, tubes, quads and more, and every shape you add to one builder becomes part of the same mesh, drawn in one call. `renderer.createMesh` uploads the result to the GPU and returns a handle. Do this once, at load, never in the frame. ## The scene ```ts const spinner = new SceneNode(); spinner.setPosition(0, 1, 0); const stillness = new SceneNode(); stillness.updateWorld(); const camera = new Camera(); camera.position[0] = 6; camera.position[1] = 4.5; camera.position[2] = 8; camera.lookAt(0, 1, 0); ``` A `SceneNode` holds a position, a rotation and a scale, and computes a `worldMatrix` from them when you call `updateWorld()`. Nodes can be parented, and a child's world matrix includes its parent's. The ground never moves, so its node is updated once. The `Camera` is a perspective camera. Set its `position` and call `lookAt`, or set `yaw` and `pitch` directly: yaw 0 looks toward negative Z, and positive yaw turns right. ## A rule in DriftScript ```drs // Radians a second: a steady turn that quickens and eases every few seconds. fn spinRate(time: f32) -> f32 { return 0.8 + 0.4 * math.sin(time * 0.5) } ``` DriftScript is the engine's scripting language, and a game's rules belong in it: the numbers and decisions you tune by watching the game run. This one says how fast the cube turns, and it can answer only that. It cannot reach the cube, the renderer or the page; the page asks it, and acts on the answer. ```ts /* * How fast the cube turns is a rule, and rules live in DriftScript: `spin.drs`. The bundler compiles * the file, `loadModule` makes a module of it, and `bindModule` gives it the engine capabilities it * imports. Saving the file while the page is open replaces its function in place. */ const spinModule = loadModule(spinScript as Record); const bound = bindModule(spinModule, {}); if (!bound.bound) throw new Error(bound.reason); const rules = spinModule.exports as unknown as { spinRate(time: number): number }; if (import.meta.hot) { import.meta.hot.accept('./spin.drs', (next) => { if (next !== undefined) patchModule(spinModule, next as Record); }); } ``` The bundler compiles `spin.drs` when the page imports it. `loadModule` turns the result into a module, `bindModule` hands it whatever engine capabilities it imports (here none, since `std/math` is the language's own), and the rule is then an ordinary function. The `import.meta.hot` block is what makes a script worth having: save `spin.drs` with the page open, and the cube changes speed in the same frame, with nothing reloaded and nothing reset. To build this outside the engine's repository, a project needs the DriftScript plugin in its Vite config, which [Installation](https://driftengine.dev/docs/start/installation#driftscript) shows. [DriftScript in a game](https://driftengine.dev/docs/scripting/driftscript) is the section on what goes in a script and what stays in TypeScript. ## The loop ```ts /* * Two angles, because that is what `alpha` is for. The simulation advances in fixed steps and * the display does not, so a frame almost never lands on a step boundary: drawing `spin` * directly judders at any refresh rate that is not a multiple of the step. Interpolating * between the last two states is the whole reason the loop hands `alpha` over. */ let spin = 0; let previousSpin = 0; let time = 0; startLoop({ simulate(dt) { previousSpin = spin; time += dt; spin += dt * rules.spinRate(time); }, render(alpha) { spinner.setRotationAxisAngle(0, 1, 0, previousSpin + (spin - previousSpin) * alpha); spinner.updateWorld(); camera.updateMatrices(canvas.height > 0 ? canvas.width / canvas.height : 1); renderer.beginFrame(CLEAR); renderer.bindMeshPass(camera, ENV); renderer.drawMesh(ground, stillness.worldMatrix); renderer.drawMesh(cube, spinner.worldMatrix); renderer.endFrame(); }, }); ``` `startLoop` calls your `simulate` at a fixed 60 steps a second, however fast the display refreshes, and calls `render` once per displayed frame. Each step adds the script's rate, at the time the simulation has reached, to the angle. `render` receives `alpha`, how far the display has got between the last simulated step and the next, and the cube's angle is drawn at exactly that point between its previous and current value. [The loop](https://driftengine.dev/docs/start/the-loop) explains why this is the whole difference between smooth motion and judder. The simplest frame is four calls: `beginFrame` with a clear colour, `bindMeshPass` with the camera and the environment, any number of `drawMesh` calls with a mesh and a world matrix, and `endFrame`. ## Where to go from here You have a renderer, light, meshes, a camera, a loop and a script, which is everything a game is made of. Next, [The loop](https://driftengine.dev/docs/start/the-loop) covers simulation, pause and the step counter, and [Moving things](https://driftengine.dev/docs/start/moving-things) covers input. --- # The loop Getting started. https://driftengine.dev/docs/start/the-loop A fixed simulation step, rendering between steps with alpha, pausing without freezing the screen, and the tick count replays and networking key on. Every DriftEngine game runs on `startLoop`. It is the fixed timestep with render interpolation that game programmers usually learn from Glenn Fiedler's "Fix Your Timestep!": the simulation advances in steps of exactly the same length, however fast or unevenly the display refreshes, and each displayed frame is drawn between the last two simulated states. ```ts /* * Two angles, because that is what `alpha` is for. The simulation advances in fixed steps and * the display does not, so a frame almost never lands on a step boundary: drawing `spin` * directly judders at any refresh rate that is not a multiple of the step. Interpolating * between the last two states is the whole reason the loop hands `alpha` over. */ let spin = 0; let previousSpin = 0; let time = 0; startLoop({ simulate(dt) { previousSpin = spin; time += dt; spin += dt * rules.spinRate(time); }, render(alpha) { spinner.setRotationAxisAngle(0, 1, 0, previousSpin + (spin - previousSpin) * alpha); spinner.updateWorld(); camera.updateMatrices(canvas.height > 0 ? canvas.width / canvas.height : 1); renderer.beginFrame(CLEAR); renderer.bindMeshPass(camera, ENV); renderer.drawMesh(ground, stillness.worldMatrix); renderer.drawMesh(cube, spinner.worldMatrix); renderer.endFrame(); }, }); ``` ## Two callbacks, two clocks `simulate(dt, tick)` is where the game changes. `dt` is always the fixed step, a sixtieth of a second unless you pass another `fixedDt`, so a jump reaches the same height and a ball lands in the same place on a 60 Hz phone and a 240 Hz monitor. A slow frame runs `simulate` two or three times to catch up; a fast one may run it not at all. `render(alpha, frameDt, wallDt)` is where the game is drawn. It runs once per animation frame and must not change the simulation. `alpha` is between 0 and 1: how far real time has got from the last step toward the next. That is why a moving thing keeps two copies of its state. Draw the current one and motion judders, because a frame almost never lands on a step boundary. Draw between the previous and the current at `alpha` and it's smooth at any refresh rate. The first game keeps its player's previous position for exactly this: ```ts const player = new CharacterController({ maxSpeed: 7, jumpSpeed: 7, pushStrength: 2 }); const START: Vec3 = [0, 1.2, 7]; const playerMesh = renderer.createMesh( new MeshBuilder() .addCapsule([0, 0, 0], player.radius, player.halfHeight, srgbColor(0.92, 0.88, 0.82)) .build(), ); /** Where the player was before the last step, for the same reason the crates keep one. */ const playerBefore = { x: 0, y: 0, z: 0 }; ``` and copies the current position into it at the start of each step, before moving. ## Animating what isn't simulated `frameDt` is the time since the last drawn frame, clamped by `maxFrameTime` (a quarter of a second by default) so that a stall, a debugger stop or a background tab doesn't come back as one enormous jump. Use it for things that only exist on screen: a camera easing toward its target, a light flickering, an orb bobbing. The first game's camera follows the player this way: ```ts const camera = new Camera(); camera.fovYDeg = 55; const eye = { x: START[0], y: START[1] + 6, z: START[2] + 9 }; /** Ease toward a spot behind and above the player. Presentation only, so it runs on frame time. */ function follow(x: number, y: number, z: number, frameDt: number): void { eye.x = damp(eye.x, x, 5, frameDt); eye.y = damp(eye.y, y + 6, 5, frameDt); eye.z = damp(eye.z, z + 9, 5, frameDt); camera.position[0] = eye.x; camera.position[1] = eye.y; camera.position[2] = eye.z; camera.lookAt(x, y + 0.6, z); camera.updateMatrices(renderer.cssHeight > 0 ? renderer.cssWidth / renderer.cssHeight : 1); } ``` `damp` is an exponential approach that gives the same motion at any frame rate, which a fixed fraction per frame does not. `wallDt` is the same gap with no clamp. It's there for diagnostics, to tell a slow device from a browser that paused the page. Don't animate with it. ## Pausing `shouldSimulate` is asked once per frame. While it returns false, `simulate` isn't called and the time that passes is discarded, but `render` still runs, so the world stays on screen behind a pause menu instead of freezing on whatever frame was last drawn. ```ts newRound(); startLoop({ simulate, render, shouldSimulate: () => !paused }); ``` Because `simulate` doesn't run while paused, the key that unpauses has to be read in `render`: ```ts // Read here, not in simulate: while paused, simulate is not called at all. if (actions.consumePress('pause')) paused = !paused; ``` `shouldRender` is the matching question for drawing. Video capture uses it to draw exactly as many frames as the clip needs; time that wasn't drawn is added to the next frame's `frameDt`. ## Ticks `tick` counts fixed steps from `startTick`, which is 0 unless you say otherwise. It is the identity that replays and networking address everything by: an input belongs to a tick, a snapshot is of a tick, and two machines agree about the world when they agree about a tick. A player joining a session in progress starts their loop at the host's tick. ## Keeping a run repeatable A simulation that only reads its own state, the input for the step and a seeded random generator produces the same result every time it is run from the same start. That's what makes replays, rollback networking and the editor's backwards scrubbing possible, so it's worth keeping from the first line. - Use a seeded generator such as `mulberry32(seed)` inside `simulate`, never `Math.random()`. - Never read `Date.now()` or `performance.now()` inside `simulate`. Time is the tick count. - Read input at the boundary, once per step, and pass what you read into the step as data. The first game lays out its rounds from a seed this way, so the same seed gives the same rounds in the same order on every machine: ```ts /** Half the arena's width, in metres. */ const ARENA = 12; const ORB_COUNT = 8; /** The same seed lays out the same rounds, in the same order, on every machine. */ const SEED = 2026; ``` ## Stopping `startLoop` returns a function that stops the loop. Call it when the screen that owns the loop goes away, before you start another one. --- # Moving things Getting started. https://driftengine.dev/docs/start/moving-things Read the keyboard, the mouse, a gamepad and a touch screen through one action map, and turn what you read into movement on the fixed step. Input in DriftEngine comes in three layers, and a game usually uses all three. - `InputSource` captures the devices: keys, the mouse with pointer lock, touches and gamepads. - `ActionMap` names what the player means, such as _move_ or _jump_, and binds keys and buttons to those names, so the rest of the game never asks which device was used. - `TouchControls` turns a touch screen into a thumb stick on one side and taps, holds and swipes on the other. The first game uses all three, and this page follows it. ## Capturing devices ```ts const input = new InputSource(canvas, ['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']); const actions = new ActionMap(input, { move: { stick: 'left', up: ['KeyW', 'ArrowUp'], down: ['KeyS', 'ArrowDown'], left: ['KeyA', 'ArrowLeft'], right: ['KeyD', 'ArrowRight'], }, jump: { keys: ['Space'], buttons: ['faceDown'] }, restart: { keys: ['KeyR', 'Enter'], buttons: ['start'] }, pause: { keys: ['KeyP', 'Escape'], buttons: ['select'] }, }); /** A thumb stick on the left of a touch screen, and a tap or hold on the right. */ const touch = new TouchControls(input); const move = { x: 0, y: 0 }; ``` `new InputSource(canvas, codes)` starts listening. The second argument lists keys whose browser default should be suppressed: without it, Space and the arrows scroll the page under your game. Keys are named by `KeyboardEvent.code`, the physical key, so `KeyW` is the same key on a QWERTY and an AZERTY keyboard. On its own, an `InputSource` answers questions directly: - `isDown('KeyW')` is whether a key is held now. - `keyPressed('Space')` is whether it went down since the last poll, and `consumeKeyPress` is the same question answered `true` for exactly one caller. - `pad(0)` is the first gamepad, or `null`, with named buttons such as `faceDown` and `start` in the standard layout, sticks, triggers, and rumble where the browser can drive the motors. - `consumeMouseDelta(out)` drains the mouse movement since you last asked, which is what a mouse look reads, and `requestPointerLock()` captures the pointer for it. The source polls gamepads and turns key presses into edges once per animation frame on its own. If you record replays, pass `{ autoPoll: false }` and call `poll()` yourself at the start of each step, so the sample belongs to the step. ## Naming what the player means An `ActionMap` takes the source and a table of actions. A **digital** action, such as `jump`, lists keys and gamepad buttons. An **analog** action, such as `move`, names a stick and the keys for each direction, so a keyboard player and a gamepad player steer the same way. - `down('jump')` is whether anything bound to the action is held. - `consumePress('restart')` is a press, claimed once. Use this for anything that should happen once per press: a slow frame can run `simulate` twice, and `pressed` would answer yes both times. - `vector('move', out)` fills `out` with a direction, the larger of the stick and the keys, never their sum, so holding a key while pushing the stick doesn't double the speed. Bindings can be changed at run time with `rebind`, and saved and loaded with any key/value store, so a controls screen is a list of actions and a button that waits for the next key. ## Touch screens `new TouchControls(input)` splits the screen in two. The left part is a stick that appears where the thumb lands; the right part reports a tap, a hold, a downward swipe and look movement. It reports signals, never verbs: `primaryHeld` doesn't mean jump until your game says so, which is also what makes it simple to record. Call `tick(performance.now())` once per frame, outside the simulation, so a hold resolves on time. ## Turning input into movement ```ts function simulate(dt: number): void { if (round.phase.tag !== 'Playing') { if (actions.consumePress('restart') || touch.consumePrimaryPress()) newRound(); return; } // Keys and the pad follow the stick convention, where up is negative. The touch stick reports // up as positive, so it is flipped here, once. actions.vector('move', move); if (touch.moveX !== 0 || touch.moveY !== 0) { move.x = touch.moveX; move.y = -touch.moveY; } playerBefore.x = player.x; playerBefore.y = player.y; playerBefore.z = player.z; player.move(world, dt, { moveX: move.x * player.maxSpeed, moveZ: move.y * player.maxSpeed, jump: actions.down('jump') || touch.primaryHeld, }); recordCrates(crateBefore); world.step(dt); recordCrates(crateAfter); for (let i = 0; i < orbs.length; i += 1) { const orb = orbs[i]; if (orb.taken) continue; const dx = orb.x - player.x; const dy = orb.y - player.y; const dz = orb.z - player.z; if (rules.reaches(dx, dy, dz)) { orb.taken = true; rules.gather(round); chime(); } } if (player.y < -10) player.teleport(START[0], START[1], START[2]); rules.tick(round, dt); } ``` The step reads the move vector, decides what it means, and hands it to the `CharacterController`, which slides the player's capsule along walls, steps up kerbs and handles jumping. The direction maps straight onto the world here because the camera sits behind the player looking toward negative Z, so stick-forward is negative Z. A camera that turns would rotate the vector by its yaw first. > [!NOTE] > The keyboard, the gamepad and `ActionMap.vector` report up as **negative** Y, which is the gamepad > specification's convention. `TouchControls` reports up as positive. The first game flips the touch > value once, where it reads it, and every line after that agrees. ## What the frame does with it The step moved the player and kept where it was before; the frame draws it between the two at `alpha`. That split, input sampled at the edge, applied in a fixed step, and drawn by interpolation, is the same for every moving thing in every example in this manual. Next is [Your first game](https://driftengine.dev/docs/start/first-game), which adds a level, physics, things to collect, sound, a timer and a HUD. --- # Your first game Getting started. https://driftengine.dev/docs/start/first-game A complete 3D game. An arena with physics, a character, crates to push, orbs to gather against the clock, sound, shadows, a HUD, and rules in DriftScript. This chapter builds a complete game: walk an arena, push crates out of the way, jump up a platform, and gather eight orbs before sixty seconds run out. It has physics, a character controller, shadows, a synthesised sound, a HUD, pause and restart, and it plays with a keyboard, a gamepad or a touch screen. (This chapter runs the `first-game` example at https://driftengine.dev/docs/start/first-game.) Move with WASD, the arrow keys, the left stick or a thumb on the left of a touch screen. Jump with Space, the bottom face button or a hold on the right of the screen. P pauses, and R starts a new round once one has ended. The program is two files. `examples/first-game/main.ts` holds everything that touches the engine: the renderer, the physics world, the player, input and sound. `examples/first-game/round.drs` holds the round's rules in DriftScript, the engine's scripting language: how long a round lasts, how close counts as reaching an orb, and when the round is won or lost. Each section here is one region of them, in the order the program runs. ## The rules ```ts /** Half the arena's width, in metres. */ const ARENA = 12; const ORB_COUNT = 8; /** The same seed lays out the same rounds, in the same order, on every machine. */ const SEED = 2026; ``` Constants first, so the shape of the game is one block. The seed matters more than it looks: everything random in the game draws from a generator made from it, which is what lets a round be replayed. The numbers a round is tuned by, its length and how close the player has to come to an orb, are not here; they are in the script, below, where changing them does not restart the game. ## A renderer with shadows ```ts const canvas = document.querySelector('#stage'); if (canvas === null) throw new Error('the page must carry '); const { renderer, backend } = await createRenderer(canvas, { maxDevicePixelRatio: 1.75, directionalShadows: true, }); const readout = document.querySelector('#backend'); if (readout !== null) readout.textContent = backend; renderer.resize(); addEventListener('resize', () => renderer.resize()); ``` The same call as [Hello world](https://driftengine.dev/docs/start/hello-world), with `directionalShadows` turned on. That option allocates the sun's shadow map; the game still has to draw into it each frame, which happens at the end of this chapter. ## Light that makes orbs glow ```ts /* * Colours picked by eye go through `srgbColor`, because the renderer works in linear light and * encodes for the screen at the end — the clear colour and the interface's included. The sky is the * clear colour and the fog fades to it. The sun is half again as bright as white: light adds in * linear values, and a sun of exactly white beside this ambient leaves a sunlit floor darker than * the colour picked for it. */ const SKY = srgbColor(0.56, 0.68, 0.84); const ENV = createEnvironment({ directionalDir: [0.35, 0.8, 0.45], directionalColor: scaleColor(srgbColor(1, 0.95, 0.86), 1.5), ambient: srgbColor(0.34, 0.38, 0.46), ambientGround: srgbColor(0.14, 0.12, 0.1), // The emissive master switch. At 0 nothing glows, whatever emissiveGain says. nightFactor: 1, emissiveGain: 1.6, fogColor: SKY, fogDensity: 0.007, fogHeightFalloff: 0.06, fogBaseY: 0, }); ``` Fog takes the sky's colour, so the far wall fades into the sky instead of into grey. `nightFactor` is 1 because it is the switch that lets emissive surfaces glow, and the orbs are emissive. ## The level ```ts const world = new PhysicsWorld({ substeps: 4 }); const level = new MeshBuilder(); const footprints: { x: number; z: number; hx: number; hz: number }[] = []; /** One box, in the picture and in the physics from the same numbers, so the two cannot disagree. */ function solid( x: number, y: number, z: number, hx: number, hy: number, hz: number, color: Vec3, ): void { level.addBox([x, y, z], [hx, hy, hz], color); world.addBody({ type: BODY_STATIC, shape: boxShape(hx, hy, hz), x, y, z, friction: 0.8 }); footprints.push({ x, z, hx, hz }); } const GRASS = srgbColor(0.4, 0.5, 0.36); const WALL = srgbColor(0.62, 0.6, 0.56); const STONE = srgbColor(0.5, 0.52, 0.58); solid(0, -0.5, 0, ARENA, 0.5, ARENA, GRASS); for (const side of [-1, 1]) { solid(side * (ARENA + 0.5), 0.75, 0, 0.5, 0.75, ARENA + 1, WALL); solid(0, 0.75, side * (ARENA + 0.5), ARENA, 0.75, 0.5, WALL); } // Two tiers, each low enough to jump onto, with an orb waiting on top. solid(-6, 0.4, -6, 2.6, 0.4, 2.6, STONE); solid(-6, 1.2, -6, 1.4, 0.4, 1.4, STONE); solid(6, 1.5, -5, 0.6, 1.5, 0.6, STONE); solid(5, 1.5, 6, 0.6, 1.5, 0.6, STONE); const levelMesh = renderer.createMesh(level.build()); const PLATFORM_TOP = 1.6; ``` Every solid thing in the level is one call to `solid`, which adds a box to the picture and the same box to the physics world. Keeping both in one function is the simplest way to make sure the walls you see are the walls you hit. `PhysicsWorld` is the engine's own rigid-body solver, and it is deterministic: the same inputs give the same result, which is what replays and rollback networking rely on. `BODY_STATIC` bodies never move. `boxShape` takes **half** extents, like `MeshBuilder.addBox`. `substeps` is a quality dial: more substeps resolve contacts more accurately for more time per step, and the behaviour stays the same. All the boxes go into one `MeshBuilder`, so the whole level is a single mesh and a single draw. ## Crates ```ts const CRATE = 0.5; const crateMesh = renderer.createMesh( new MeshBuilder().addBox([0, 0, 0], [CRATE, CRATE, CRATE], srgbColor(0.74, 0.52, 0.3)).build(), ); const crates: number[] = []; for (const [x, z] of [ [2, -1], [3.1, -1.2], [2.5, 0.1], [-3, 5], ]) { crates.push( world.addBody({ type: BODY_DYNAMIC, shape: boxShape(CRATE, CRATE, CRATE), x, y: CRATE, z, friction: 0.6, }), ); } /** Position and rotation per crate, before and after the last step, for drawing between them. */ const crateBefore = new Float32Array(crates.length * 7); const crateAfter = new Float32Array(crates.length * 7); function recordCrates(out: Float32Array): void { const b = world.bodies; for (let i = 0; i < crates.length; i += 1) { const body = crates[i]; const o = i * 7; out[o] = b.posX[body]; out[o + 1] = b.posY[body]; out[o + 2] = b.posZ[body]; out[o + 3] = b.rotX[body]; out[o + 4] = b.rotY[body]; out[o + 5] = b.rotZ[body]; out[o + 6] = b.rotW[body]; } } ``` Crates are `BODY_DYNAMIC`: gravity, contacts and friction move them. The world keeps body state in flat typed arrays, `posX`, `rotW` and so on, indexed by the number `addBody` returned, which is cheap to read every step. The game records every crate's position and rotation before and after each step. Like every moving thing, a crate is drawn between the two at `alpha`. ## The player ```ts const player = new CharacterController({ maxSpeed: 7, jumpSpeed: 7, pushStrength: 2 }); const START: Vec3 = [0, 1.2, 7]; const playerMesh = renderer.createMesh( new MeshBuilder() .addCapsule([0, 0, 0], player.radius, player.halfHeight, srgbColor(0.92, 0.88, 0.82)) .build(), ); /** Where the player was before the last step, for the same reason the crates keep one. */ const playerBefore = { x: 0, y: 0, z: 0 }; ``` `CharacterController` is a capsule moved by the controller, not by forces. It slides along walls, steps up anything lower than `stepHeight`, stands on slopes up to `slopeCos`, buffers a jump pressed just before landing and still allows one just after walking off an edge. `pushStrength` is how hard it shoves dynamic bodies it walks into, which is all it takes to push a crate. The capsule's mesh is built from the controller's own `radius` and `halfHeight`, so the picture and the collision shape match. ## Orbs ```ts interface Orb { x: number; y: number; z: number; taken: boolean; } const random = mulberry32(SEED); const orbs: Orb[] = []; const orbMesh = renderer.createMesh( new MeshBuilder().addSphere([0, 0, 0], 0.32, srgbColor(1, 0.78, 0.36), 1).build(), ); function blocked(x: number, z: number): boolean { return footprints.some( (f) => f.hx < ARENA && Math.abs(x - f.x) < f.hx + 0.8 && Math.abs(z - f.z) < f.hz + 0.8, ); } /** Lay out a round. Called between rounds, never per frame, so building the list is fine here. */ function scatter(): void { orbs.length = 0; while (orbs.length < ORB_COUNT - 1) { const x = (random() * 2 - 1) * (ARENA - 1.5); const z = (random() * 2 - 1) * (ARENA - 1.5); if (!blocked(x, z)) orbs.push({ x, y: 0.9, z, taken: false }); } orbs.push({ x: -6, y: PLATFORM_TOP + 0.9, z: -6, taken: false }); } ``` `mulberry32(SEED)` is a seeded random generator. Seven orbs are scattered where nothing stands, and the eighth always waits on top of the platform, so every round asks for one climb. The fourth argument to `addSphere` is the emissive strength: these orbs glow. ## Input ```ts const input = new InputSource(canvas, ['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']); const actions = new ActionMap(input, { move: { stick: 'left', up: ['KeyW', 'ArrowUp'], down: ['KeyS', 'ArrowDown'], left: ['KeyA', 'ArrowLeft'], right: ['KeyD', 'ArrowRight'], }, jump: { keys: ['Space'], buttons: ['faceDown'] }, restart: { keys: ['KeyR', 'Enter'], buttons: ['start'] }, pause: { keys: ['KeyP', 'Escape'], buttons: ['select'] }, }); /** A thumb stick on the left of a touch screen, and a tap or hold on the right. */ const touch = new TouchControls(input); const move = { x: 0, y: 0 }; ``` [Moving things](https://driftengine.dev/docs/start/moving-things) explains the three layers. The game binds `move` to a stick and four key directions, and `jump`, `restart` and `pause` to keys and buttons. ## Sound ```ts // A browser lets a page make sound only after a gesture, so the graph is made on the first press. let sound: AudioGraph | null = null; let soundAsked = false; async function startSound(): Promise { if (soundAsked) return; soundAsked = true; const graph = await AudioGraph.create({ stemCount: 0 }); if (graph === null) return; graph.registry.register('orb', { urls: [], synth: (ctx) => toneBuffer(ctx, 0.2, 660, 1320, 3), }); sound = graph; await graph.registry.load(graph.context); } addEventListener('pointerdown', () => void startSound()); addEventListener('keydown', () => void startSound()); function chime(): void { sound?.play(sound.registry.get('orb'), 0.45); } ``` `@driftengine/audio` gives every sound a named slot. A slot lists files to try and a function that synthesises a stand-in when none of them loads. This one lists no files, so the chime is always the stand-in: a sine sweep from 660 to 1320 Hz. Drop an `orb.opus` into the game's assets and add it to `urls`, and the real sound replaces it with no other change. A browser starts audio only after the player touches something, and warns about a page that makes an audio context before then, so the game makes its graph on the first key or tap. Until then, and in a browser with no audio at all, where `AudioGraph.create` returns `null`, `sound` is `null` and `chime` plays nothing. ## The round, in DriftScript ```drs // How long a round lasts, in seconds, and how close the player has to come to an orb, in metres. let ROUND_SECONDS: f32 = 60 let REACH: f32 = 1 // Where a round is: still being played, or over one way or the other. enum Phase { Playing Won Lost } // One round, which the page owns and hands to every rule below. data Round { remaining: f32 = 60 gathered: u32 = 0 total: u32 = 8 phase: Phase = Phase.Playing } ``` The round's state is a `data` record, `Round`, and the two numbers it is tuned by are constants beside it. Where the round is, playing, won or lost, is an enum, `Phase`, so a misspelt phase is a compile error and the page reads which one it is as `round.phase.tag`. A `.drs` file is compiled by the bundler like any other import, so it needs no build step of its own, and it is checked before the page loads: a misspelt field or a number where a string belongs is an error in the terminal, not a surprise in the browser. ```drs // A new round: a full clock, nothing gathered yet, and the number of orbs the page laid out. fn start(round: mut Round, total: u32) { round.remaining = ROUND_SECONDS round.gathered = 0 round.total = total round.phase = Phase.Playing } // Whether the player, this far from an orb on each axis, is close enough to take it. Pure: it reaches // nothing outside its arguments and the constants above, which the compiler checks. @pure fn reaches(dx: f32, dy: f32, dz: f32) -> bool { return dx * dx + dy * dy + dz * dz < REACH * REACH } fn gather(round: mut Round) { round.gathered = round.gathered + 1 } ``` ```drs // The clock, once a step. Every orb taken wins the round; the clock reaching zero first loses it. // Deterministic: the same round and the same step give the same answer on every machine, so a // recorded round replays exactly. Reading input or the wall clock here would not compile. @deterministic fn tick(round: mut Round, dt: f32) { if round.phase != Phase.Playing { return } round.remaining = round.remaining - dt if round.gathered == round.total { round.phase = Phase.Won } else if round.remaining <= 0 { round.remaining = 0 round.phase = Phase.Lost } } ``` Each rule is a function the page calls. `round: mut Round` is the record the page passes in, which the function may change. Nothing here can reach the renderer, the physics world or the player: the page works out how far the player is from an orb and asks `reaches`, and the script answers. That is the split this whole engine is written around. A script decides; the page, which holds the engine's objects, acts. ```ts /* * The round's rules are a DriftScript module. Loading it builds the module, binding it hands it * the engine capabilities it imports, which here is none, and `createRound` makes the record it * keeps the round in. The page owns that record and passes it to every rule. */ const roundModule = loadModule(roundScript as Record); const bound = bindModule(roundModule, {}); if (!bound.bound) throw new Error(bound.reason); /* A variant reaches the page as its tag: `round.phase.tag` is `'Playing'`, `'Won'` or `'Lost'`. */ interface Round { remaining: number; gathered: number; total: number; phase: { tag: 'Playing' | 'Won' | 'Lost' }; } /* Read through the module each call, so a rule patched by a save is the rule that runs. */ const rules = roundModule.exports as unknown as { createRound(): Round; start(round: Round, total: number): void; reaches(dx: number, dy: number, dz: number): boolean; gather(round: Round): void; tick(round: Round, dt: number): void; }; const round = rules.createRound(); /* Saving `round.drs` replaces its functions and keeps `round` as it was: the clock carries on. */ if (import.meta.hot) { import.meta.hot.accept('./round.drs', (next) => { if (next !== undefined) patchModule(roundModule, next as Record, { Round: [round] }); }); } ``` `loadModule` turns the compiled file into a module, and `bindModule` gives it the engine capabilities it imports, here none. `createRound` is made by the compiler from the `data` declaration, and the record it returns belongs to the page from then on. The rules are read through the module on every call, so a function replaced by a save is the one that runs next. Run the example with `npm run examples`, start a round, then change `ROUND_SECONDS` or the `tick` rule and save: the game carries on with the clock where it was and plays by the new rule from the next step. That is the point of keeping rules in a script. [DriftScript in a game](https://driftengine.dev/docs/scripting/driftscript) says what belongs in one and what does not, and [Setting up scripts](https://driftengine.dev/docs/scripting/setting-up) covers the build and the hot reload in full. ## A round ```ts let paused = false; function newRound(): void { scatter(); rules.start(round, orbs.length); player.teleport(START[0], START[1], START[2]); playerBefore.x = player.x; playerBefore.y = player.y; playerBefore.z = player.z; } ``` `newRound` lays out new orbs, has the script start a round over them, and puts the player back at the start. It also resets `playerBefore`, so the first frame of a round doesn't draw the player sliding back from wherever the last round ended. ## The step ```ts function simulate(dt: number): void { if (round.phase.tag !== 'Playing') { if (actions.consumePress('restart') || touch.consumePrimaryPress()) newRound(); return; } // Keys and the pad follow the stick convention, where up is negative. The touch stick reports // up as positive, so it is flipped here, once. actions.vector('move', move); if (touch.moveX !== 0 || touch.moveY !== 0) { move.x = touch.moveX; move.y = -touch.moveY; } playerBefore.x = player.x; playerBefore.y = player.y; playerBefore.z = player.z; player.move(world, dt, { moveX: move.x * player.maxSpeed, moveZ: move.y * player.maxSpeed, jump: actions.down('jump') || touch.primaryHeld, }); recordCrates(crateBefore); world.step(dt); recordCrates(crateAfter); for (let i = 0; i < orbs.length; i += 1) { const orb = orbs[i]; if (orb.taken) continue; const dx = orb.x - player.x; const dy = orb.y - player.y; const dz = orb.z - player.z; if (rules.reaches(dx, dy, dz)) { orb.taken = true; rules.gather(round); chime(); } } if (player.y < -10) player.teleport(START[0], START[1], START[2]); rules.tick(round, dt); } ``` The order is the whole design: 1. Read input into a direction. 2. Move the player against the world. 3. Step the world, so crates the player pushed respond, recording crates before and after. 4. Collect any orb the rules say is close enough. 5. Let the rules count the clock down and decide whether the round is over. Everything here reads state, the step's input and the seeded generator. Nothing reads the time of day, so a recording of the inputs replays the round exactly. ## The camera ```ts const camera = new Camera(); camera.fovYDeg = 55; const eye = { x: START[0], y: START[1] + 6, z: START[2] + 9 }; /** Ease toward a spot behind and above the player. Presentation only, so it runs on frame time. */ function follow(x: number, y: number, z: number, frameDt: number): void { eye.x = damp(eye.x, x, 5, frameDt); eye.y = damp(eye.y, y + 6, 5, frameDt); eye.z = damp(eye.z, z + 9, 5, frameDt); camera.position[0] = eye.x; camera.position[1] = eye.y; camera.position[2] = eye.z; camera.lookAt(x, y + 0.6, z); camera.updateMatrices(renderer.cssHeight > 0 ? renderer.cssWidth / renderer.cssHeight : 1); } ``` The camera eases toward a spot behind and above the player. The easing runs on `frameDt` in the frame, because it's presentation: it doesn't change the game, only how it's seen. ## Placing everything for the frame ```ts /** One node per thing that moves, built once, so a frame writes matrices and allocates nothing. */ const still = new SceneNode(); still.updateWorld(); const playerNode = new SceneNode(); const crateNodes = crates.map(() => new SceneNode()); const orbNodes = Array.from({ length: ORB_COUNT }, () => new SceneNode()); let clock = 0; function placeEverything(alpha: number): void { playerNode.setPosition( lerp(playerBefore.x, player.x, alpha), lerp(playerBefore.y, player.y, alpha), lerp(playerBefore.z, player.z, alpha), ); playerNode.updateWorld(); for (let i = 0; i < crates.length; i += 1) placeCrate(crateNodes[i], i, alpha); for (let i = 0; i < orbs.length; i += 1) { const orb = orbs[i]; orbNodes[i].setPosition(orb.x, orb.y + Math.sin(clock * 2.4 + i) * 0.12, orb.z); orbNodes[i].setRotationAxisAngle(0, 1, 0, clock * 1.5 + i); orbNodes[i].updateWorld(); } } /** Position by lerp and rotation by normalised lerp. A step turns a crate very little, so that is enough. */ function placeCrate(node: SceneNode, i: number, alpha: number): void { const a = crateBefore; const b = crateAfter; const o = i * 7; // q and -q are the same rotation; flip one so the blend goes the short way round. const dot = a[o + 3] * b[o + 3] + a[o + 4] * b[o + 4] + a[o + 5] * b[o + 5] + a[o + 6] * b[o + 6]; const sign = dot < 0 ? -1 : 1; const r = node.rotation; for (let k = 0; k < 4; k += 1) r[k] = lerp(a[o + 3 + k] * sign, b[o + 3 + k], alpha); const length = Math.hypot(r[0], r[1], r[2], r[3]); for (let k = 0; k < 4; k += 1) r[k] /= length; node.position[0] = lerp(a[o], b[o], alpha); node.position[1] = lerp(a[o + 1], b[o + 1], alpha); node.position[2] = lerp(a[o + 2], b[o + 2], alpha); node.markMoved(); node.updateWorld(); } ``` Each moving thing gets its own `SceneNode`, made once at load. Each frame writes their positions between the last two steps and updates their world matrices, and nothing is allocated. Rotations are quaternions. Blending two of them component by component and normalising, the normalised lerp, is accurate for the small turn a crate makes in one step. The sign check makes the blend go the short way round, because a quaternion and its negative are the same rotation. ## Shadows and the frame ```ts /** * Everything in the world, said once. The shadow pass and the colour pass both draw from this, * so nothing can cast a shadow without being seen, or be seen without casting one. */ const casters: ShadowCasters = (sink) => { sink.mesh(levelMesh, still.worldMatrix); sink.mesh(playerMesh, playerNode.worldMatrix); for (let i = 0; i < crateNodes.length; i += 1) sink.mesh(crateMesh, crateNodes[i].worldMatrix); for (let i = 0; i < orbs.length; i += 1) { if (!orbs[i].taken) sink.mesh(orbMesh, orbNodes[i].worldMatrix); } }; const lightMatrix = new Float32Array(16); ENV.lightViewProj = lightMatrix; ENV.shadowStrength = 0.8; ``` `casters` is one function that names everything in the world. The shadow pass calls it to draw depth from the sun, and the colour pass calls it to draw the picture, so nothing can be visible without casting a shadow, or cast one without being visible. ```ts function render(alpha: number, frameDt: number): void { // Input is sampled here, at the edge of the simulation: a step reads what this left behind. touch.tick(performance.now()); // Read here, not in simulate: while paused, simulate is not called at all. if (actions.consumePress('pause')) paused = !paused; if (!paused) clock += frameDt; placeEverything(alpha); const at = playerNode.position; follow(at[0], at[1], at[2], frameDt); // The shadow map covers 16 metres around the player, which is everything the camera sees. ENV.shadowDepthSpan = computeLightMatrix( ENV.directionalDir, at[0], at[1], at[2], 16, renderer.shadowMapSize, lightMatrix, ); renderer.beginShadowPass(lightMatrix, 'static'); renderer.drawShadowCasters(casters); renderer.endShadowPass(); renderer.beginFrame(SKY); renderer.bindMeshPass(camera, ENV); renderer.drawSceneCasters(casters); drawHud(); renderer.endFrame(); } ``` `computeLightMatrix` aims the sun's shadow map at the 16 metres around the player, which is all the camera ever shows, so the map's resolution is spent where you're looking. It returns the depth span the shading needs, and the environment carries both to the mesh pass. The frame then runs the shadow pass, opens the colour frame, binds the camera and environment, draws the casters, draws the HUD and ends. ## The HUD ```ts const hud = renderer.createText(); let hudStyle: typeof DEFAULT_TEXT_STYLE = { ...DEFAULT_TEXT_STYLE, color: srgbColor(1, 0.98, 0.92), glow: 0.7, }; /** What the text last said, so a new string is built only when a number on it changes. */ const shown = { gathered: -1, seconds: -1, phase: '', paused: false }; function drawHud(): void { const seconds = Math.ceil(round.remaining); if ( round.gathered !== shown.gathered || seconds !== shown.seconds || round.phase.tag !== shown.phase || paused !== shown.paused ) { shown.gathered = round.gathered; shown.seconds = seconds; shown.phase = round.phase.tag; shown.paused = paused; renderer.setText( hud, paused ? 'PAUSED. PRESS P TO CARRY ON' : round.phase.tag === 'Won' ? 'ALL GATHERED. PRESS R OR TAP TO PLAY AGAIN' : round.phase.tag === 'Lost' ? 'OUT OF TIME. PRESS R OR TAP TO PLAY AGAIN' : `ORBS ${round.gathered}/${round.total} TIME ${seconds}`, ); } const width = renderer.cssWidth; const height = renderer.cssHeight; // The style is rebuilt only when a resize moves the cell size. const cell = Math.max(2, Math.round(Math.min(width, height) / 220)); if (cell !== hudStyle.cellSize) hudStyle = { ...hudStyle, cellSize: cell }; renderer.drawText( hud, width, height, Math.round(width / 2 - renderer.textWidth(hud, cell) / 2), Math.round(height * 0.08) + cell * 7, hudStyle, 0, ); } ``` The built-in pixel font needs no asset. A text handle is laid out once per string, so the HUD builds a new string only when a number on it changes, and the style object is rebuilt only when a resize changes the size of a cell. ## Starting it ```ts newRound(); startLoop({ simulate, render, shouldSimulate: () => !paused }); ``` A round, then the loop, with pause wired to `shouldSimulate`. ## Where to take it The game is small on purpose, and every part of it has somewhere to grow: - Replace the boxes with a model from Blender or glTF, and the capsule with a skinned, animated character. - Swap the follow camera for the third-person rig, which keeps the lens out of walls. - Turn on bloom, so the orbs glow past their edges. - Record the inputs for each tick and play a round back, which the fixed step already makes exact. - Move more of the game into `round.drs`: a bonus orb that adds time, crates that score when pushed off the platform, a round that gets shorter each time it is won. Next, [A 2D game](https://driftengine.dev/docs/start/a-2d-game) shows that the same engine draws a flat game with no special mode, and [Shipping to the web](https://driftengine.dev/docs/start/shipping-to-the-web) turns either into something you can put online. --- # A 2D game Getting started. https://driftengine.dev/docs/start/a-2d-game A complete breakout game drawn in the XY plane by the same 3D renderer, with a camera that makes it read as flat and one mesh tinted per brick. There's no 2D mode in DriftEngine, and a flat game doesn't need one. Lay the world out in the XY plane, put the camera down the Z axis looking back at it, and the screen has X to the right and Y up, exactly as a 2D game expects. This page builds breakout that way: a paddle, a ball, rows of bricks, a score, three lives, and a win and a loss. (This chapter runs the `game-2d` example at https://driftengine.dev/docs/start/a-2d-game.) Move the paddle with the mouse or the arrow keys. The program is `examples/game-2d/main.ts`. For sprite sheets, tilemaps and a retained interface tree, the engine also has a dedicated 2D layer in `@driftengine/ui2d`. This page is about the other route: drawing a 2D game with the renderer you already know, which gets lighting and depth for nothing. ## The field ```ts const FIELD_X = 7; const FIELD_TOP = 9.5; const FIELD_BOTTOM = -9.5; const PADDLE_Y = -8; const PADDLE_HALF = 1.3; const BALL_R = 0.24; const COLS = 8; const ROWS = 4; const BRICK_HALF_X = 0.72; const BRICK_HALF_Y = 0.26; ``` Everything is measured in world units in the plane. The field is 14 units wide and 19 tall. ## Even light ```ts /** * Flat-on light, so the board reads evenly rather than falling off toward one corner. Colours * picked by eye go through `srgbColor` wherever they are lit, since the renderer lights in linear * values, and the clear colour and the score's with them. */ const CLEAR = srgbColor(0.05, 0.06, 0.09); const FLAT = createEnvironment({ directionalDir: [0.25, 0.45, 1], directionalColor: srgbColor(1, 0.97, 0.92), ambient: srgbColor(0.34, 0.36, 0.42), ambientGround: srgbColor(0.2, 0.21, 0.26), emissiveGain: 1, nightFactor: 0, fogColor: srgbColor(0.05, 0.06, 0.09), fogDensity: 0, fogHeightFalloff: 0, fogBaseY: 0, }); ``` The light comes almost straight down the view, so the board reads evenly instead of falling off toward one corner. Each brick is still a lit box, and its sides shade like one. ## The stage ```ts const stage = await openStage({ directionalShadows: false, sceneSamples: 4 }); ``` `openStage` is a helper shared by the engine's examples. It does what [Hello world](https://driftengine.dev/docs/start/hello-world) does by hand: finds the canvas, creates the renderer, wires resize, makes a camera and starts the loop. `sceneSamples: 4` turns on multisampling, which matters here because long horizontal edges are exactly where aliasing shows. ## One mesh for every brick ```ts /* * One unit brick, drawn once per live brick with a different tint. `drawMesh` takes an * optional colour multiplier that is reset after the call, which is what lets a single * flat-shaded mesh stand in for four rows of different colours without four meshes. */ const brickMesh = new MeshBuilder(); brickMesh.addBox([0, 0, 0], [BRICK_HALF_X, BRICK_HALF_Y, 0.24], [1, 1, 1]); const brick = stage.renderer.createMesh(brickMesh.build()); const paddleMesh = new MeshBuilder(); paddleMesh.addBox([0, 0, 0], [PADDLE_HALF, 0.26, 0.24], srgbColor(0.82, 0.86, 0.95)); const paddle = stage.renderer.createMesh(paddleMesh.build()); const ballMesh = new MeshBuilder(); ballMesh.addBox([0, 0, 0], [BALL_R, BALL_R, BALL_R], srgbColor(1, 0.86, 0.5)); const ball = stage.renderer.createMesh(ballMesh.build()); const wallMesh = new MeshBuilder(); wallMesh.addBox([0, 0, 0], [0.25, FIELD_TOP, 0.24], srgbColor(0.24, 0.26, 0.34)); const wall = stage.renderer.createMesh(wallMesh.build()); ``` There is one brick mesh, white. `drawMesh` takes an optional tint that multiplies the mesh's colour for that one draw, so four rows of different colours are four tints on the same mesh instead of four meshes. ## The bricks ```ts const ROW_TINTS: [number, number, number][] = [ srgbColor(0.95, 0.42, 0.35), srgbColor(0.95, 0.68, 0.32), srgbColor(0.55, 0.78, 0.5), srgbColor(0.45, 0.66, 0.95), ]; /** Reused for every draw: set, update, draw, set again. Nothing is allocated in the frame. */ const place = new SceneNode(); interface Brick { readonly x: number; readonly y: number; readonly row: number; alive: boolean; } const bricks: Brick[] = []; function rack(): void { bricks.length = 0; for (let row = 0; row < ROWS; row += 1) { for (let col = 0; col < COLS; col += 1) { bricks.push({ x: (col - (COLS - 1) / 2) * (BRICK_HALF_X * 2 + 0.14), y: 6.6 - row * (BRICK_HALF_Y * 2 + 0.24), row, alive: true, }); } } } rack(); ``` The game's own state is plain data: a list of bricks with a position, a row and whether they're still standing. One `SceneNode` is reused for every draw: set its position, update it, draw, and set it again for the next thing. ```ts let paddleX = 0; let ballX = 0; let ballY = PADDLE_Y + 1; let previousBallX = ballX; let previousBallY = ballY; let velX = 4.4; let velY = 7.6; let score = 0; let lives = 3; let over = ''; ``` The ball keeps its previous position, like every moving thing, so the frame can draw it between steps. ## Input ```ts /* Pointer drives the paddle; the arrow keys do too, so the example works without a mouse. */ let pointerTarget: number | null = null; const held = new Set(); addEventListener('pointermove', (event) => { const half = stage.renderer.cssWidth / 2; pointerTarget = ((event.clientX - half) / half) * FIELD_X; }); addEventListener('keydown', (event) => held.add(event.key)); addEventListener('keyup', (event) => held.delete(event.key)); addEventListener('pointerdown', () => { if (over !== '') { score = 0; lives = 3; over = ''; rack(); serve(); } }); function serve(): void { ballX = paddleX; ballY = PADDLE_Y + 1; previousBallX = ballX; previousBallY = ballY; velX = 4.4 * (Math.random() < 0.5 ? -1 : 1); velY = 7.6; } ``` This example reads the DOM directly to stay on one subject. A real game would use an `ActionMap`, as [Moving things](https://driftengine.dev/docs/start/moving-things) describes, and get gamepads and touch for free. ## A camera that looks flat ```ts const hud = stage.renderer.createText(); stage.camera.fovYDeg = 14; stage.camera.position[0] = 0; stage.camera.position[1] = 0; stage.camera.position[2] = 86; stage.camera.lookAt(0, 0, 0); ``` The engine's camera is a perspective camera. What makes it read as flat is a narrow field of view from a long way back. The visible height at distance `d` is `2 * d * tan(fov / 2)`, so a 19-unit board at 14 degrees needs about 86 units of distance. At that distance the lines of sight have barely spread by the time they cross the board, and the picture is orthographic to the eye. Widen `fovYDeg` and the outer bricks start to show their sides. ## The step ```ts simulate(dt) { if (over !== '') return; if (held.has('ArrowLeft')) paddleX -= 14 * dt; if (held.has('ArrowRight')) paddleX += 14 * dt; if (pointerTarget !== null) paddleX += (pointerTarget - paddleX) * Math.min(1, dt * 14); paddleX = Math.max(-FIELD_X + PADDLE_HALF, Math.min(FIELD_X - PADDLE_HALF, paddleX)); previousBallX = ballX; previousBallY = ballY; ballX += velX * dt; ballY += velY * dt; /* Walls and ceiling. Reflect and push back out, so a fast ball cannot stick to an edge. */ if (ballX < -FIELD_X + BALL_R) { ballX = -FIELD_X + BALL_R; velX = Math.abs(velX); } else if (ballX > FIELD_X - BALL_R) { ballX = FIELD_X - BALL_R; velX = -Math.abs(velX); } if (ballY > FIELD_TOP - BALL_R) { ballY = FIELD_TOP - BALL_R; velY = -Math.abs(velY); } /* * The paddle steers rather than merely reflecting: where the ball lands across its width * sets the outgoing angle. Without that a game of this shape has exactly one rally in it. */ if ( velY < 0 && ballY - BALL_R < PADDLE_Y + 0.26 && ballY > PADDLE_Y - 0.6 && Math.abs(ballX - paddleX) < PADDLE_HALF + BALL_R ) { ballY = PADDLE_Y + 0.26 + BALL_R; const offset = (ballX - paddleX) / PADDLE_HALF; const speed = Math.hypot(velX, velY); const angle = offset * 1.0; velX = Math.sin(angle) * speed; velY = Math.cos(angle) * speed; } for (const b of bricks) { if (!b.alive) continue; if ( Math.abs(ballX - b.x) < BRICK_HALF_X + BALL_R && Math.abs(ballY - b.y) < BRICK_HALF_Y + BALL_R ) { b.alive = false; score += 10; /* Reflect on the shallower overlap, so a corner hit does not pass through. */ const overlapX = BRICK_HALF_X + BALL_R - Math.abs(ballX - b.x); const overlapY = BRICK_HALF_Y + BALL_R - Math.abs(ballY - b.y); if (overlapY < overlapX) velY = -velY; else velX = -velX; break; } } if (bricks.every((b) => !b.alive)) over = 'CLEARED'; if (ballY < FIELD_BOTTOM) { lives -= 1; if (lives <= 0) over = 'GAME OVER'; else serve(); } }, ``` Breakout needs no physics engine. The ball moves by its velocity each step and bounces by flipping a component of it. The paddle steers: where the ball lands across its width sets the outgoing angle, which is what gives the game more than one rally. A brick hit reflects on the axis with the smaller overlap, so a corner hit doesn't pass through. ## The frame ```ts render(alpha) { const drawX = previousBallX + (ballX - previousBallX) * alpha; const drawY = previousBallY + (ballY - previousBallY) * alpha; stage.renderer.beginFrame(CLEAR); stage.renderer.bindMeshPass(stage.camera, FLAT); for (const side of [-1, 1]) { place.setPosition(side * (FIELD_X + 0.25), 0, 0); place.updateWorld(); stage.renderer.drawMesh(wall, place.worldMatrix); } for (const b of bricks) { if (!b.alive) continue; place.setPosition(b.x, b.y, 0); place.updateWorld(); stage.renderer.drawMesh(brick, place.worldMatrix, undefined, ROW_TINTS[b.row]); } place.setPosition(paddleX, PADDLE_Y, 0); place.updateWorld(); stage.renderer.drawMesh(paddle, place.worldMatrix); place.setPosition(drawX, drawY, 0); place.updateWorld(); stage.renderer.drawMesh(ball, place.worldMatrix); const width = stage.renderer.cssWidth; const height = stage.renderer.cssHeight; const cell = Math.max(2, Math.round(Math.min(width, height) / 260)); stage.renderer.setText( hud, over === '' ? `SCORE ${score} LIVES ${lives}` : `${over} - CLICK TO PLAY AGAIN`, ); stage.renderer.drawText( hud, width, height, Math.round(width * 0.5 - stage.renderer.textWidth(hud, cell) / 2), Math.round(height * 0.93), { ...DEFAULT_TEXT_STYLE, cellSize: cell, color: srgbColor(0.92, 0.94, 1), glow: 0, alpha: 1, reveal: 1, }, 0, ); stage.renderer.endFrame(); }, ``` Walls, live bricks with their row tint, the paddle and the ball at its interpolated position, then the score in the built-in pixel font, centred by measuring the string. --- # Shipping to the web Getting started. https://driftengine.dev/docs/start/shipping-to-the-web Build a DriftEngine game into static files, host it anywhere, test it on a phone, and know what a web build carries and why. A DriftEngine game is static files. There is no server component to run and nothing to install on the host: build the game, upload the output, and it plays in a browser. ```sh npm run build ``` With Vite that writes `dist/`, an `index.html` beside a folder of hashed scripts and assets. Upload that folder to any static host, a CDN bucket or a plain web server. ## What a build carries Only what you import. Every package is tree-shaken, and each package's README states its measured gzipped cost, checked on every change to the engine. A game that imports only `@driftengine/core` ships without the audio package, the physics workers or the model readers. Features that run off the main thread are separate files. The bundler finds each `new Worker(new URL(...))` the engine uses and emits the worker beside your scripts, and it is only fetched when the feature that owns it starts. ## Paths If the game is served from a subfolder of a site instead of the root, tell the bundler. In Vite that is `base`: ```js import { defineConfig } from 'vite'; export default defineConfig({ base: '/games/arena/' }); ``` Anything your own code fetches by an absolute path needs the same treatment. Audio slots are a common case: the helper that lists a sound's candidate files defaults to `/audio`, and takes a second argument for the folder they really live in. ## Testing on a phone Serve the development build on your network and open it on the phone: ```sh npm run dev -- --host ``` > [!NOTE] > Browsers only offer WebGPU on a secure origin: `https://`, or `localhost` on the machine itself. > A phone opening `http://192.168.1.20:5173` gets WebGL2, which is correct behaviour and a good test of > the fallback. To test WebGPU on the phone, serve the development build over HTTPS or tunnel it to > the phone's own `localhost`. The quality profile you give `createRenderer` is where a phone is won or lost. `maxDevicePixelRatio` is the first setting to lower: a phone's screen is dense, and drawing every physical pixel is the largest single cost in most frames. ## Before you publish - **Show the backend and the reason** somewhere a tester can see them, at least in builds you hand out for testing. Every report about a picture starts with which backend drew it. - **Decide about the badge.** The engine shows its badge for three seconds after the first frame unless you pass `{ splash: false }`. It's a request, and turning it off is fine. - **Reproduce the `NOTICE`.** The licence asks for it somewhere a person can read it, and the engine's entry points already carry it into your bundle. A credits page that repeats it is the simplest way to be sure. - **Serve with compression.** Most hosts gzip or Brotli-compress scripts by default; check yours does, since a game's scripts compress well. The same build can also become an installed app on Linux, Windows, macOS and Android, from one manifest, which the shipping section of this manual covers. --- # Packages Concepts. https://driftengine.dev/docs/concepts/packages How the engine divides into packages, what each one costs in a build, how they depend on each other, and which to install for what. DriftEngine is a set of npm packages under the `@driftengine` scope, all released together on one version line. A game installs `@driftengine/core` and adds the others as it needs them. ## What core is, and what it brings with it `@driftengine/core` is the runtime: the loop, the renderer and its passes on both backends, the scene graph and culling, cameras, input, geometry builders, maths, storage and preferences. It depends on two other packages and re-exports both, so you can import their names from core: - **`@driftengine/physics`** in full. The cameras and the ribbon builder use its collision sweep, so core cannot be built without it, and re-exporting it means `PhysicsWorld` and `CharacterController` come from the same import as `createRenderer`. - **`@driftengine/drft`** for the mesh data type every package shares, `MeshData`. Its validator, `validateMeshData`, is imported from `@driftengine/drft` itself. Everything else is optional, and a package that builds on core declares it as a peer dependency. ## Every package on one version Each package pins the exact version of every engine package it depends on, so a project uses one version for every `@driftengine` package it installs. Upgrade them together: ```sh npm install @driftengine/core@latest @driftengine/audio@latest @driftengine/assets@latest ``` A mismatch is caught by npm at install time, as an unmet peer dependency, which is a better place to find it than a missing export at run time. ## What each costs The engine's size gate builds each entry point on its own and fails the engine's CI if the gzipped size moves more than 3% from the figure it holds. These are those figures, read from the gate at the release this site documents: Most of core is shader source, generated WGSL for every combination of features the lit pass can be built with. Shader text barely minifies, which is why the optional packages look small beside it. Features that live inside the lit pass cannot be packages, so they are compiled in only when a quality option asks for them: physically based maps, spot and area lights, clustered lighting, image-based lighting, depth of field, screen-space reflection, temporal antialiasing, colour grading and decals. A driver compiles the text it is given, so a feature that is off costs no GPU time. ## Which package for what | You want | Install | | -------------------------------------------------------------- | -------------------------- | | A renderer, a loop, input, cameras, collision and rigid bodies | `@driftengine/core` | | Models from glTF, OBJ, FBX, USD, STL, 3MF or Blender | `@driftengine/assets` | | Music, sound effects, positional audio | `@driftengine/audio` | | Skeletal animation, blending, IK | `@driftengine/animation` | | Sprites, tilemaps and an interface tree | `@driftengine/ui2d` | | Entities, components and systems | `@driftengine/entities` | | Multiplayer: lockstep, prediction, rollback | `@driftengine/network` | | Navigation meshes and pathfinding | `@driftengine/nav` | | Heightfield terrain | `@driftengine/terrain` | | Gaussian splat captures | `@driftengine/splats` | | Textures as compiled programs, streamed | `@driftengine/texture` | | A video turned into a scene | `@driftengine/capture` | | Recording video of the game | `@driftengine/media` | | VR and AR through WebXR | `@driftengine/xr` | | Language-model agents with typed tools | `@driftengine/ai` | | Chemistry of bulk matter: fire, smoke, reactions | `@driftengine/chemistry` | | Editor panels inside a shipped game | `@driftengine/tools` | | The scene editor's model | `@driftengine/editor` | | DriftScript bindings to the engine | `@driftengine/script` | | Desktop and Android builds of the game | `@driftengine/package` | | Running with no browser | `@driftengine/native-host` | ## Three packages that need nothing else `@driftengine/physics`, `@driftengine/entities` and `@driftengine/chemistry` import no other engine package. A server that runs a simulation, or a worker that steps one, can import any of them without pulling a renderer into its module graph. That's what makes an authoritative multiplayer host possible in plain Node. ## Built JavaScript or TypeScript source Every package ships compiled JavaScript with declaration files, and that is what a bundler and Node find by default. Every package also ships its TypeScript source behind the `drift-source` export condition, for a project that depends on a checkout of the engine and wants an edit to it live with no build; [Installation](https://driftengine.dev/docs/start/installation) covers that set-up. --- # WebGPU and WebGL2 Concepts. https://driftengine.dev/docs/concepts/backends How the engine chooses between WebGPU and WebGL2, what it reports about the choice, what only WebGPU can do, and how to tune quality per backend. The engine draws with WebGPU and falls back to WebGL2. Both backends implement one surface, `RendererApi`, and a game draws through that surface without knowing which one is underneath. You never write a shader, own a framebuffer or touch GPU state; you submit meshes, lights and passes. ## How the choice is made `createRenderer` asks for WebGPU first. It falls back to WebGL2 when any of these happens: - the browser has no WebGPU, or returns no adapter; - the adapter or the device request fails; - the device is created but cannot draw: the engine draws a known pixel with it and reads it back before accepting it, because some devices validate every call and rasterise nothing; - the request takes longer than its timeout, eight seconds unless you set `backendTimeoutMs`, because an adapter request that never settles would otherwise leave the page blank forever. The fallback is silent in the picture and loud in the result. `createRenderer` resolves to the renderer and three facts about it: `backend`, which is `'webgpu'` or `'webgl2'`; `reason`, why, in words; and `rendererName`, what the GPU calls itself. Put the first two somewhere a tester can see them and all three in any report of a problem. `?backend=webgl2` or `?backend=webgpu` on the page's address forces the choice, which is the quickest way to compare a scene on both. `preferWebGpu: false` in the renderer's options skips WebGPU entirely. ## Tuning per backend The quality profile can be a function of the backend that was built. `createRenderer` calls it once, with the answer: ```ts /** A quality profile per backend: the function is called once, with the backend that was built. */ export async function rendererFor(canvas: HTMLCanvasElement) { return createRenderer(canvas, (backend: RenderBackend) => backend === 'webgpu' ? { maxDevicePixelRatio: 2, directionalShadows: true, sceneSamples: 4, bloom: 0.4 } : { maxDevicePixelRatio: 1.5, directionalShadows: true }, ); } ``` A profile is chosen at construction because most options size GPU memory. To change one, build a new renderer. ## Knowing the GPU before you build `describeGpu` asks the browser what part it has, before any renderer exists, and whether that part belongs to a family known to struggle with heavy profiles: ```ts /** Ask what part this is before building, so a known-weak family starts on the lighter profile. */ export async function rendererForThisMachine(canvas: HTMLCanvasElement) { const gpu = await describeGpu(); const heavy = !gpu.weak; const created = await createRenderer(canvas, { maxDevicePixelRatio: heavy ? 2 : 1.25, directionalShadows: true, pointShadows: heavy, }); console.info( `${created.backend} on ${created.rendererName || 'an unnamed GPU'}: ${created.reason}`, ); return created; } ``` `weak` is a starting point, never a verdict: an unknown part is not weak. `ResolutionGovernor` corrects from measurement after that, lowering and raising the drawing-buffer scale against a frame time. The renderer also clamps the pixel-heavy settings of a known-weak family by itself, because most players never open a settings screen. When a player has chosen their settings in yours, pass `capabilityClamp: false`, so the numbers they picked are the numbers they get. ## What only WebGPU does Some features need compute shaders or indirect draws, which WebGL2 doesn't have. They are off by default and refuse in words on WebGL2, never silently: - **The GPU-driven pipeline**, `pipeline: 'gpu-driven'`, which culls instances and clusters on the device. Asking for it on WebGL2 throws, with the reason. - **DriftTR temporal reconstruction**, `reconstruction`, which renders below output resolution. - **DriftRay indirect light**, `indirectLight`, which marches rays through a distance field. - **Compute passes** of your own. `renderer.computeSupported` answers whether the backend can run them. Everything else draws on both, and the engine holds them to each other: a feature added to one backend reaches the other or states why it doesn't yet. ## What a frame asked for WebGPU keeps fixed rings for per-draw data, so a frame has ceilings: how many draws, material changes, shadow draws, water bodies and so on. `renderer.frameBudget` reports every one of them for the frame just drawn, counting what was asked for, not just what fit: ```ts /** After `endFrame`: every ceiling the backend imposes, and what this frame asked of it. */ export function reportBudget(renderer: RendererApi): void { const budget = renderer.frameBudget; if (!budget.dropped) return; for (const line of budget.lines) { if (line.dropped > 0) { console.warn( `${line.name}: ${line.used} asked for, ${line.dropped} over the ceiling of ${line.ceiling}`, ); } } } ``` The draw and material rings grow on their own when a scene outgrows them, from the next frame. On WebGL2 the same lines are reported with no ceiling, because it imposes none, and counted by the same rules, so you can see a WebGPU ceiling coming while you develop on the fallback. ## Depth runs backwards The engine renders scene depth reversed: the near plane is 1, the far plane is 0, and the depth test is `greater`. It gives far better precision at a distance. It only matters if you write a custom pass: a shader that writes `1.0` meaning "far" is writing the near plane. `REVERSED_DEPTH` is the engine's intent and `reversedDepth` on the created renderer is what the device granted. ## Timing the GPU `gpuTiming: true` measures GPU time with timestamp queries, where the adapter has the `timestamp-query` feature. Leave it off in a shipped build: it adds a timestamp write to every pass in the frame, and a driver that disagrees with any part of that invalidates the whole command buffer, which is a black frame. Turn it on while you measure. Without the feature the timer reports that it is unavailable instead of reporting zero. --- # The scene graph Concepts. https://driftengine.dev/docs/concepts/scene-graph Nodes, parents and world matrices, bounds that enclose a whole subtree, culling by frustum and by occluder, and levels of detail chosen by apparent size. A `SceneNode` holds a position, a rotation and a scale, and works out a world matrix from them and from its parent's. That's all the scene graph is: the engine has no scene object that owns your meshes. You keep nodes where you like, give each mesh draw a node's `worldMatrix`, and use the hierarchy where it helps, for things that move together and for culling whole groups at once. ## Nodes and parents ```ts /** A tower of blocks under one root: move the root and every block moves with it. */ export function buildTower(renderer: RendererApi): { root: SceneNode; block: MeshHandle } { const block = renderer.createMesh( new MeshBuilder().addBox([0, 0, 0], [0.5, 0.5, 0.5], [0.7, 0.7, 0.75]).build(), ); const root = new SceneNode(); for (let level = 0; level < 10; level += 1) { const node = new SceneNode(); node.setPosition(0, level + 0.5, 0); // The mesh's bounds were measured when it was uploaded; the node only says it holds them. node.setBounds(block.bounds); root.attachChild(node); } root.setPosition(4, 0, -6); root.updateWorld(); return { root, block }; } ``` `attachChild` puts a node under another, taking it from wherever it was before; a cycle is refused when you make it, not discovered later as a stack overflow inside a frame. `updateWorld` brings a node and everything under it up to date, and only recomputes what moved: a node whose own transform and whose ancestors are unchanged keeps its matrix. `setPosition`, `setScale` and `setRotationAxisAngle` mark the node as moved. `position`, `rotation` and `scale` are also plain typed arrays you may write in place, which is the allocation-free path for animation. When you do, call `markMoved`, because the node cannot see the write. Rotation is a quaternion, so two rotations interpolate cleanly, which Euler angles do not. ## Bounds A node's `worldBounds` is a sphere that encloses its own geometry **and every descendant's**. That union is what makes the hierarchy useful for culling: a parent whose sphere is out of view answers for everything beneath it in one test. A node learns its own geometry's size from `setBounds`. The renderer measures every mesh when you upload it, so `mesh.bounds` is ready to hand over. A node with no geometry only groups others. ## Culling by frustum ```ts const frustum = createFrustum(); const counts = createVisitResult(); /** Draw only what the camera can see. A rejected parent rejects its whole subtree in one test. */ export function drawVisible( renderer: RendererApi, camera: Camera, env: Environment, root: SceneNode, block: MeshHandle, ): void { frustumFromViewProjection(camera.viewProjection, frustum); renderer.bindMeshPass(camera, env); visitVisible(root, frustum, (node) => renderer.drawMesh(block, node.worldMatrix), counts); // counts.visited, counts.pruned and counts.tested say what the walk saved. } ``` `frustumFromViewProjection` reads the six planes of the camera's view. `visitVisible` walks the hierarchy, skipping any subtree the frustum rejects, and hands you each visible node with geometry. It doesn't draw, so the order things are drawn in stays yours. The counts it fills say what the walk saved: nodes visited, subtrees pruned, and how many tests that took. Separately, the renderer can skip any single `drawMesh` whose bounds are outside the view. That is the `cullDraws` quality option. It costs a sphere test per draw and needs nothing from you. For instanced batches, `cullInstances` keeps only the instances whose spheres meet a frustum, compacted in place. [Instancing](https://driftengine.dev/docs/rendering/instancing) covers batches that cull themselves. ## Levels of detail ```ts /** Apparent sizes, in radians, at which each level stops being good enough. */ const THRESHOLDS = [0.2, 0.06, 0.015]; /** The finest level a thing has earned, from how big it looks, not how far away it is. */ export function levelFor(node: SceneNode, camera: Camera): number { const eye = camera.position; return lodForBounds(node.worldBounds, node.worldMatrix, eye[0], eye[1], eye[2], THRESHOLDS); } ``` `lodForBounds` picks a level from how large an object looks from the eye, as an angle, never from its distance. A distance threshold makes a cathedral and a doorknob change detail at the same range, so one of them always looks wrong; apparent size gets both right with one set of thresholds. The thresholds are in descending order, and the function returns the first level the object is still large enough for. For whole regions of a large world, [hierarchical detail](https://driftengine.dev/docs/worlds/hierarchical-detail) picks each region's level from its error on screen and crossfades between levels for you. ## Culling by occluder The renderer can also hide what is behind something large. You declare the occluders, the few big things a scene is really hidden by, such as walls, buildings and slabs of ground, and the renderer rasterises them into a small depth buffer on the CPU and tests each object against it. ```ts const WALL_MIN = [-6, 0, -0.5]; const WALL_MAX = [6, 8, 0.5]; const IDENTITY = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); /** * Hide what a wall hides. Needs `occlusionCulling` set in the quality profile, the width of the * occlusion buffer in texels; without it `addOccluder` does nothing and `occluded` answers false. */ export function drawBehindWall( renderer: RendererApi, camera: Camera, env: Environment, wall: MeshHandle, crates: readonly SceneNode[], crate: MeshHandle, ): void { renderer.bindMeshPass(camera, env); // After binding the pass and before the first draw: the first test freezes the buffer. renderer.addOccluder(WALL_MIN, WALL_MAX, IDENTITY); renderer.drawMesh(wall, IDENTITY); for (const node of crates) { if (!renderer.occluded(crate.bounds, node.worldMatrix)) renderer.drawMesh(crate, node.worldMatrix); } } ``` The buffer is sized by the `occlusionCulling` quality option, its width in texels; 256 is a good start. With the option off, `addOccluder` does nothing and `occluded` answers false, so the same code runs either way. Everything in it errs toward drawing. It holds the depth of an occluder's far side, shrinks its coverage by a texel at every edge, and hides an object only when every texel the object touches is nearer. A wrong cull is a hole in the world, so it is never traded for a faster frame. Declare the box you may be hidden _by_, never a larger one: an occluder bigger than its solid hides things a player can see. And small things never occlude: a crowd does not hide what is behind it. That is the trade the design makes for running on both backends, with no frame of latency and no GPU read-back. --- # Determinism Concepts. https://driftengine.dev/docs/concepts/determinism How a DriftEngine simulation gives the same result every run on every browser, which replays, rollback netcode and the editor's timeline all depend on. A deterministic simulation, started from the same state and fed the same inputs, produces the same result to the last bit, every time and on every JavaScript engine. DriftEngine is built so that a game can have that property without working for it, and the engine's own systems depend on it: - a replay is a recording of inputs, played back through the same simulation; - rollback networking re-runs the last few ticks when a late input arrives; - the editor scrubs a running game backwards by restoring a snapshot and simulating forward again; - a ghost, a race against your own best run, is a replay you draw beside the live one. All of them come from four rules, and the engine keeps the first three in its own code. ## 1. A fixed step The simulation advances only in fixed steps, a sixtieth of a second by default. A variable step makes a jump height depend on the frame rate, and makes two runs of the same inputs diverge the moment one machine stutters. [The loop](https://driftengine.dev/docs/start/the-loop) covers `startLoop`, which owns this. ## 2. Seeded randomness, which can be rewound ```ts /** A generator whose position is one integer, so a rollback can put it back exactly. */ const random = savableMulberry32(42); const before = random.save(); const first = random.next(); random.restore(before); const again = random.next(); // the same number as `first`, bit for bit ``` `mulberry32(seed)` returns a fast generator whose sequence is fixed forever: the engine treats a change to it as breaking every replay anybody has saved, so it never changes, and a different distribution would be a new function. `savableMulberry32` is the same sequence with its position readable and writable as one integer, which a rollback needs: re-simulated ticks must draw the numbers they drew the first time. Two helpers cover the common cases without a generator at all. `hashToUnit(seed)` gives one well-mixed value per integer, for per-particle or per-tile variation; `pickBySeed(seed, items)` chooses from a list without consecutive seeds walking it in order. ## 3. Arithmetic that every engine agrees on `+`, `-`, `*`, `/` and `Math.sqrt` are exactly specified by ECMAScript, and JavaScript never fuses a multiply and an add. `Math.sin`, `Math.cos`, `Math.exp` and nineteen more are not: two browsers may differ in the last bit, and in a simulation a last bit becomes a different world a few seconds later. Inside the simulation, use the engine's reproducible versions: ```ts /** A platform that sways on a fixed step. `Math.sin` may differ in its last bit between browsers. */ export function swayAt(tick: number): { x: number; z: number } { const t = tick / 60; return { x: exactSin(t * 0.7) * 2, z: exactCos(t * 0.7) * 2 }; } ``` `exactSin`, `exactCos`, `exactExp`, `exactLog` and `exactAcos` are built from the five exact operations only, with fdlibm's coefficients, so they agree everywhere. They are no more accurate than `Math`; they are reproducible, which is the point. Outside the simulation, in drawing and in presentation, `Math` is fine. The engine's own simulation code is held to this by a gate in its repository that refuses the unspecified functions in any module the simulation reaches. ## 4. Nothing from outside Inside `simulate`, never read the wall clock (`Date.now`, `performance.now`), never call `Math.random`, and never read input devices directly. Time is the tick count. Input is sampled once, at the edge of the step, and handed in as data, which is also what you record for a replay. ## Proving two runs agree ```ts /** Run the same simulation twice from the same start, and compare the bodies' bits. */ function run(ticks: number): string { const world = new PhysicsWorld({ substeps: 4 }); world.addBody({ type: BODY_STATIC, shape: boxShape(10, 0.5, 10), y: -0.5 }); for (let i = 0; i < 6; i += 1) { world.addBody({ type: BODY_DYNAMIC, shape: boxShape(0.5, 0.5, 0.5), x: i * 0.3, y: 1 + i * 1.1, }); } for (let tick = 0; tick < ticks; tick += 1) world.step(1 / 60); return fingerprintBodies(world.bodies); } export const agrees = run(600) === run(600); ``` `fingerprintBodies` hashes the raw bits of every body's state, and `fingerprintColliders` the static geometry a simulation ran against. A recording is only replayable against the world it was recorded in, so storing the collider fingerprint beside a replay lets you refuse one recorded against a level that has since changed, before it plays back wrongly. The physics solver keeps its defaults stable for the same reason. Its elliptical friction model is more physically correct and is still opt-in, because switching it on changes every result and would invalidate fingerprints and replays that games have stored. ## Keeping what each tick produced ```ts /** Keep what each tick produced, so a replay can seek to any tick without simulating its way there. */ export function recordHeights(ticks: number): TickTrace { const trace = new TickTrace(1, ticks); const value = new Float32Array(1); for (let tick = 0; tick < ticks; tick += 1) { value[0] = swayAt(tick).x; trace.push(value); } return trace; } ``` Seeking in a replay would otherwise mean re-simulating every tick before the one you want. A `TickTrace` records the values you choose, per tick, once, and then answers any tick at once, which is what makes a replay scrubbable. ## Where the rest is Snapshots and rollback are in `@driftengine/network`, and the entity model's whole-world snapshots in `@driftengine/entities`, which [Entities](https://driftengine.dev/docs/simulation/entities) rewinds a pond with. A world larger than single precision can address keeps its simulation coordinates absolute and never rebases them, because a rebase changes floating-point results; [Coordinates](https://driftengine.dev/docs/concepts/coordinates) explains how rendering copes. --- # Coordinates and units Concepts. https://driftengine.dev/docs/concepts/coordinates Metres, Y up, which way the camera looks, how matrices are laid out, and how a world larger than single precision stays exact. ## The conventions - **Units are metres** and seconds. Physics gravity defaults to 9.81 metres per second squared, downward. - **Y is up.** The ground is the XZ plane. - **The camera looks toward negative Z at yaw 0.** Positive yaw turns right, toward positive X, and positive pitch looks up. With X to the right, Y up and the view down negative Z, the system is right-handed. - **Rotations are quaternions** on scene nodes and physics bodies, stored `x, y, z, w`. - **Matrices are column-major `Float32Array`s of sixteen**, the layout WebGPU, WebGL2 and gl-matrix all use. A translation is in elements 12, 13 and 14. - **Colours are RGB triples from 0 to 1**, written `[r, g, b]`, and linear: the light they reflect adds as light does. A light's colour may go above 1, which means brighter than white. A colour picked by eye is a display value, so it is written `srgbColor(r, g, b)`. How the shaded result maps to the screen is the `outputTransform` quality option, covered in [Render quality](https://driftengine.dev/docs/concepts/quality). ## Worlds bigger than a float A `Float32Array` holds about seven significant digits. Forty kilometres from the origin, a single precision coordinate can no longer tell two points a few millimetres apart, so vertices jitter and the camera shakes. Engines usually answer by shifting the origin under the player now and then. DriftEngine splits the problem in two, because a shift that touches the simulation changes its floating-point results, and a replay recorded before the shift stops matching one recorded after. **The simulation never rebases.** Its positions are absolute and kept in double precision, which is exact to well under a millimetre anywhere on a planet. **Rendering does, in whole cells.** The render origin is the minimum corner of the grid cell the camera is in, so it only moves when the camera crosses a cell boundary. An origin that followed the camera continuously would re-quantise every vertex every frame, and the world would shimmer in a different way. ```ts /** Cells are this many metres on a side. The render origin moves a whole cell at a time. */ const CELL = 256; /** The simulation's positions: absolute, in metres, in double precision. Never rebased. */ const player = new Float64Array([40_000_123.25, 12, -7_500_000.5]); const beacon = new Float64Array([40_000_180, 30, -7_500_040]); const origin = new Float64Array(3); const scratch = new Float32Array(3); /** Each frame: choose the origin, then hand the renderer only small numbers. */ export function placeForFrame(camera: Camera, beaconNode: SceneNode): void { renderOrigin(player[0], player[1], player[2], CELL, origin); // The camera sits behind and above the player, in render space. toRenderSpace(player[0], player[1] + 6, player[2] + 10, origin, scratch); camera.position[0] = scratch[0]; camera.position[1] = scratch[1]; camera.position[2] = scratch[2]; toRenderSpace(player[0], player[1], player[2], origin, scratch); camera.lookAt(scratch[0], scratch[1], scratch[2]); // Every drawn thing goes through the same subtraction, done in doubles before it narrows. toRenderSpace(beacon[0], beacon[1], beacon[2], origin, scratch); beaconNode.setPosition(scratch[0], scratch[1], scratch[2]); beaconNode.updateWorld(); } ``` `toRenderSpace` subtracts in double precision and only narrows the small result to single precision, which keeps the precision; narrowing first and then subtracting would already have lost it. `toWorldSpace` goes back, exactly. Three consequences are worth knowing before you meet them: - A view matrix is single precision, so it cannot hold an absolute position in a large world. Views are in render space, and anything that predicts where the camera will be, such as streaming, is told the origin and adds it back in double precision. - A navigation mesh is built and queried in render space for the same reason. - **Freezing is a simulation decision and unloading is a memory decision.** A grid cell outside the simulated radius freezes whether or not its contents are loaded, and only a frozen cell may be unloaded. If unloading caused freezing, the simulation would depend on how much memory a machine had, and two players would diverge. The cell grid, streaming cells in and out, and freezing and thawing them are covered in [Large worlds](https://driftengine.dev/docs/worlds/large-worlds), and drawing distant regions coarsely in [Hierarchical detail](https://driftengine.dev/docs/worlds/hierarchical-detail). --- # Render quality Concepts. https://driftengine.dev/docs/concepts/quality The quality profile a renderer is built with, what each group of options does and costs, the defaults that surprise people, and the dials that move per frame. Everything that decides how good a frame looks, and how much it costs, is in the quality profile passed to `createRenderer`. A profile is fixed for the renderer's life, because most options size GPU memory or decide which shader is compiled. To change one, build a new renderer; a settings screen does exactly that when the player presses apply. ```ts /** A desktop profile: a filmic tone curve, real brightness through the composite, and post effects. */ export const DESKTOP: RenderQualityOptions = { maxDevicePixelRatio: 2, outputTransform: 'aces', outputExposure: 1.4, screenEffects: true, hdrScene: true, sceneSamples: 4, bloom: 0.5, bloomThreshold: 1, ambientOcclusion: 0.6, directionalShadows: true, directionalShadowMapSize: 2048, pointShadows: true, }; /** A phone profile: fewer pixels, a smaller shadow map, and no full-frame post pass. */ export const PHONE: RenderQualityOptions = { maxDevicePixelRatio: 1.25, maxDrawingBufferPixels: 1280 * 720, outputTransform: 'aces', outputExposure: 1.4, screenEffects: false, directionalShadows: true, directionalShadowMapSize: 1024, pointShadows: false, }; export async function build(canvas: HTMLCanvasElement, phone: boolean) { return createRenderer(canvas, phone ? PHONE : DESKTOP); } ``` Every option has a default that means "off" or "the smallest correct thing", so a profile only names what it changes. The full list, with what each option costs, is in the reference under `RenderQuality`. This page groups them. ## The tone curve, first The default output transform is `'srgb'`: the renderer lights in linear values and encodes them for the screen at the end, as the display expects, so a model reads as it does in any other engine. It has no tone curve, so a channel above 1 clips on its own and a bright coloured light goes to white. **`'aces'` with an `outputExposure` rolls those highlights off**, and is what the examples use. `'none'` writes values as they are computed, which reads as dark and muddy unless every colour in the world was chosen under it; it was the default until 4.13.0, and a game made then says it. Every pass applies the transform where nothing after it will, and the clear colour with them, so every colour the renderer draws means the same thing. A colour picked by eye is a display value, so it goes through `srgbColor(r, g, b)`, and a mesh whose colours were picked by eye is built with `build({ colorSpace: 'srgb' })`; either gives back exactly the colour picked where a surface is lit at 1. Text, panels and the 2D layer take the screen encode and not the tone curve, so their colours come out exactly as picked under any transform, and `@driftengine/ui2d` decodes a theme's hex tokens for you. A light's intensity is an amount rather than a look, and stays as it is. ## Resolution - `maxDevicePixelRatio` caps how many pixels the drawing buffer gets per CSS pixel. On a phone it is the single largest cost in most frames. - `maxDrawingBufferPixels` caps the area, so a large window doesn't multiply the cost of every frame. The renderer is mostly fragment-bound, and on a display with vsync a frame that misses by a little runs at half the rate. - `ResolutionGovernor` adjusts the drawing-buffer scale from measured frame times while the game runs; `setMaxDrawingBufferPixels` is the dial it turns. ## Post-processing - `screenEffects` resolves the scene through an off-screen target, which every screen-space effect needs. Off, there is no post stage at all, and that is the honest low-end setting. - `sceneSamples: 4` multisamples that target. With `screenEffects` on and this at 1, there is no antialiasing at all. - `hdrScene` keeps brightness above 1 through to the end of the frame, in half floats, and grades once there. Bloom needs it, or something brighter than its threshold to find. - `bloom` and `bloomThreshold`: the threshold is in scene units, and 1 means "brighter than white". **The two only work as a pair**: without `hdrScene`, nothing is above 1, so lower the threshold. - `ambientOcclusion` and `ambientOcclusionRadius`: contact shading where surfaces meet. Needs `screenEffects`. - `cameraMotionBlur`, `depthOfField`, `temporalAa` and `orderIndependent`, each off by default. [Post-processing](https://driftengine.dev/docs/rendering/post-processing) covers them in depth. ## Shadows and lights - `directionalShadows` with `directionalShadowMapSize`, and the reach and slope limits beside them. - `pointShadows` with `pointShadowFaceSize` and the per-frame bake budgets. - `shadowFilterTaps`, the softening budget shared by both kinds. - `maxLights` and `maxAreaLights` size the lit shader. They are ceilings, and the renderer lowers them on its own when a device cannot link a shader that large. - `clusteredLights` lights each part of the view from the lights near it, instead of one set for the whole frame. Off by default. - `pointLightFalloff`: `'smooth'` ends exactly at a light's radius; `'inverseSquare'` is the physical law, windowed by the radius. ## Water, reflections and air `water`, `waterResolution` and `waterReflections` for the wave-simulated water; `planarReflections` and `reflectionProbeSize` for mirrors and baked reflections; `globalMediumSteps` and `lightVolumeSamples` for light in fog and dust. Each has a chapter in the Rendering section. ## What only WebGPU does `reconstruction` (DriftTR) and `indirectLight` (DriftRay) are quality options too, and the GPU-driven pipeline is a renderer option. All three are off by default and explained in [WebGPU and WebGL2](https://driftengine.dev/docs/concepts/backends). ## Culling and the frame's work - `cullDraws` skips a draw whose bounds are out of view. Off by default, because a mesh whose vertex shader displaces it, such as foliage in wind, is bigger than its bounds say, and culling it would remove something visible. - `occlusionCulling` sizes the occlusion buffer; see [The scene graph](https://driftengine.dev/docs/concepts/scene-graph). - `capabilityClamp` lets the renderer clamp a known-weak GPU; pass `false` when a player chose their settings. ## Shaders first needed mid-game A draw can need a shader the renderer has not compiled yet: a material that is two-sided, cut out or shades by a surface model asks for a variant that creating the mesh did not prepare. With `pipelineCompile: 'wait'`, the default, it is compiled where the draw asks, and the frame waits for it, from a few hundred milliseconds to several seconds on a phone. With `'skip'` the compile starts off the frame and the draw is left out until it lands, a few frames later, so nothing waits. Either way, a loading screen can prepare a scene: draw what the scene will use once, then `await renderer.ready()`, which waits for every compile started. Or prepare it without drawing: `prepareMesh(mesh, material)` and `prepareInstanced(batch, material)` compile every shader a draw of that mesh in that material will ask for, its surface model, its two-sided and cut-out variants and its lit switches, and `ready()` waits for those too. Under `'skip'` that is what keeps a figure brought on screen from missing its skin and hair for the frames they take. `{ translucent: true }` prepares the blended draws as well. Call them between frames. On WebGL2 only a surface model's program compiles at a draw, and `'skip'` helps there only where the browser offers parallel shader compiling, which ANGLE on OpenGL does and ANGLE on Vulkan does not. ## Three defaults that surprise people - **A lamp that won't glow.** Emissive light is switched by the environment's `nightFactor`; at 0, nothing glows whatever its emissive value. It is a switch, despite its name. - **Bloom that does nothing.** A threshold above anything the scene contains blooms nothing. See the pair above. - **Jagged edges with every effect on.** `screenEffects` takes the canvas's own antialiasing away; set `sceneSamples`. ## Dials that move per frame A few things are cheap to change while the game runs, and have setters on the renderer: ```ts /** The dials that may move every frame. Everything else is fixed when the renderer is built. */ export function cinematicMoment(renderer: RendererApi, intensity: number): void { renderer.setBloom(0.5 + intensity * 0.5); renderer.setOutputExposure(1.4 + intensity * 0.6); renderer.setCameraMotionBlur(intensity); renderer.setVignette(intensity * 0.4); } ``` `setDepthOfField`, `setColourGrade`, `setAutoExposure`, `setLocalExposure`, `setSpeedRush` and `setFrameVeil` are the others. Each only does something when the profile built the stage it drives. --- # The frame Concepts. https://driftengine.dev/docs/concepts/the-frame What happens between beginFrame and endFrame, in what order a game issues its work, where custom passes and compute fit, and how the GPU-driven path differs. DriftEngine draws in immediate mode. Each frame, your `render` callback issues verbs to the renderer in the order they should happen: shadows, the frame, the scene, the effects, the interface. The engine has no scene it walks on its own, and no list of objects it keeps between frames; what you issue is the frame. That keeps the order of every draw yours, and it is why the same engine draws a breakout game and a streamed city. ## A frame, in order The first game's frame is typical: ```ts function render(alpha: number, frameDt: number): void { // Input is sampled here, at the edge of the simulation: a step reads what this left behind. touch.tick(performance.now()); // Read here, not in simulate: while paused, simulate is not called at all. if (actions.consumePress('pause')) paused = !paused; if (!paused) clock += frameDt; placeEverything(alpha); const at = playerNode.position; follow(at[0], at[1], at[2], frameDt); // The shadow map covers 16 metres around the player, which is everything the camera sees. ENV.shadowDepthSpan = computeLightMatrix( ENV.directionalDir, at[0], at[1], at[2], 16, renderer.shadowMapSize, lightMatrix, ); renderer.beginShadowPass(lightMatrix, 'static'); renderer.drawShadowCasters(casters); renderer.endShadowPass(); renderer.beginFrame(SKY); renderer.bindMeshPass(camera, ENV); renderer.drawSceneCasters(casters); drawHud(); renderer.endFrame(); } ``` 1. **Shadow passes come first**, before the frame opens: `beginShadowPass`, `drawShadowCasters`, `endShadowPass` for the sun, and the point-light bakes the renderer budgets per frame. 2. **`beginFrame(clear)`** opens the frame. With `screenEffects` on, it opens the off-screen scene target the effects read from. 3. **`bindMeshPass(camera, environment)`** sets the camera and the light for the meshes that follow. Material state set before a pass does not carry into it. 4. **Opaque geometry**: `drawMesh`, `drawInstanced`, terrain, skinned meshes. 5. **The sky, water and effects**: `drawSky`, `drawWater`, particles and plumes, translucent meshes after the opaque ones they show through. 6. **Your own passes**, at the point you call `drawPass`. 7. **Overlays**: text and panels over the scene. 8. **`endFrame()`** resolves the scene target through the post stage, ambient occlusion, bloom, the tone curve and the grade, and presents. ## One list for two passes The same things usually need to be drawn into the shadow map and into the picture. A `ShadowCasters` function names them once, and both passes call it: `renderer.drawShadowCasters(casters)` for depth, and `renderer.drawSceneCasters(casters)` for colour with materials. A reflection or a probe face can call it a third time from another viewpoint. ## Custom passes A package or a game can add a pass of its own with `registerPass`, giving it a label, the frame attachments it reads, such as depth, and up to four callbacks: - `init` builds pipelines and buffers once, when the pass is registered; - `prepare` fills a target the pass owns, each frame, before the frame's own pass opens; - `draw` runs where you call `renderer.drawPass(handle)`; - `dispose` releases what `init` built. That is how the engine's own optional packages draw: the splat package's pass composes Gaussian splats into the scene through it. On WebGPU a pass may also dispatch compute: `registerCompute` takes a definition whose `dispatch` sets a pipeline and calls `dispatchWorkgroups`, and `renderer.computeSupported` says whether the backend has compute at all. [Custom passes and compute](https://driftengine.dev/docs/rendering/custom-passes) works through an example. ## The frame graph Inside the renderer, a frame's passes are scheduled from what each one declares it reads and writes. The `frameGraph` quality option routes the migrated verbs through that graph instead of issuing them directly, so a pass and its resources are ordered by data instead of by call position; it is opt-in while the migration completes. You keep issuing verbs in order either way. ## The GPU-driven path `createRenderer(canvas, quality, { pipeline: 'gpu-driven' })` builds a different renderer for very large scenes, on WebGPU only. Each frame the GPU culls instances against the view, chooses the level of detail each one has earned, culls clusters against a depth pyramid built that frame, compacts what survives into one indirect draw into a visibility buffer, and shades it with one dispatch per material. Draw-call counts stop being a cost. [The GPU-driven pipeline](https://driftengine.dev/docs/rendering/gpu-driven) covers it. --- # DriftScript in a game DriftScript. https://driftengine.dev/docs/scripting/driftscript What the engine's scripting language is for, what belongs in a script and what stays in TypeScript, and how the two share one game. DriftScript is the engine's scripting language, and a game on DriftEngine is written in two. The TypeScript holds the engine's objects: the renderer, the physics world, meshes, sounds, cameras, the page. The DriftScript holds the game's rules: the decisions and the numbers that make it this game and not another. The engine is built around that split, and every example in this manual that has behaviour keeps the behaviour in a `.drs` file beside its `main.ts`. (This chapter runs the `first-game` example at https://driftengine.dev/docs/scripting/driftscript.) [Your first game](https://driftengine.dev/docs/start/first-game) is the split at its smallest. The page moves the player and draws the arena; `round.drs` decides how long a round lasts, when an orb is close enough to take, and when the round is won or lost. ## Why a second language A rule needs three things that TypeScript in a browser does not give it. **Changing it while the game runs.** Saving a `.drs` file replaces its functions in the running page, and the records the game keeps its state in stay as they were: the player is where they were, the clock reads what it read. Most of what makes a game feel right is found by playing it. A jump that floats too long, an enemy that gives up too early, a round a few seconds too short: each is changed by saving the file with the game still going. The same change in TypeScript reloads the page and starts the game again. **Knowing what a rule touches.** Every engine function a script can call is declared with its effects: reading input, writing physics, playing a sound, reading the wall clock. The compiler works out from the calls which effects a function has. A function marked `@deterministic` that reaches input or the clock does not compile, and the error names the call, which is how a rule that has to replay the same way on every machine stays one. **Checked before it runs.** Types are strict, a value is never null unless its type says it may be absent, integer overflow is defined, a `match` has to cover every case, and units such as `ms`, `m` and `degC` are checked and then erased. A mistake is an error in the terminal, with a code and the line, before the page loads. ## What goes where | In DriftScript | In TypeScript | | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | Rules: when a round ends, what a pickup does, who an enemy chases | Anything that holds an engine object: the renderer, meshes, the physics world, sounds | | Tuning: speeds, durations, distances, weights, odds | The frame: `beginFrame`, the draws, `endFrame` | | Decisions: which shot to cut to, which animation to blend to, when to give up | Loading: models, textures, sounds, levels | | State machines, and the state they keep | The platform: the page, storage, the network, a desktop shell | | Per-entity behaviour, as systems over components | Wiring: the loop, and binding each script to what it needs | The test for a piece of code is one question: does it have to hold an engine object, or draw? If it does, it is TypeScript. If it does not, it is a rule, and it goes in a script, even a short one. A rule left in TypeScript is a rule tuned by reloading. ## How the two share a game ```drs // The clock, once a step. Every orb taken wins the round; the clock reaching zero first loses it. // Deterministic: the same round and the same step give the same answer on every machine, so a // recorded round replays exactly. Reading input or the wall clock here would not compile. @deterministic fn tick(round: mut Round, dt: f32) { if round.phase != Phase.Playing { return } round.remaining = round.remaining - dt if round.gathered == round.total { round.phase = Phase.Won } else if round.remaining <= 0 { round.remaining = 0 round.phase = Phase.Lost } } ``` A script keeps nothing of its own between calls. The game's state lives in records the page owns: `data Round` is declared in the script, the compiler makes a `createRound` for it, the page calls that once and passes the record to every rule. A rule changes the record it is handed; the page reads it to draw the HUD. Because the page holds the record, a save that replaces `tick` leaves the round exactly where it was. ```drs // The stick, the keys or a thumb on the screen, whichever is pushed furthest: a keyboard and a // touch screen at once never add up to more than one stick. fn steer(puck: mut Puck, actions: Actions, touch: Touch, dt: f32) { var sx = input.axisX(actions, "move") var sz = input.axisY(actions, "move") if puck.raw { sx = input.rawAxisX(actions, "move") sz = input.rawAxisY(actions, "move") } if math.abs(input.touchX(touch)) > math.abs(sx) { sx = input.touchX(touch) } if math.abs(input.touchY(touch)) > math.abs(sz) { sz = input.touchY(touch) } if puck.rest > 0 { puck.rest -= dt } let tapped = input.touchTap(touch) if (input.pressed(actions, "boost") || tapped) && puck.rest <= 0 { puck.boost = 0.5 puck.rest = 1.2 } var push = PUSH if puck.boost > 0 { push = PUSH * 2.6 puck.boost -= dt } puck.braking = input.down(actions, "brake") || input.touchHeld(touch) var drag = DRAG if puck.braking { drag = DRAG * 5 } puck.vx += (sx * push - puck.vx * drag) * dt puck.vz += (sz * push - puck.vz * drag) * dt puck.x += puck.vx * dt puck.z += puck.vz * dt } ``` A script reaches the engine through what it is given. The puck's rules read the player's controls through `input.axisX(actions, "move")`, where `actions` is the page's `ActionMap`, passed in as an argument. A script can use an engine object it is handed, and it cannot make one or find one: what a rule can touch is exactly what its caller gave it, which is what makes a rule safe to replace while the game runs. A few modules need something from the page as a whole, such as the entity world or the mixer, and the page gives those once, when it binds the script. ## Where to learn the language The language has a site of its own, [script.driftengine.dev](https://script.driftengine.dev/docs), with a guide whose every example compiles and runs in the page: values and types, records and enums, options and results, units, effects and capabilities. This section is about using it with the engine: - [Setting up scripts](https://driftengine.dev/docs/scripting/setting-up): the build, loading and binding, the services a host gives, and hot reload. - [Patterns](https://driftengine.dev/docs/scripting/patterns): how the examples divide the work, from a record the page owns to systems over components. - [What a script can reach](https://driftengine.dev/docs/scripting/reach): every engine module and function a script can import. - [Determinism, testing and shipping](https://driftengine.dev/docs/scripting/testing): what the annotations promise, testing a script with no page, and what reaches the bundle. --- # Setting up scripts DriftScript. https://driftengine.dev/docs/scripting/setting-up The build that compiles .drs files, loading and binding a script, the services a host gives it, calling it, and hot reload that keeps the game's state. A script goes through four steps between the file and the game: the bundler compiles it, the page loads it, the page binds it to the engine, and the page calls it. A fifth, hot reload, replaces its functions when the file is saved. Each is a few lines, and the starter project has all of them. ## The build ```ts import { fileURLToPath } from 'node:url'; import { driftScript } from 'driftscript/vite'; import { defineConfig } from 'vite'; export default defineConfig(({ command }) => ({ plugins: [ driftScript({ /* The engine's capabilities, as data: every `drift/*` function, its types and its effects. */ capabilities: fileURLToPath(import.meta.resolve('@driftengine/script/capabilities.json')), /* The engine modules a script in this game may import. Add one here when a script needs it; an import of a module not named is refused when the file compiles, naming the module. */ manifest: { name: 'my-game', provides: ['drift/random', 'drift/scene', 'drift/input'] }, /* `vite build` compiles for shipping: the editor's metadata stays out of the bundle. */ mode: command === 'build' ? 'production' : 'development', }), ], build: { target: 'es2022', /* Just above the engine's WebGPU renderer, one module of about 2,100 kB minified that loads only where WebGPU does. Vite warns past 500 kB by default; anything larger than the renderer still warns. */ chunkSizeWarningLimit: 2200, }, })); ``` DriftScript compiles at the bundler, so a `.drs` file is imported like any other module and needs no step of its own. The plugin reads two things. `capabilities` is the engine's description of every function a script can call, as data: its module, its signature and its effects. The compiler checks calls against it and infers effects from it. `manifest.provides` lists the engine modules this game's scripts may import, and an import of one not listed is refused when the file compiles, with the module named. List a module when a script first needs it, and the build says so if you forget. An error in any script stops the build and lists every error, not only the first, so a script that does not compile never ships. `mode` decides one thing: whether the editor's metadata rides along in the compiled module. The starter passes `production` for `vite build`, which leaves it out, and `development` while serving, which keeps it. A production build also refuses to run without `capabilities` and `manifest`, since without them `@deterministic` would be a promise nothing checked. [Installation](https://driftengine.dev/docs/start/installation#driftscript) has the two packages to install and the declaration TypeScript needs. ## Loading and binding ```ts /* * How fast the cube turns is a rule, and rules live in DriftScript: `spin.drs`. The bundler compiles * the file, `loadModule` makes a module of it, and `bindModule` gives it the engine capabilities it * imports. Saving the file while the page is open replaces its function in place. */ const spinModule = loadModule(spinScript as Record); const bound = bindModule(spinModule, {}); if (!bound.bound) throw new Error(bound.reason); const rules = spinModule.exports as unknown as { spinRate(time: number): number }; if (import.meta.hot) { import.meta.hot.accept('./spin.drs', (next) => { if (next !== undefined) patchModule(spinModule, next as Record); }); } ``` `loadModule` turns the compiled file into a module: its exports, and the metadata saying which engine modules it imports. A module is not runnable until it is bound. `bindModule(module, services)` fills every engine import with the engine's implementation and answers `{ bound: true }`, or `{ bound: false, reason }` with a sentence when it cannot, for instance when the script imports `drift/ecs` and no entity world was given. Check `bound` and stop: a script that half bound would fail later, at the first call into the module it is missing, in the middle of a frame. The examples share one helper for the two calls, with the services as its second argument: ```ts /** * Load a compiled `.drs` module and bind it. Most of the modules the examples import need no host; * `drift/navigation` needs the graph it routes over, which is what `services` is for. */ export function hostScript(compiled: unknown, services: HostServices = {}): DriftModule { const module = loadModule(compiled as Record); const bound = bindModule(module, services); if (!bound.bound) throw new Error(bound.reason); return module; } /** One of the module's exports, by name: a function, or the factory a `data` declaration makes. */ export function exported(module: DriftModule, name: string): T { const value = module.exports[name]; if (value === undefined) throw new Error(`the script exports no ${name}`); return value as T; } ``` ## What a host gives Most engine modules need nothing from the page. What each of their functions acts on, a physics world, an action map, a camera, arrives as an argument when the page calls the script. Eight need something from the page as a whole, given once, in `services`: | Module | `services` field | What it is | | ------------------ | ---------------- | ------------------------------------------------------------------------ | | `drift/ecs` | `entities` | The component registry and prefabs the script's entity declarations made | | `drift/audio` | `audio` | The audio graph, its sound registry, and a kick detector for music | | `drift/time` | `clocks` | The loop's fixed step, frame time, wall time and elapsed time | | `drift/navigation` | `navigation` | The places a world has and how they connect | | `drift/ai` | `ai` | The agents a script may ask about | | `drift/behavior` | `behavior` | What a behaviour tree's tick is handed | | `drift/chemistry` | `chemistry` | The chemistry world and its parcels | | `drift/xr` | `xr` | The session's head, controllers and hands | [What a script can reach](https://driftengine.dev/docs/scripting/reach) lists, for every module, whether it is bound from a service or from arguments, and every function in it. ## Calling a script ```ts const script = hostScript(puckScript); interface Puck { x: number; z: number; vx: number; vz: number; boost: number; braking: boolean; bumps: number; hit: number; raw: boolean; shake: boolean; } const puck = exported<() => Puck>(script, 'createPuck')(); type Drive = (puck: Puck, actions: ActionMap, touch: TouchControls, dt: number) => void; if (import.meta.hot) { import.meta.hot.accept('./puck.drs', (next) => { if (next !== undefined) patchModule(script, next as Record, { Puck: [puck] }); }); } ``` A compiled module's exports are its functions, and a `create` function for each `data` declaration, which builds a record with the declared defaults. TypeScript cannot see a `.drs` file's exports, so the page states their shape once, as an interface for each record and a type for each function, and casts. The record belongs to the page from then on: here `puck` is created once and passed to the script's `drive` every step. A value crosses as what the script compiled it to. A number, a string or a `bool` is itself, and a record is a plain object with its fields. A variant of an enum is `{ tag: 'Won' }`, so the first game's page reads `round.phase.tag`, and an option is `{ tag: 'some', value }` or `{ tag: 'none' }`, which is how the cinematic director says whether to cut. A page that hands a variant in takes it from the script's exports, as the weather page takes `Sky.Storm` from its module, and compares a variant by its tag: a save makes a new object for every variant, so the one the page kept is a different object with the same tag. An engine answer that is one of a few things arrives the same way, as a variant of an enum the engine declares, such as `ContactKind` or `MatterPhase`; [What a script can reach](https://driftengine.dev/docs/scripting/reach) lists them with their variants. Read a function through the module each time you call it, as `exported(script, 'drive')` does in this example and `rules.tick(...)` does in the first game. A save replaces the module's exports in place, so a reference read once at startup keeps calling the old function. ## Hot reload The `import.meta.hot` block in each example is the whole of it. When a `.drs` file is saved, Vite sends the newly compiled module, and `patchModule(script, next, records)` replaces the old module's functions with the new ones. `records` names the live records by their type, here `{ Puck: [puck] }`, so that a save which adds a field to `data Puck` gives the existing puck that field with its declared default and keeps every other value. The game carries on from where it was. A script that declares components and systems is reloaded the same way, and then registered again so the schedule picks up the new systems: ```ts /** * The script's components become stores, its prefabs become prefabs, and its systems become a * schedule. The registry and the world outlive every reload; the schedule is rebuilt on one. */ const pond = loadModule(pondScript as Record); const registry: ComponentRegistry = new Map(); const prefabs = new Map(); let registered = registerEntityModule(pond, registry); for (const prefab of registered.prefabs) prefabs.set(prefab.name, prefab); const bound = bindModule(pond, { entities: { components: registry, prefabs } }); if (!bound.bound) throw new Error(bound.reason); const world = new World(); let schedule = buildSchedule(registered.systems); if (import.meta.hot) { import.meta.hot.accept('./pond.drs', (next) => { if (next === undefined) return; patchModule(pond, next as Record); /* The stores are kept, so every fly and frog keeps its components; the systems are new. */ registered = registerEntityModule(pond, registry); for (const prefab of registered.prefabs) prefabs.set(prefab.name, prefab); schedule = buildSchedule(registered.systems); }); } ``` Only the `.drs` file reloads in place. A change to the TypeScript reloads the page, which is one more reason the rules belong in the script. ## When something is wrong A mistake in a script is reported where it is made, with a code, the line and a sentence: - **A compile error** (a type that does not fit, a field that does not exist, a `match` that misses a case) appears in the terminal and over the page, and the page keeps running the last version that compiled. - **A module the manifest does not provide** is refused when the file compiles, naming the module and the file that imported it. - **A service the page did not give** is refused by `bindModule`, naming the script and the engine module it needs. The codes are the language's, `DS` and four digits, and they stay the same from one version to the next, so an error can be searched for by its code. --- # Patterns DriftScript. https://driftengine.dev/docs/scripting/patterns How the examples split work between the page and its scripts, from a record the page owns to a rule that decides and systems over components. Every example in this manual that has behaviour keeps it in DriftScript, and they divide the work the same few ways. This page names each one and shows the example it comes from, so a new game can pick the shape before writing the first rule. ## A record the page owns ```drs // The lamp follows the right trigger while a session is running and the controller is tracked. A // headset taken off ends the session, and the lamp goes out with it. fn light(lamp: mut Lamp, dt: f32) { var want: f32 = 0 if xr.presenting() && xr.holding(Hand.Right) { want = xr.trigger(Hand.Right) } lamp.level = lamp.level + (want - lamp.level) * math.min(1, lamp.ease * dt) } ``` The commonest shape, and the one to start from. The script declares a `data` record and the functions that change it; the page creates the record once, keeps it, passes it in, and reads it back to draw. Here the XR example's lamp eases toward the right trigger, and the page sets the light's colour from `lamp.level` every frame. The record is the line between the two halves. Everything the rule needs to remember goes in it, so a function has nothing hidden to lose when a save replaces it, and everything the page needs to draw comes out of it, so the page never asks the script how it reached a number. When a record gains a field in a save, the live one gains it too, with its declared default. ## Deciding, and acting on the decision ```drs // A take-off cuts at once, across the line of travel and low, the shot that sells a gap; a landing // cuts to an orbit round it. Otherwise a shot holds its time, the tower is framed when the buggy // passes it, and a long shot gives way to the next in turn. Answers the shot to cut to, or `none` // to hold the one on screen. fn direct(director: mut Director, cam: Camera, airborne: bool, nearTower: bool) -> Shot? { let age = camera.shotAge(cam) var want = director.shot if airborne && !director.flying { want = Shot.LowWide } else if !airborne && director.flying { want = Shot.Orbit } else if age < director.least { want = director.shot } else if nearTower && director.shot != Shot.LookAt { want = Shot.LookAt } else if age > director.most { want = next(director.shot) } director.flying = airborne if want == director.shot { return none } director.shot = want director.cuts += 1 return some(want) } ``` The cinematic example's director decides which shot the camera cuts to and when. It answers a `Shot?`: `some` of the shot to cut to, a variant of its own `Shot` enum, or `none` to stay on the current one. The page holds a record for each variant and makes the cut with the camera rig it owns. The script never moves the camera. It reads one fact from it, `camera.shotAge(cam)`, through the rig the page passed in, and answers a question. This is the shape for anything with taste in it: which animation to blend to, which line a character says, when an enemy gives up a chase. The decision is the part tuned by watching, so it goes in the script. The doing needs the engine's objects, so it stays in the page: ```ts const script = hostScript(directorScript); /* A variant reaches the page as `{ tag }`, and an option as `{ tag: 'some', value }` or `none`. */ interface Director { shot: { tag: ShotName }; cuts: number; } const director = exported<() => Director>(script, 'createDirector')(); type Direct = ( director: Director, camera: CinematicCamera, airborne: boolean, nearTower: boolean, ) => { tag: 'none' } | { tag: 'some'; value: { tag: ShotName } }; if (import.meta.hot) { import.meta.hot.accept('./director.drs', (next) => { if (next !== undefined) { patchModule(script, next as Record, { Director: [director] }); } }); } ``` ## Engine objects as arguments A script cannot create an engine object or look one up. It uses the ones it is handed: - the puck's rules read the controls through the page's `ActionMap`, passed as `actions`; - the director reads the age of a shot from the page's camera rig, passed as `cam`; - the garden's autosave writes through the page's store, passed as `store`: ```drs data Autosave { // Seconds between autosaves, and since the last one. every: f32 = 5 since: f32 = 0 written: u32 = 0 // How many were held back because the one before had not landed. held: u32 = 0 } // The page offers the garden once a second and the script decides whether it is written. An // autosave waits while the last one is still on its way, so a slow server is never handed a queue. fn autosave(auto: mut Autosave, store: Store, garden: String, dt: f32) -> bool { auto.since = auto.since + dt if auto.since < auto.every { return false } if persistence.pendingSaves(store) > 0 { auto.held = auto.held + 1 return false } persistence.write(store, "driftengine.examples.saves.auto", garden) auto.since = 0 auto.written = auto.written + 1 return true } ``` The types (`Actions`, `Camera`, `Store`) are opaque in the script. It can pass one to the engine functions that take it and do nothing else with it. That is what makes a script safe to replace in a running game: everything a function can affect arrives through its own arguments, and the page decides what those are each time it calls. ## Services the page gives once Some engine modules act on something that belongs to the whole game, the entity world, the mixer, the navigation graph, and passing it to every call would be noise. The page gives those once, at bind, in `services`. The XR example hands `drift/xr` the session it reads; the audio example hands `drift/audio` its graph and sound registry; the entities and saves examples hand `drift/ecs` the component registry their script declared. [Setting up scripts](https://driftengine.dev/docs/scripting/setting-up#what-a-host-gives) lists all eight. ## Systems over components ```drs // Four times a second, each rested frog fixes on the nearest fly within its reach. system Hunt { reads Fly reads Position writes Frog update at 4Hz { for frog in query() { if frog.Frog.resting > 0 { continue } var best = frog.Frog.reach * frog.Frog.reach frog.Frog.target = none for fly in query() { let dx = fly.Position.x - frog.Position.x let dy = fly.Position.y - frog.Position.y let dz = fly.Position.z - frog.Position.z let distance = dx * dx + dy * dy + dz * dz if distance < best { best = distance frog.Frog.target = some(fly) } } } } } ``` When a rule applies to many things of one kind, frogs, flies, plants, it is a `system` over `component`s, declared in the script. A system says which components it reads and writes, how often it runs, and loops over a query; the engine's schedule runs the systems each step in an order their reads and writes allow. The page registers the script's components and systems once and steps the schedule, and it can read any component back to draw. [Entities](https://driftengine.dev/docs/simulation/entities) covers components, prefabs, systems and rewinding in full, and [Saves and preferences](https://driftengine.dev/docs/systems/saves) writes a whole world of them out and reads it back. ## Many small files A script is a module, and a game is better as several than as one. A `.drs` file can import another by a relative path (`import { start } from "./round"`), and anything else it imports is an engine or language module. A `data` record can extend another and stand in for it wherever the base is expected. Keep one file per subject: the round, the enemies, the pickups, the camera. A save then replaces one subject's rules and nothing else's, and each file's imports say exactly which engine modules that subject touches. ## What stays out of a script - **Drawing.** A script never calls the renderer. It decides what is drawn and the page draws it. - **Loading.** Models, textures, sounds and levels are loaded by the page, which hands the script what it needs once they exist. - **Anything that reads the wall clock or the input inside the fixed step.** Rules that run in the simulation see the step's time and the step's input, which the page passes in, so a recorded game replays. [Determinism, testing and shipping](https://driftengine.dev/docs/scripting/testing) has the annotation that enforces it. - **The platform.** Storage, the network and a desktop shell are the page's; a script reaches them only through what it is handed, as the garden reaches its save store. --- # What a script can reach DriftScript. https://driftengine.dev/docs/scripting/reach Every engine module a DriftScript file can import, what the host binds it from, and each function's signature and whether it is deterministic. A script reaches the engine only through the modules listed here, and only through the ones the game's manifest provides. Each function is declared with its signature, its effects and whether it is deterministic, which is what the compiler checks a call against and what `@deterministic` depends on. "Bound from arguments" means every function takes what it acts on as an argument the page passes in; "bound from `services.x`" means the page gives that once, to `bindModule` ([Setting up scripts](https://driftengine.dev/docs/scripting/setting-up#what-a-host-gives)). `std/math` and `std/time` are the language's own and need no host at all. The page links each module to the chapters whose examples import it. The language's own reference, types, records and the rest, is at [script.driftengine.dev](https://script.driftengine.dev/docs). 25 modules and 343 functions, written from `capabilities.json` by `npm run manual:sync`. | Module | Functions | Deterministic | Bound from | |---|---|---|---| | [`std/math`](#stdmath) | 13 | 13 | the language | | [`std/time`](#stdtime) | 3 | 3 | the language | | [`drift/2d`](#drift2d) | 12 | 7 | arguments | | [`drift/ai`](#driftai) | 9 | 7 | `services.ai` | | [`drift/animation`](#driftanimation) | 17 | 9 | arguments | | [`drift/audio`](#driftaudio) | 9 | 3 | `services.audio` | | [`drift/behavior`](#driftbehavior) | 8 | 4 | `services.behavior` | | [`drift/camera`](#driftcamera) | 2 | 1 | arguments | | [`drift/chemistry`](#driftchemistry) | 53 | 53 | `services.chemistry` | | [`drift/ecs`](#driftecs) | 17 | 11 | `services.entities` | | [`drift/editor`](#drifteditor) | 43 | 0 | arguments | | [`drift/events`](#driftevents) | 3 | 3 | arguments | | [`drift/input`](#driftinput) | 14 | 0 | arguments | | [`drift/navigation`](#driftnavigation) | 12 | 12 | `services.navigation` | | [`drift/network`](#driftnetwork) | 9 | 2 | arguments | | [`drift/persistence`](#driftpersistence) | 5 | 0 | arguments | | [`drift/physics`](#driftphysics) | 42 | 32 | arguments | | [`drift/random`](#driftrandom) | 3 | 3 | arguments | | [`drift/render`](#driftrender) | 10 | 0 | arguments | | [`drift/rollback`](#driftrollback) | 6 | 0 | arguments | | [`drift/scene`](#driftscene) | 11 | 8 | arguments | | [`drift/terrain`](#driftterrain) | 8 | 8 | arguments | | [`drift/time`](#drifttime) | 4 | 0 | `services.clocks` | | [`drift/ui`](#driftui) | 18 | 6 | arguments | | [`drift/xr`](#driftxr) | 12 | 0 | `services.xr` | ### std/math Part of the language: every script may import it and no host binds it. Effects: `pure`. Used by [Animation](https://driftengine.dev/docs/simulation/animation), [Characters](https://driftengine.dev/docs/simulation/characters), [Colour and motion](https://driftengine.dev/docs/rendering/colour-and-motion), [Entities](https://driftengine.dev/docs/simulation/entities), [Fog and weather](https://driftengine.dev/docs/rendering/fog-and-weather), [Hello world](https://driftengine.dev/docs/start/hello-world), [Input](https://driftengine.dev/docs/interface/input), [Large worlds](https://driftengine.dev/docs/worlds/large-worlds), [Light in the air](https://driftengine.dev/docs/rendering/light-in-the-air), [Navigation](https://driftengine.dev/docs/simulation/navigation), [Networking and rollback](https://driftengine.dev/docs/systems/networking), [Procedural solids](https://driftengine.dev/docs/worlds/procedural-solids), [Queries and colliders](https://driftengine.dev/docs/simulation/queries), [Recording and clips](https://driftengine.dev/docs/systems/recording), [Saves and preferences](https://driftengine.dev/docs/systems/saves), [Sound and music](https://driftengine.dev/docs/content/audio), [Sprites and tilemaps](https://driftengine.dev/docs/interface/sprites), [Terrain](https://driftengine.dev/docs/worlds/terrain), [Vehicles](https://driftengine.dev/docs/simulation/vehicles), [Wet surfaces](https://driftengine.dev/docs/rendering/wet-surfaces), [XR](https://driftengine.dev/docs/interface/xr). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `abs` | `fn(x: float) -> float` | yes | The magnitude of a number. | | `min` | `fn(a: float, b: float) -> float` | yes | The smaller of two numbers. | | `max` | `fn(a: float, b: float) -> float` | yes | The larger of two numbers. | | `clamp` | `fn(x: float, low: float, high: float) -> float` | yes | A number pinned between two bounds. | | `lerp` | `fn(a: float, b: float, t: float) -> float` | yes | A value between two others. | | `floor` | `fn(x: float) -> float` | yes | The largest whole number no greater than this. | | `ceil` | `fn(x: float) -> float` | yes | The smallest whole number no less than this. | | `round` | `fn(x: float) -> float` | yes | The nearest whole number, halves rounding up. | | `sqrt` | `fn(x: float) -> float` | yes | The square root. | | `sin` | `fn(radians: float) -> float` | yes | The sine of an angle in radians. | | `cos` | `fn(radians: float) -> float` | yes | The cosine of an angle in radians. | | `atan2` | `fn(y: float, x: float) -> float` | yes | The angle to a point, in radians. | | `exp` | `fn(x: float) -> float` | yes | Euler's number raised to this power. | ### std/time Part of the language: every script may import it and no host binds it. Effects: `pure`. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `seconds` | `fn(duration: float) -> float` | yes | A duration in seconds. | | `milliseconds` | `fn(duration: float) -> float` | yes | A duration in milliseconds, for formatting. | | `progress` | `fn(elapsed: float, total: float) -> float` | yes | How far through a duration something is, from 0 to 1. | ### drift/2d Bound always: what each function acts on arrives as an argument the host passes in. Effects: `scene.read`, `scene.write`. Used by [Sprites and tilemaps](https://driftengine.dev/docs/interface/sprites). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `sprite` | `fn(batch: SpriteBatch, texture: i32, x: f32, y: f32, w: f32, h: f32) -> void` | no | Put one quad in the batch, covering the whole of a texture. | | `tinted` | `fn(batch: SpriteBatch, texture: i32, x: f32, y: f32, w: f32, h: f32, r: f32, g: f32, b: f32, a: f32) -> void` | no | The same, multiplied by a colour picked for the screen: sRGB, 0 to 1, decoded to linear as a tint on a node is, with alpha kept as given. | | `frame` | `fn(batch: SpriteBatch, sheet: SpriteSheet, frame: i32, x: f32, y: f32, w: f32, h: f32) -> void` | no | Put one frame of a sheet in the batch. | | `named` | `fn(sheet: SpriteSheet, name: String) -> i32` | yes | The index a name has in a sheet, or -1. | | `frames` | `fn(sheet: SpriteSheet) -> i32` | yes | How many frames the sheet was cut into. | | `tilemap` | `fn(batch: SpriteBatch, map: Tilemap, sheet: SpriteSheet, x: f32, y: f32, w: f32, h: f32) -> i32` | no | Draw the tiles a view rectangle can see, and answer how many that was. | | `tile` | `fn(map: Tilemap, column: i32, row: i32) -> i32` | yes | The frame in a cell, or -1 for an empty one — including for a cell outside the map, which answers empty rather than another row. | | `setTile` | `fn(map: Tilemap, column: i32, row: i32, tile: i32) -> void` | no | Put a frame in a cell. | | `columns` | `fn(map: Tilemap) -> i32` | yes | How wide the map is, in cells. | | `rows` | `fn(map: Tilemap) -> i32` | yes | How tall the map is, in cells. | | `count` | `fn(batch: SpriteBatch) -> i32` | yes | How many quads are in the batch this frame. | | `dropped` | `fn(batch: SpriteBatch) -> i32` | yes | How many quads did not fit this frame. | ### drift/ai Bound when the host passes `services.ai` to `bindModule`; without it, an import of this module is refused at bind with a sentence saying so. Effects: `ai`, `navigation.read`, `navigation.write`, `network.read`, `pure`. Used by [Agents and behaviour](https://driftengine.dev/docs/simulation/agents). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `agent` | `fn(id: String) -> Agent?` | yes | Resolve an agent by the id the consumer registered it under. | | `wake` | `fn(agent: Agent, reason: String, priority: i32) -> void` | no | Tell an agent something happened. | | `consider` | `fn(agent: Agent) -> void` | no | Ask an agent to think, at ordinary priority. | | `intentId` | `fn(agent: Agent) -> String` | yes | What the agent is doing now. | | `degraded` | `fn(agent: Agent) -> bool` | yes | Whether the agent is over budget and running on its policy floor alone. | | `reachable` | `fn(agent: Agent, x: float, y: float, z: float) -> bool` | yes | Whether a route exists from where this agent is to a point, without writing one. | | `navigate` | `fn(agent: Agent, x: float, y: float, z: float) -> bool` | yes | Route this agent to a point. | | `path` | `fn(agent: Agent) -> NavPath?` | yes | The route object this agent follows, for `drift/navigation` to read or steer along. | | `deciding` | `fn(agent: Agent) -> bool` | yes | Whether this peer decides this agent’s model intents. | ### drift/animation Bound always: what each function acts on arrives as an argument the host passes in. Effects: `animation.write`, `pure`. Used by [Animation](https://driftengine.dev/docs/simulation/animation). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `pose` | `fn(jointCount: u32) -> Pose` | yes | A new pose at rest. | | `toRest` | `fn(pose: Pose, jointCount: u32) -> void` | no | Return a pose to rest without allocating another, which is what a state machine does on re-entry. | | `sample` | `fn(clip: Clip, at: f32, into: Pose) -> void` | no | Sample a clip at a time. | | `blend` | `fn(a: Pose, b: Pose, amount: f32, into: Pose) -> void` | no | Blend two poses into a third, clamped at the ends. | | `blendSet` | `fn(tree: Blend, parameter: String, value: f32) -> void` | no | Set one of a tree's parameters. | | `blendAt` | `fn(tree: Blend, at: f32, into: Pose) -> void` | no | Evaluate a whole tree into a pose. | | `reach` | `fn(skeleton: Skeleton, pose: Pose, root: u32, mid: u32, tip: u32, targetX: f32, targetY: f32, targetZ: f32, poleX: f32, poleY: f32, poleZ: f32) -> bool` | no | Bend a two-bone chain so its tip reaches a target. | | `motion` | `fn() -> Motion` | yes | A new root displacement, at zero. | | `rootMotion` | `fn(clip: Clip, joint: u32, from: f32, to: f32, into: Motion) -> void` | no | How far the root travelled between two times, in its own frame at `from`. | | `stripRoot` | `fn(clip: Clip, joint: u32, pose: Pose) -> void` | no | Pin a sampled pose's root to the clip's value at time zero, so the displacement `rootMotion` handed you is not also in the pose. | | `motionX` | `fn(motion: Motion) -> f32` | yes | The displacement along the root's own x axis at the earlier time. | | `motionY` | `fn(motion: Motion) -> f32` | yes | The displacement along the root's own y axis at the earlier time. | | `motionZ` | `fn(motion: Motion) -> f32` | yes | The displacement along the root's own z axis at the earlier time. | | `motionTurnX` | `fn(motion: Motion) -> f32` | yes | The x part of the rotation the root turned through, as a quaternion. | | `motionTurnY` | `fn(motion: Motion) -> f32` | yes | The y part of the rotation the root turned through, as a quaternion. | | `motionTurnZ` | `fn(motion: Motion) -> f32` | yes | The z part of the rotation the root turned through, as a quaternion. | | `motionTurnW` | `fn(motion: Motion) -> f32` | yes | The w part of the rotation the root turned through, as a quaternion. | ### drift/audio Bound when the host passes `services.audio` to `bindModule`; without it, an import of this module is refused at bind with a sentence saying so. Effects: `audio.write`, `nondeterministic`, `pure`. Used by [Sound and music](https://driftengine.dev/docs/content/audio). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `sound` | `fn(slot: String) -> Sound?` | yes | Resolve a sound slot. | | `play` | `fn(sound: Sound, gain: f32) -> void` | no | Play a resolved sound through the mix. | | `playPanned` | `fn(sound: Sound, gain: f32, pan: f32) -> void` | no | Play a resolved sound at a stereo position, -1 left to 1 right. | | `distanceGain` | `fn(distance: f32, radius: f32) -> f32` | yes | How loud something is at a distance, falling off to nothing at the radius. | | `stereoPan` | `fn(dx: f32, dz: f32, yaw: f32) -> f32` | yes | Where something sits in the stereo field, relative to a listener facing yaw. | | `duck` | `fn(bus: String, factor: f32, seconds: f32) -> bool` | no | Take a bus down to factor of its fader over seconds, 1 to bring it back, leaving the fader where the player set it. | | `fade` | `fn(bus: String, level: f32, seconds: f32) -> bool` | no | Move a bus's fader to level over seconds. | | `recall` | `fn(snapshot: String, seconds: f32) -> bool` | no | Crossfade every level, mute and send to a snapshot the host captured, over seconds. | | `pulse` | `fn() -> f32` | no | How hard the music is kicking, 0 to 1, spiking on each kick and falling back. | ### drift/behavior Bound when the host passes `services.behavior` to `bindModule`; without it, an import of this module is refused at bind with a sentence saying so. Effects: `behavior.read`, `behavior.write`. Used by [Agents and behaviour](https://driftengine.dev/docs/simulation/agents). `TreeStatus`: `Failure`, `Success`, `Running`. What a behaviour tree answered: it failed, it finished, or it is still going. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `tick` | `fn(behavior: Behavior) -> TreeStatus` | no | Advance the routine one tick, and answer whether it failed, finished or is still going. | | `step` | `fn(behavior: Behavior) -> TreeStatus` | no | Advance one tick even while paused, which is what a step button is. | | `restart` | `fn(behavior: Behavior) -> void` | no | Forget where the routine had got to, so the next tick starts it from the top. | | `setPaused` | `fn(behavior: Behavior, paused: bool) -> void` | no | Hold this one agent while the world carries on. | | `paused` | `fn(behavior: Behavior) -> bool` | yes | Whether it is being held. | | `status` | `fn(behavior: Behavior) -> TreeStatus` | yes | What the last tick answered, without ticking again. | | `doing` | `fn(behavior: Behavior, node: String) -> bool` | yes | Whether the agent is currently inside a node of this name — the routine's own answer, not a copy of it. | | `depth` | `fn(behavior: Behavior) -> i32` | yes | How deep in the tree the last tick reached. | ### drift/camera Bound always: what each function acts on arrives as an argument the host passes in. Effects: `scene.read`, `scene.write`. Used by [Cameras and cinematics](https://driftengine.dev/docs/interface/cameras). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `snap` | `fn(camera: Camera) -> void` | no | Jump the camera to where it is heading, skipping the ease. | | `shotAge` | `fn(camera: Camera) -> f32` | yes | Seconds since the current shot began. | ### drift/chemistry Bound when the host passes `services.chemistry` to `bindModule`; without it, an import of this module is refused at bind with a sentence saying so. Effects: `chemistry.read`, `chemistry.write`. Used by [Chemistry](https://driftengine.dev/docs/simulation/chemistry). `MatterPhase`: `Solid`, `Liquid`, `Gas`, `Mixed`. What a parcel is made of now. Mixed is a real answer: wet wood is a solid and a liquid at once. `ChemistryEvent`: `Ignited`, `Extinguished`, `SmoulderStart`, `SmoulderEnd`, `Consumed`, `Charred`, `StructuralFail`, `Frozen`, `Melted`, `Boiled`, `Condensed`, `Sublimed`, `Corroded`, `Calcined`, `Dissolved`, `Denatured`, `Browned`, `Caramelised`, `Fermented`, `Decayed`, `Exploded`. What happened to a parcel this tick: it caught, went out, melted, boiled and the rest. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `substance` | `fn(chem: Chemistry, id: String) -> Substance` | yes | A registered material by id, such as `oak`. | | `species` | `fn(chem: Chemistry, id: String) -> Species` | yes | A registered species by id, such as `O2`. | | `parcelCount` | `fn(chem: Chemistry) -> i32` | yes | How many parcel handles have ever been issued, live or not. | | `parcelAt` | `fn(chem: Chemistry, index: i32) -> i32` | yes | The handle at an index, for iteration. | | `alive` | `fn(chem: Chemistry, parcel: i32) -> bool` | yes | Whether a parcel still exists. | | `substanceOf` | `fn(chem: Chemistry, parcel: i32) -> Substance` | yes | What material a parcel is made of. | | `temperature` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | K, averaged over the whole parcel. | | `surfaceTemperature` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | K at the outermost shell — the one that decides whether it catches. | | `coreTemperature` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | K at the innermost shell — the one that decides whether it is cooked. | | `mass` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | How much of it there is, in kilograms. | | `speciesMass` | `fn(chem: Chemistry, parcel: i32, species: Species) -> f32` | yes | kg of one species held anywhere in this parcel. | | `moisture` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | kg of water per kg of dry matter — the dry basis, which is how moisture content is quoted. | | `charFraction` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | Share of the parcel that is now carbon, 0 to 1. | | `charDepth` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | Metres of char measured inward from the surface. | | `wetness` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | kg of liquid water on the surface, per square metre of it. | | `wettable` | `fn(chem: Chemistry, parcel: i32) -> bool` | yes | Whether this material can hold liquid water, which is what `wet` asks. | | `phase` | `fn(chem: Chemistry, parcel: i32) -> MatterPhase` | yes | Whether the parcel is solid, liquid, gas or mixed. | | `burning` | `fn(chem: Chemistry, parcel: i32) -> bool` | yes | Whether a flame stands over it. | | `smouldering` | `fn(chem: Chemistry, parcel: i32) -> bool` | yes | Whether it is glowing with no flame. | | `heatRelease` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | kW the reactions released last tick. | | `ignitionProgress` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | How close to catching, 0 to 1: the least satisfied of the five criteria. | | `structuralIntegrity` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | How much is still load-bearing, 1 down to 0, as char eats the thickness. | | `massFlux` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | kg/(m²·s) of gas leaving the surface — the smoke. | | `fuelFlux` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | The combustible share of that, which is what ignition is measured against. | | `positionX` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | Where the consumer said this parcel is. | | `positionY` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | Where the consumer said this parcel is. | | `positionZ` | `fn(chem: Chemistry, parcel: i32) -> f32` | yes | Where the consumer said this parcel is. | | `ambientTemperature` | `fn(chem: Chemistry, x: f32, y: f32, z: f32) -> f32` | yes | K of the air at a point. | | `oxygenFraction` | `fn(chem: Chemistry, x: f32, y: f32, z: f32) -> f32` | yes | Volume fraction of oxygen. | | `humidity` | `fn(chem: Chemistry, x: f32, y: f32, z: f32) -> f32` | yes | Relative humidity, 0 to 1. | | `pressure` | `fn(chem: Chemistry, x: f32, y: f32, z: f32) -> f32` | yes | Pascals. | | `concentration` | `fn(chem: Chemistry, species: Species, x: f32, y: f32, z: f32) -> f32` | yes | Parts per million by volume. | | `smokeDensity` | `fn(chem: Chemistry, x: f32, y: f32, z: f32) -> f32` | yes | Extinction coefficient, 1/m: what to attenuate a light along a ray by. | | `visibility` | `fn(chem: Chemistry, x: f32, y: f32, z: f32) -> f32` | yes | How far you can see, metres. | | `place` | `fn(chem: Chemistry, substance: Substance, kilograms: f32, area: f32, x: f32, y: f32, z: f32) -> i32` | yes | Put a new parcel in the world. | | `destroy` | `fn(chem: Chemistry, parcel: i32) -> void` | yes | Remove a parcel. | | `move` | `fn(chem: Chemistry, parcel: i32, x: f32, y: f32, z: f32) -> void` | yes | Where it is. | | `addHeat` | `fn(chem: Chemistry, parcel: i32, joules: f32) -> void` | yes | Joules into the surface shell, which is what a flux from outside does. | | `addHeatDeep` | `fn(chem: Chemistry, parcel: i32, shell: i32, joules: f32) -> void` | yes | Joules into a named shell. | | `setTemperature` | `fn(chem: Chemistry, parcel: i32, kelvin: f32) -> void` | yes | Set every shell to a temperature. | | `wet` | `fn(chem: Chemistry, parcel: i32, kilograms: f32) -> void` | yes | Pour water on it: real liquid water into the surface shell, where boiling will find it. | | `dry` | `fn(chem: Chemistry, parcel: i32, kilograms: f32) -> void` | yes | Take surface water away: a cloth, a hot dry pan, or wind. | | `ignite` | `fn(chem: Chemistry, parcel: i32) -> void` | yes | Supply a pilot for one tick. | | `douse` | `fn(chem: Chemistry, parcel: i32) -> void` | yes | Remove the pilot and the flame. | | `addSpecies` | `fn(chem: Chemistry, parcel: i32, species: Species, kilograms: f32) -> void` | yes | Salt the water, oil the pan, poison the well. | | `mix` | `fn(chem: Chemistry, from: i32, into: i32) -> void` | yes | Pour one parcel into another; the first is consumed. | | `release` | `fn(chem: Chemistry, species: Species, kilograms: f32, x: f32, y: f32, z: f32) -> void` | yes | A gas release into the air: a leak, a vent, an extinguisher. | | `addAirHeat` | `fn(chem: Chemistry, joules: f32, x: f32, y: f32, z: f32) -> void` | yes | Joules into a cell of air, which is what a heater does and what a fire does to the room. | | `eventCount` | `fn(chem: Chemistry) -> i32` | yes | Events this tick. | | `eventKind` | `fn(chem: Chemistry, index: i32) -> ChemistryEvent` | yes | What happened in one of this tick’s events. | | `eventParcel` | `fn(chem: Chemistry, index: i32) -> i32` | yes | Which parcel it happened to. | | `eventSpecies` | `fn(chem: Chemistry, index: i32) -> i32` | yes | Which species, or -1 where the kind does not name one. | | `eventValue` | `fn(chem: Chemistry, index: i32) -> f32` | yes | The kind's own quantity. | ### drift/ecs Bound when the host passes `services.entities` to `bindModule`; without it, an import of this module is refused at bind with a sentence saying so. Effects: `ecs.read`, `ecs.write`. Used by [Entities](https://driftengine.dev/docs/simulation/entities), [Saves and preferences](https://driftengine.dev/docs/systems/saves). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `create` | `fn(world: World) -> Entity` | no | A fresh entity with nothing on it. | | `destroy` | `fn(world: World, entity: Entity) -> bool` | no | Remove an entity and every component it had. | | `alive` | `fn(world: World, entity: Entity) -> bool` | yes | Whether this handle still names a live entity. | | `has` | `fn(world: World, entity: Entity, component: String) -> bool` | yes | Whether an entity carries a component. | | `attach` | `fn(world: World, entity: Entity, component: String) -> void` | no | Give an entity a component, every field at the zero for its type. | | `detach` | `fn(world: World, entity: Entity, component: String) -> bool` | no | Take a component away. | | `read` | `fn(world: World, entity: Entity, component: String, field: String) -> f64` | yes | One numeric field. | | `write` | `fn(world: World, entity: Entity, component: String, field: String, value: f64) -> void` | no | Set one numeric field. | | `count` | `fn(world: World, component: String) -> u32` | yes | How many entities carry a component. | | `at` | `fn(world: World, component: String, index: u32) -> Entity` | yes | The nth entity carrying a component. | | `findNearest` | `fn(world: World, component: String, fieldX: String, fieldY: String, fieldZ: String, x: float, y: float, z: float, radius: float) -> bool` | yes | Whether any entity carrying a component has position fields putting it within a radius, and the search `nearest` then reads. | | `nearest` | `fn(world: World) -> Entity` | yes | The entity the last `findNearest` on this world found. | | `instantiate` | `fn(world: World, prefab: String) -> Entity` | no | Make an entity from a prefab, with every component it names. | | `query` | `fn(world: World, a: String, b: String, c: String, d: String) -> Cursor` | yes | Open a walk over everything carrying these components. | | `without` | `fn(cursor: Cursor, component: String) -> void` | yes | Narrow an open walk to entities that do **not** carry a component. | | `next` | `fn(cursor: Cursor) -> Entity` | yes | The next entity, or a **negative** number when the walk is done — which also gives the cursor back. | | `view` | `fn(world: World, component: String, forWriting: bool) -> View` | yes | A component’s live columns. | ### drift/editor Bound always: what each function acts on arrives as an argument the host passes in. Effects: `editor`. `GizmoMode`: `Translate`, `Rotate`, `Scale`. Which tool a gizmo is: it moves, turns or scales. `GizmoSpace`: `World`, `Local`. Which axes a gizmo’s handles point along: the world’s or the object’s own. `GizmoHandle`: `None`, `TranslateX`, `TranslateY`, `TranslateZ`, `TranslateYZ`, `TranslateZX`, `TranslateXY`, `RotateX`, `RotateY`, `RotateZ`, `ScaleX`, `ScaleY`, `ScaleZ`, `ScaleUniform`. Which handle the pointer is over, or `None`. `EditorMode`: `Edit`, `Play`, `Paused`. Whether the editor is editing, playing the world, or paused part way through playing it. `FieldKind`: `Number`, `Integer`, `Boolean`, `Text`, `Entity`, `Enum`. How an inspector field is shown, taken from the type it was declared with. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `translateMode` | `fn(gizmo: Gizmo) -> void` | no | Make this an arrow gizmo, which moves what it is on. | | `rotateMode` | `fn(gizmo: Gizmo) -> void` | no | Make this a ring gizmo, which turns what it is on. | | `scaleMode` | `fn(gizmo: Gizmo) -> void` | no | Make this a scale gizmo. | | `gizmoMode` | `fn(gizmo: Gizmo) -> GizmoMode` | no | Which of the three the gizmo is: translate, rotate or scale. | | `worldSpace` | `fn(gizmo: Gizmo) -> void` | no | Point the handles along the world axes. | | `localSpace` | `fn(gizmo: Gizmo) -> void` | no | Point the handles along the object’s own axes. | | `space` | `fn(gizmo: Gizmo) -> GizmoSpace` | no | Which the handles are pointing along: the world or the object. | | `size` | `fn(gizmo: Gizmo) -> f32` | no | How big the gizmo is in metres. | | `setSize` | `fn(gizmo: Gizmo, metres: f32) -> void` | no | Set how big the gizmo is in metres. | | `hovered` | `fn(gizmo: Gizmo) -> GizmoHandle` | no | What the pointer is over: `None`, or a handle such as `TranslateX`, `TranslateYZ`, `RotateY` or `ScaleUniform`. | | `dragging` | `fn(gizmo: Gizmo) -> bool` | no | Whether a drag is running. | | `dragAngle` | `fn(gizmo: Gizmo) -> f32` | no | How far a rotation drag has turned, in radians, signed and past a full turn if it went that far. | | `positionX` | `fn(gizmo: Gizmo) -> f32` | no | Where the thing being edited is, along x. | | `positionY` | `fn(gizmo: Gizmo) -> f32` | no | The same, along y. | | `positionZ` | `fn(gizmo: Gizmo) -> f32` | no | The same, along z. | | `setPosition` | `fn(gizmo: Gizmo, x: f32, y: f32, z: f32) -> void` | no | Put the gizmo, and the transform it is editing, somewhere. | | `scaleX` | `fn(gizmo: Gizmo) -> f32` | no | How much the thing being edited is scaled, along x. | | `scaleY` | `fn(gizmo: Gizmo) -> f32` | no | The same, along y. | | `scaleZ` | `fn(gizmo: Gizmo) -> f32` | no | The same, along z. | | `rotationX` | `fn(gizmo: Gizmo) -> f32` | no | The orientation being edited, as a quaternion: x. | | `rotationY` | `fn(gizmo: Gizmo) -> f32` | no | The same: y. | | `rotationZ` | `fn(gizmo: Gizmo) -> f32` | no | The same: z. | | `rotationW` | `fn(gizmo: Gizmo) -> f32` | no | The same: w. | | `mode` | `fn(editor: Editor) -> EditorMode` | no | What the editor is doing: editing, playing or paused. | | `playing` | `fn(editor: Editor) -> bool` | no | Whether the world is advancing. | | `play` | `fn(editor: Editor) -> bool` | no | Start playing, taking a snapshot of the world first so `stop` can put it back. | | `pause` | `fn(editor: Editor) -> void` | no | Hold the world where it is. | | `step` | `fn(editor: Editor) -> void` | no | Advance exactly one fixed tick, then hold. | | `stop` | `fn(editor: Editor) -> bool` | no | Leave play and put the world back as it was. | | `rowCount` | `fn(editor: Editor) -> i32` | no | How many rows the tree showed at its last rebuild. | | `rebuildTree` | `fn(editor: Editor, root: Node) -> void` | no | Walk a node and everything under it into rows, honouring which branches are collapsed. | | `rowName` | `fn(editor: Editor, row: i32) -> String` | no | What the node on a row is called, or "" for a row that does not exist. | | `rowDepth` | `fn(editor: Editor, row: i32) -> i32` | no | How deep a row sits, with the root at zero. | | `rowExpanded` | `fn(editor: Editor, row: i32) -> bool` | no | Whether a row is showing its children. | | `toggleRow` | `fn(editor: Editor, row: i32) -> void` | no | Open a closed row or close an open one. | | `selectRow` | `fn(editor: Editor, row: i32) -> void` | no | Select the node on a row, which points the gizmo at it. | | `selectedRow` | `fn(editor: Editor) -> i32` | no | Which row is selected, or minus one. | | `fieldCount` | `fn(editor: Editor) -> i32` | no | How many fields the inspector is showing. | | `fieldLabel` | `fn(editor: Editor, field: i32) -> String` | no | A field’s name as it was declared, or "" for a field that does not exist. | | `fieldGroup` | `fn(editor: Editor, field: i32) -> String` | no | What a field belongs to: a component’s name, or "transform" for a node. | | `fieldKind` | `fn(editor: Editor, field: i32) -> FieldKind` | no | How to show a field: a number, an integer, a boolean, text, an entity or an enum. | | `fieldNumber` | `fn(editor: Editor, field: i32) -> f32` | no | A field’s value as a number. | | `setFieldNumber` | `fn(editor: Editor, field: i32, value: f32) -> bool` | no | Write a number into a field. | ### drift/events Bound always: what each function acts on arrives as an argument the host passes in. Effects: `pure`. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `push` | `fn(queue: Queue, id: String, priority: f32, holdFor: f32) -> void` | yes | Queue a message by identity. | | `current` | `fn(queue: Queue) -> String?` | yes | The id of the message showing now, if any. | | `clear` | `fn(queue: Queue) -> void` | yes | Drop everything queued. | ### drift/input Bound always: what each function acts on arrives as an argument the host passes in. Effects: `host`, `input.read`. Used by [Characters](https://driftengine.dev/docs/simulation/characters), [Input](https://driftengine.dev/docs/interface/input), [Sprites and tilemaps](https://driftengine.dev/docs/interface/sprites), [Vehicles](https://driftengine.dev/docs/simulation/vehicles). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `down` | `fn(actions: Actions, action: String) -> bool` | no | Whether an action is held. | | `pressed` | `fn(actions: Actions, action: String) -> bool` | no | Whether an action went down this frame. | | `axisX` | `fn(actions: Actions, action: String) -> f32` | no | A directional action's horizontal component, shortened to the rim with the vertical one so a keyboard diagonal is not faster than a straight line. | | `axisY` | `fn(actions: Actions, action: String) -> f32` | no | A directional action's vertical component, shortened to the rim with the horizontal one. | | `rawAxisX` | `fn(actions: Actions, action: String) -> f32` | no | An action's horizontal axis on its own, not shortened against the vertical one. | | `rawAxisY` | `fn(actions: Actions, action: String) -> f32` | no | An action's vertical axis on its own, not shortened against the horizontal one. | | `canRumble` | `fn(actions: Actions) -> bool` | no | Whether the pad these actions read has motors this browser can drive. | | `rumble` | `fn(actions: Actions, durationMs: f32, strong: f32, weak: f32) -> bool` | no | Rumble for a duration in milliseconds, at two magnitudes in [0, 1]: `strong` is the low-frequency motor and `weak` the high-frequency one. | | `stopRumble` | `fn(actions: Actions) -> bool` | no | Stop whatever that pad is playing. | | `touchX` | `fn(touch: Touch) -> f32` | no | The touch stick's horizontal, -1 to 1, 0 while no thumb is on it. | | `touchY` | `fn(touch: Touch) -> f32` | no | The touch stick's vertical, -1 to 1, up negative as a gamepad stick's is. | | `touchHeld` | `fn(touch: Touch) -> bool` | no | Whether a thumb is held still on the action side of the screen: the held form of the primary. | | `touchTap` | `fn(touch: Touch) -> bool` | no | Whether the action side was tapped since this was last asked. | | `touchSlide` | `fn(touch: Touch) -> bool` | no | Whether a downward flick on the action side is being held: the secondary, a slide or a crouch. | ### drift/navigation Bound when the host passes `services.navigation` to `bindModule`; without it, an import of this module is refused at bind with a sentence saying so. Effects: `navigation.read`, `navigation.write`. Used by [Navigation](https://driftengine.dev/docs/simulation/navigation). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `nearest` | `fn(graph: NavGraph, x: float, y: float, z: float) -> i32` | yes | The node nearest a place, or -1 where the graph has none. | | `nearestWithin` | `fn(graph: NavGraph, x: float, y: float, z: float, maxDistance: float) -> i32` | yes | The nearest node within a distance, or -1. | | `route` | `fn(path: NavPath, graph: NavGraph, fromX: float, fromY: float, fromZ: float, toX: float, toY: float, toZ: float) -> bool` | yes | Path from one place to another, storing the route. | | `routeBetween` | `fn(path: NavPath, graph: NavGraph, from: i32, to: i32) -> bool` | yes | The same, between two nodes you already have. | | `path` | `fn(agent: Entity) -> NavPath` | yes | The route this agent is following, kept by the host between steps. | | `clear` | `fn(path: NavPath) -> void` | yes | Forget the route. | | `following` | `fn(path: NavPath) -> bool` | yes | Whether there is a route to follow. | | `steerX` | `fn(path: NavPath, x: float, y: float, z: float) -> float` | yes | Where a walker at this place should aim, along x. | | `steerY` | `fn(path: NavPath, x: float, y: float, z: float) -> float` | yes | The same aim point, along y. | | `steerZ` | `fn(path: NavPath, x: float, y: float, z: float) -> float` | yes | The same aim point, along z. | | `remaining` | `fn(path: NavPath, x: float, y: float, z: float) -> float` | yes | How far is left, following the path rather than as the crow flies. | | `arrived` | `fn(path: NavPath, x: float, y: float, z: float) -> bool` | yes | Whether the walker is there. | ### drift/network Bound always: what each function acts on arrives as an argument the host passes in. Effects: `network.read`, `network.write`, `nondeterministic`. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `self` | `fn(session: Session) -> i32` | yes | Which participant this peer is. | | `authority` | `fn(session: Session) -> bool` | yes | Whether this peer’s world is the authoritative one. | | `participants` | `fn(session: Session) -> i32` | no | How many participants the session holds. | | `confirmed` | `fn(session: Session) -> i32` | no | The highest tick every participant’s input has arrived for, or -1. | | `halted` | `fn(session: Session) -> bool` | no | Whether the session has stopped, because an input arrived too late to apply or two peers computed different worlds. | | `haltReason` | `fn(session: Session) -> String` | no | Why it halted, as a sentence, or an empty string. | | `slots` | `fn(session: Session) -> i32` | no | How many replicated scalars each participant has. | | `replicated` | `fn(session: Session, participant: i32, slot: i32) -> f32` | no | Read a participant’s published scalar. | | `replicate` | `fn(session: Session, slot: i32, value: f32) -> void` | no | Publish a value in one of this peer’s slots. | ### drift/persistence Bound always: what each function acts on arrives as an argument the host passes in. Effects: `persistence.read`, `persistence.write`. Used by [Saves and preferences](https://driftengine.dev/docs/systems/saves). `SaveStatus`: `Idle`, `Pending`, `Saving`, `Failed`. Whether a store’s writes have landed: idle, waiting to send, sending, or failed. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `read` | `fn(store: Store, key: String) -> String?` | no | What is stored under a key. | | `write` | `fn(store: Store, key: String, value: String) -> void` | no | Store a value under a key. | | `remove` | `fn(store: Store, key: String) -> void` | no | Forget a key. | | `saveStatus` | `fn(store: Store) -> SaveStatus` | no | Whether writes have landed: idle, pending, saving or failed. | | `pendingSaves` | `fn(store: Store) -> u32` | no | How many keys are waiting to reach the backend. | ### drift/physics Bound always: what each function acts on arrives as an argument the host passes in. Effects: `physics.read`, `physics.write`. Used by [Queries and colliders](https://driftengine.dev/docs/simulation/queries), [Rigid bodies](https://driftengine.dev/docs/simulation/rigid-bodies). `ContactKind`: `Enter`, `Stay`, `Exit`. Whether two bodies began touching this step, are still touching, or have parted. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `colliderCount` | `fn(colliders: Colliders) -> u32` | yes | How many colliders a set holds. | | `colliderCapacity` | `fn(colliders: Colliders) -> u32` | yes | How many slots the set has allocated, live or not. | | `colliderBytes` | `fn(colliders: Colliders) -> u32` | yes | What the set costs in memory, in bytes. | | `beginColliderGroup` | `fn(colliders: Colliders) -> void` | no | Open a group. | | `addColliderBox` | `fn(colliders: Colliders, cx: f32, cy: f32, cz: f32, hx: f32, hy: f32, hz: f32) -> void` | no | A box in the open group, by centre and half-extents — the same numbers a mesh builder takes, so nothing is authored twice. | | `endColliderGroup` | `fn(colliders: Colliders) -> u32` | no | Put the open group into the set and return the handle that drops it again. | | `removeColliderGroup` | `fn(colliders: Colliders, group: u32) -> void` | no | Drop a group and everything in it. | | `anyWithin` | `fn(colliders: Colliders, x: f32, y: f32, z: f32, radius: f32) -> bool` | yes | Whether any collider overlaps the *box* around a sphere. | | `nearestWithin` | `fn(colliders: Colliders, x: f32, y: f32, z: f32, radius: f32) -> bool` | yes | Find the closest collider within a radius and record it. | | `nearCollider` | `fn(colliders: Colliders) -> i32` | yes | The collider the last `nearestWithin` on this set found, or −1. | | `nearX` | `fn(colliders: Colliders) -> f32` | yes | The closest point on that collider’s bounds, along x — the point on the wall rather than the wall’s centre. | | `nearY` | `fn(colliders: Colliders) -> f32` | yes | The closest point on that collider’s bounds, along y. | | `nearZ` | `fn(colliders: Colliders) -> f32` | yes | The closest point on that collider’s bounds, along z. | | `nearDistance` | `fn(colliders: Colliders) -> f32` | yes | How far that collider’s bounds are, in metres. | | `bodyCount` | `fn(world: PhysicsWorld) -> i32` | yes | How many bodies the world holds. | | `bodyX` | `fn(world: PhysicsWorld, body: i32) -> f32` | yes | A body's world position along x. | | `bodyY` | `fn(world: PhysicsWorld, body: i32) -> f32` | yes | A body's world position along y. | | `bodyZ` | `fn(world: PhysicsWorld, body: i32) -> f32` | yes | A body's world position along z. | | `bodyVelX` | `fn(world: PhysicsWorld, body: i32) -> f32` | yes | A body's velocity along x, in metres per second. | | `bodyVelY` | `fn(world: PhysicsWorld, body: i32) -> f32` | yes | A body's velocity along y, in metres per second. | | `bodyVelZ` | `fn(world: PhysicsWorld, body: i32) -> f32` | yes | A body's velocity along z, in metres per second. | | `bodyMass` | `fn(world: PhysicsWorld, body: i32) -> f32` | yes | A body's mass in kilograms, or zero where it has none because it is static or kinematic. | | `sleeping` | `fn(world: PhysicsWorld, body: i32) -> bool` | yes | Whether a body has been still long enough to stop being solved. | | `raycast` | `fn(world: PhysicsWorld, x: f32, y: f32, z: f32, dx: f32, dy: f32, dz: f32, maxDistance: f32, mask: i32) -> bool` | yes | Cast a ray and record what it hit. | | `hitBody` | `fn(world: PhysicsWorld) -> i32` | yes | The body the last `raycast` on this world found, or −1. | | `hitX` | `fn(world: PhysicsWorld) -> f32` | yes | Where the last raycast struck, along x. | | `hitY` | `fn(world: PhysicsWorld) -> f32` | yes | Where the last raycast struck, along y. | | `hitZ` | `fn(world: PhysicsWorld) -> f32` | yes | Where the last raycast struck, along z. | | `hitNormalX` | `fn(world: PhysicsWorld) -> f32` | yes | The surface normal the last raycast struck, along x. | | `hitNormalY` | `fn(world: PhysicsWorld) -> f32` | yes | The surface normal the last raycast struck, along y. | | `hitNormalZ` | `fn(world: PhysicsWorld) -> f32` | yes | The surface normal the last raycast struck, along z. | | `hitFraction` | `fn(world: PhysicsWorld) -> f32` | yes | How far along the ray the last hit was, from 0 to 1. | | `contactCount` | `fn(world: PhysicsWorld) -> i32` | yes | How many contact events the last step produced. | | `contactKind` | `fn(world: PhysicsWorld, index: i32) -> ContactKind` | yes | An event's kind: the two bodies began touching, are still touching, or have parted. | | `contactA` | `fn(world: PhysicsWorld, index: i32) -> i32` | yes | The lower-indexed body of a contact event. | | `contactB` | `fn(world: PhysicsWorld, index: i32) -> i32` | yes | The higher-indexed body of a contact event. | | `applyImpulse` | `fn(world: PhysicsWorld, body: i32, px: f32, py: f32, pz: f32, atX: f32, atY: f32, atZ: f32) -> void` | no | Apply an impulse at a world point. | | `applyForce` | `fn(world: PhysicsWorld, body: i32, fx: f32, fy: f32, fz: f32, dt: f32, atX: f32, atY: f32, atZ: f32) -> void` | no | A force applied for one step, which is an impulse of force times dt. | | `setVelocity` | `fn(world: PhysicsWorld, body: i32, vx: f32, vy: f32, vz: f32) -> void` | no | Set a body's velocity outright, waking its island. | | `setPosition` | `fn(world: PhysicsWorld, body: i32, x: f32, y: f32, z: f32) -> void` | no | Move a body outright. | | `wake` | `fn(world: PhysicsWorld, body: i32) -> void` | no | Wake a body and everything sharing its island, because a sleeping neighbour would settle it again. | | `setGravity` | `fn(world: PhysicsWorld, x: f32, y: f32, z: f32) -> void` | no | The world's gravity, in metres per second squared. | ### drift/random Bound always: what each function acts on arrives as an argument the host passes in. Effects: `pure`. Used by [Entities](https://driftengine.dev/docs/simulation/entities), [Fog and weather](https://driftengine.dev/docs/rendering/fog-and-weather), [Large worlds](https://driftengine.dev/docs/worlds/large-worlds), [Navigation](https://driftengine.dev/docs/simulation/navigation), [Rigid bodies](https://driftengine.dev/docs/simulation/rigid-bodies), [Saves and preferences](https://driftengine.dev/docs/systems/saves), [Wet surfaces](https://driftengine.dev/docs/rendering/wet-surfaces), [Worlds from a kit](https://driftengine.dev/docs/worlds/worlds-from-a-kit), [Writable textures](https://driftengine.dev/docs/worlds/writable-textures). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `unit` | `fn(seed: u32) -> f32` | yes | A value from 0 to 1 for a seed. | | `range` | `fn(seed: u32, low: f32, high: f32) -> f32` | yes | A value between two bounds for a seed. | | `index` | `fn(seed: u32, count: u32) -> u32` | yes | An index into a collection of `count` items. | ### drift/render Bound always: what each function acts on arrives as an argument the host passes in. Effects: `scene.write`. Used by [Colour and motion](https://driftengine.dev/docs/rendering/colour-and-motion), [Light in the air](https://driftengine.dev/docs/rendering/light-in-the-air). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `bloom` | `fn(renderer: Renderer, scale: f32) -> void` | no | How much of the frame's bloom ceiling to take, 0 to 1. | | `bloomAbove` | `fn(renderer: Renderer, scale: f32, threshold: f32) -> void` | no | How much of the bloom ceiling to take, 0 to 1, and how bright a pixel must be before it blooms, in scene units, above 0. | | `exposure` | `fn(renderer: Renderer, stops: f32) -> void` | no | How far this frame is scaled into the tone curve, above 0. | | `filmic` | `fn(renderer: Renderer, slope: f32, toe: f32, shoulder: f32, blackClip: f32, whiteClip: f32) -> void` | no | The `filmic` output transform's curve, held until changed: the straight segment's slope through mid grey, how much of the curve the toe and the shoulder take (0 to 1), and how far black and white clip past their ends (0 to 1). | | `motionBlur` | `fn(renderer: Renderer, scale: f32) -> void` | no | How much of the camera motion blur ceiling this frame takes, 0 to 1. | | `speedBlur` | `fn(renderer: Renderer, strength: f32) -> void` | no | How much speed blur the frame resolves with, 0 to 1. | | `focus` | `fn(renderer: Renderer, distance: f32, range: f32, scale: f32) -> void` | no | Where this frame's lens is focused and how deep the sharp zone is, in metres, and how much of the depth-of-field ceiling to take, 0 to 1. | | `occlusionFade` | `fn(renderer: Renderer, distance: f32, radius: f32) -> void` | no | Where ambient occlusion fades out with distance: whole up to `distance` metres from the eye and gone `radius` metres past it, so far scenery and a distant sky are not shaded in rings that follow the depth buffer. | | `medium` | `fn(renderer: Renderer, density: f32, albedo: f32, anisotropy: f32, maxDistance: f32) -> void` | no | How thick the air is: a medium filling the whole frustum, rather than a beam inside a hull. | | `veil` | `fn(renderer: Renderer, red: f32, green: f32, blue: f32, alpha: f32) -> void` | no | Composite a flat colour over the finished frame, for a cut dipping to white or to black. | ### drift/rollback Bound always: what each function acts on arrives as an argument the host passes in. Effects: `nondeterministic`. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `tick` | `fn(rewind: Rewind) -> i32` | no | The last tick that was stepped, or -1 before the first. | | `isReplaying` | `fn(rewind: Rewind) -> bool` | no | Whether this tick is being re-run to correct a mispredicted one. | | `depth` | `fn(rewind: Rewind) -> i32` | no | How many ticks back a rewind can reach. | | `earliest` | `fn(rewind: Rewind) -> i32` | no | The oldest tick still retained, or -1. | | `replays` | `fn(rewind: Rewind) -> i32` | no | How many rewinds have happened. | | `replayedTicks` | `fn(rewind: Rewind) -> i32` | no | How many ticks those rewinds re-ran in total. | ### drift/scene Bound always: what each function acts on arrives as an argument the host passes in. Effects: `scene.read`, `scene.write`. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `positionX` | `fn(node: Node) -> f32` | yes | A node's local x. | | `positionY` | `fn(node: Node) -> f32` | yes | A node's local y. | | `positionZ` | `fn(node: Node) -> f32` | yes | A node's local z. | | `setPosition` | `fn(node: Node, x: f32, y: f32, z: f32) -> void` | no | Move a node, marking it and its subtree for a world update. | | `setScale` | `fn(node: Node, x: f32, y: f32, z: f32) -> void` | no | Scale a node. | | `setRotation` | `fn(node: Node, x: f32, y: f32, z: f32, radians: f32) -> void` | no | Rotate a node about an axis. | | `windDirectionX` | `fn(wind: Wind) -> f32` | yes | The prevailing wind's x, normalised; zero when there is no wind to have a direction. | | `windDirectionZ` | `fn(wind: Wind) -> f32` | yes | The prevailing wind's z, normalised; zero when there is no wind to have a direction. | | `windSpeed` | `fn(wind: Wind) -> f32` | yes | How hard it is blowing, metres a second, never negative. | | `windGust` | `fn(wind: Wind) -> f32` | yes | The gust alone, -1 to 1, for a behaviour that wants the deviation and not the total. | | `distance` | `fn(a: Node, b: Node) -> f32` | yes | The distance between two nodes, in local space. | ### drift/terrain Bound always: what each function acts on arrives as an argument the host passes in. Effects: `physics.read`. Used by [Terrain](https://driftengine.dev/docs/worlds/terrain). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `heightAt` | `fn(terrain: Terrain, x: float, z: float) -> float` | yes | How high the ground is at a place, in metres. | | `normalX` | `fn(terrain: Terrain, x: float, z: float) -> float` | yes | Which way the ground faces at a place, along x. | | `normalY` | `fn(terrain: Terrain, x: float, z: float) -> float` | yes | The same, along y. | | `normalZ` | `fn(terrain: Terrain, x: float, z: float) -> float` | yes | The same, along z. | | `slopeAt` | `fn(terrain: Terrain, x: float, z: float) -> float` | yes | How steep the ground is at a place, in radians from flat. | | `covers` | `fn(terrain: Terrain, x: float, z: float) -> bool` | yes | Whether a place is over the field at all. | | `extentX` | `fn(terrain: Terrain) -> f32` | yes | How far the field reaches along x, in metres. | | `extentZ` | `fn(terrain: Terrain) -> f32` | yes | How far the field reaches along z, in metres. | ### drift/time Bound when the host passes `services.clocks` to `bindModule`; without it, an import of this module is refused at bind with a sentence saying so. Effects: `clock.read`. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `fixedDelta` | `fn() -> f32` | no | The fixed simulation step, in seconds. | | `frameDelta` | `fn() -> f32` | no | Seconds since the previous rendered frame, after clamping. | | `wallDelta` | `fn() -> f32` | no | Seconds of real time since the previous frame, unclamped. | | `elapsed` | `fn() -> f32` | no | Seconds since the loop started. | ### drift/ui Bound always: what each function acts on arrives as an argument the host passes in. Effects: `input.read`, `scene.read`, `scene.write`. Used by [Interfaces](https://driftengine.dev/docs/interface/interface). | Function | Signature | Deterministic | What it does | |---|---|---|---| | `layout` | `fn(tree: UiTree, x: f32, y: f32, w: f32, h: f32) -> void` | no | Lay the tree out into a box. | | `draw` | `fn(tree: UiTree, batch: SpriteBatch, white: i32) -> i32` | no | Put the tree in a batch and answer how many quads that was. | | `has` | `fn(tree: UiTree, name: String) -> bool` | yes | Whether the tree holds a node of this name. | | `left` | `fn(tree: UiTree, name: String) -> f32` | yes | Where a node ended up, along x. | | `top` | `fn(tree: UiTree, name: String) -> f32` | yes | The same, along y. | | `width` | `fn(tree: UiTree, name: String) -> f32` | yes | How wide a node ended up. | | `height` | `fn(tree: UiTree, name: String) -> f32` | yes | How tall a node ended up. | | `visible` | `fn(tree: UiTree, name: String) -> bool` | yes | Whether a node is shown. | | `show` | `fn(tree: UiTree, name: String, visible: bool) -> void` | no | Show or hide a node and everything under it. | | `setText` | `fn(tree: UiTree, name: String, text: String) -> void` | no | Change what a node says. | | `tint` | `fn(tree: UiTree, name: String, r: f32, g: f32, b: f32, a: f32) -> void` | no | Change a node's background colour, given as picked for the screen: sRGB, 0 to 1, decoded here to the linear light the renderer draws, as a theme's hex token is. | | `hovered` | `fn(tree: UiTree, name: String) -> bool` | no | Whether the pointer is over a node. | | `pressed` | `fn(tree: UiTree, name: String) -> bool` | no | Whether the pointer went down on a node and has not come up. | | `focused` | `fn(tree: UiTree, name: String) -> bool` | no | Whether a node has the keyboard. | | `point` | `fn(tree: UiTree, x: f32, y: f32, down: bool) -> bool` | no | Route the pointer, and answer whether this call activated anything. | | `activated` | `fn(tree: UiTree, name: String) -> bool` | no | Whether the last `point` activated this node. | | `key` | `fn(tree: UiTree, key: String, shift: bool) -> bool` | no | Route a key, and answer whether it activated what has focus. | | `focus` | `fn(tree: UiTree, name: String) -> void` | no | Give a node the keyboard. | ### drift/xr Bound when the host passes `services.xr` to `bindModule`; without it, an import of this module is refused at bind with a sentence saying so. Effects: `input.read`, `scene.read`. Used by [XR](https://driftengine.dev/docs/interface/xr). `Hand`: `Left`, `Right`, `None`. Which hand: left, right, or the input source with no side. `HandJoint`: `Wrist`, `ThumbMetacarpal`, `ThumbPhalanxProximal`, `ThumbPhalanxDistal`, `ThumbTip`, `IndexFingerMetacarpal`, `IndexFingerPhalanxProximal`, `IndexFingerPhalanxIntermediate`, `IndexFingerPhalanxDistal`, `IndexFingerTip`, `MiddleFingerMetacarpal`, `MiddleFingerPhalanxProximal`, `MiddleFingerPhalanxIntermediate`, `MiddleFingerPhalanxDistal`, `MiddleFingerTip`, `RingFingerMetacarpal`, `RingFingerPhalanxProximal`, `RingFingerPhalanxIntermediate`, `RingFingerPhalanxDistal`, `RingFingerTip`, `PinkyFingerMetacarpal`, `PinkyFingerPhalanxProximal`, `PinkyFingerPhalanxIntermediate`, `PinkyFingerPhalanxDistal`, `PinkyFingerTip`. One of the twenty-five joints WebXR tracks on a hand, from the wrist to each fingertip. | Function | Signature | Deterministic | What it does | |---|---|---|---| | `presenting` | `fn() -> bool` | no | Whether a session is running. | | `supported` | `fn() -> bool` | no | Whether this device could present at all. | | `headX` | `fn() -> f32` | no | Where the viewer’s head is, in metres. | | `headY` | `fn() -> f32` | no | Where the viewer’s head is, in metres. | | `headZ` | `fn() -> f32` | no | Where the viewer’s head is, in metres. | | `trigger` | `fn(hand: Hand) -> f32` | no | How far a hand’s trigger is pulled, 0 to 1. | | `squeeze` | `fn(hand: Hand) -> f32` | no | How far a hand’s grip is squeezed, 0 to 1. | | `holding` | `fn(hand: Hand) -> bool` | no | Whether a hand is tracked this frame. | | `jointX` | `fn(hand: Hand, joint: HandJoint) -> f32` | no | Where a hand joint is, in metres. | | `jointY` | `fn(hand: Hand, joint: HandJoint) -> f32` | no | Where a hand joint is, in metres. | | `jointZ` | `fn(hand: Hand, joint: HandJoint) -> f32` | no | Where a hand joint is, in metres. | | `pinching` | `fn(hand: Hand) -> bool` | no | Whether a hand’s thumb and index tips are close enough to count as a pinch. | --- # Determinism, testing and shipping DriftScript. https://driftengine.dev/docs/scripting/testing What @deterministic and @pure promise and how the compiler holds a script to them, testing a script in Node, CI, and what reaches the bundle. A rule written in DriftScript can carry a promise about what it touches, and the compiler checks the promise every time the file compiles. The same rules can be called from a test in Node, because a script that holds no engine object is a set of functions over records. This page covers both, then what a build checks and what it ships. ## Deterministic rules ```drs // The clock, once a step. Every orb taken wins the round; the clock reaching zero first loses it. // Deterministic: the same round and the same step give the same answer on every machine, so a // recorded round replays exactly. Reading input or the wall clock here would not compile. @deterministic fn tick(round: mut Round, dt: f32) { if round.phase != Phase.Playing { return } round.remaining = round.remaining - dt if round.gathered == round.total { round.phase = Phase.Won } else if round.remaining <= 0 { round.remaining = 0 round.phase = Phase.Lost } } ``` `@deterministic` on a function says that the same arguments give the same result on every machine, every time. The first game's `tick` carries it: given the same round and the same step, it ends the round the same way, so a recorded game replays exactly and two players simulating the same round agree. The compiler checks the promise from the calls. Every engine function is declared with its effects, and a function's effects are the effects of everything it calls, followed through its own helpers. A deterministic function may reach what is inside the simulation: reading the scene and physics, reading and writing entities, chemistry and navigation, reading a behaviour's state, and reading what the network and the save store have already delivered. It may not read input or the clock, play a sound or an animation, write to physics or the scene directly, save, send over the network, call a model, or reach the host. [What a script can reach](https://driftengine.dev/docs/scripting/reach) marks every engine function one way or the other. Hand `tick` the page's `ActionMap` and let the clock run faster while the stick is pushed, with `let hurry = input.axisX(actions, "move")`, and the file stops compiling, naming the call that broke the promise: ```text round.drs:9:1 DS0261 `tick` is annotated `@deterministic` but has `input.read`, which is outside the simulation boundary. It reaches `drift/input.axisX` (input.read). ``` When the read is inside a helper that `tick` calls, the message names the effect, and the helper is where to look. The fix is the shape the first game already has: the page reads the controls each step and passes the result in as a number, which the step can then be replayed with. ## Pure functions ```drs // A new round: a full clock, nothing gathered yet, and the number of orbs the page laid out. fn start(round: mut Round, total: u32) { round.remaining = ROUND_SECONDS round.gathered = 0 round.total = total round.phase = Phase.Playing } // Whether the player, this far from an orb on each axis, is close enough to take it. Pure: it reaches // nothing outside its arguments and the constants above, which the compiler checks. @pure fn reaches(dx: f32, dy: f32, dz: f32) -> bool { return dx * dx + dy * dy + dz * dz < REACH * REACH } fn gather(round: mut Round) { round.gathered = round.gathered + 1 } ``` `@pure` is the stricter promise: the function reaches no engine module at all, only its arguments and the script's constants. `reaches` is pure. A pure function that gains any effect, even one a deterministic function may have, fails with `DS0260` and the effects it gained. A pure function may still change a `mut` record it was handed, since the caller chose to hand it over. Mark a function pure when it answers a question from its inputs, a distance or a score or whether a move is allowed, and it stays that way. Neither annotation changes what the compiled code does. Both are checked and then erased, and a function without one is not assumed to be either. ## Testing a script ```ts import { describe, expect, it } from 'vitest'; import { loadModule } from 'driftscript'; import * as roundScript from './round.drs'; interface Round { remaining: number; gathered: number; total: number; phase: { tag: 'Playing' | 'Won' | 'Lost' }; } const rules = loadModule(roundScript as Record).exports as unknown as { createRound(): Round; start(round: Round, total: number): void; reaches(dx: number, dy: number, dz: number): boolean; gather(round: Round): void; tick(round: Round, dt: number): void; }; describe('a round', () => { it('is won when the last orb is gathered before the clock runs out', () => { const round = rules.createRound(); rules.start(round, 2); rules.gather(round); rules.gather(round); rules.tick(round, 1 / 60); expect(round.phase.tag).toBe('Won'); }); it('is lost when the clock runs out first, with the clock stopped at zero', () => { const round = rules.createRound(); rules.start(round, 2); rules.gather(round); for (let step = 0; step < 61 * 60; step += 1) rules.tick(round, 1 / 60); expect(round.phase.tag).toBe('Lost'); expect(round.remaining).toBe(0); }); it('reaches an orb within a metre and not beyond', () => { expect(rules.reaches(0.6, 0, 0.6)).toBe(true); expect(rules.reaches(0.8, 0, 0.8)).toBe(false); }); }); ``` A test imports a `.drs` file the way the page does. Vitest reads the project's `vite.config.ts` when it has no config of its own, so the DriftScript plugin compiles the script for the test with the same capabilities and the same manifest, and a script that breaks a promise fails the test run as it would fail the build. `loadModule` is all a script needs when it imports no engine module, as the round does. One that does is bound first, with `bindModule(module, services)` and whatever services its imports need, built in the test. Records are plain objects: the test creates one with the script's own `create` function, calls the rules, and reads the fields back. The examples in this repository are tested this way, beside the code they test, by the engine's own suite. ## Checking in CI A build compiles every script the page imports, so `vite build` is the check: an error in any script stops it and prints every error with its code and line. A test run checks the scripts its tests import. There is no separate command to add. A script nothing imports is never compiled, and it is also never shipped. ## What ships A compiled script is a plain JavaScript module with no imports of its own: its functions, a `create` function for each record, and a `__drift` export describing the module's records, components and systems, for the host and for hot reload. A production build leaves out the editor's metadata, which only the development tools use, and changes nothing about how the script behaves. The page's `import.meta.hot` block never runs in a built bundle. Around the scripts, the bundle carries what the page imports to run them: `loadModule` and `patchModule` from `driftscript`, and `bindModule` with the engine's bindings from `@driftengine/script`. Both packages are dependencies of the game, installed as [Installation](https://driftengine.dev/docs/start/installation#driftscript) shows, and the compiler itself stays in the toolchain. --- # Meshes and geometry Rendering. https://driftengine.dev/docs/rendering/meshes Build geometry in code with MeshBuilder or from raw arrays, upload it, rewrite it every frame, and stream big meshes in pieces. A mesh is vertex data on the GPU. You describe it as `MeshData`, plain typed arrays, hand it to `renderer.createMesh`, and get back a handle you draw with a world matrix as many times a frame as you like. Colour is a vertex attribute, so most meshes need no texture at all. ## Building from shapes ```ts /** A lamp post: every shape added to one builder becomes one mesh and one draw. */ export function lampPost(): MeshData { return ( new MeshBuilder() .addBox([0, 0.1, 0], [0.4, 0.1, 0.4], [0.3, 0.3, 0.32]) .addCylinder([0, 2, 0], 0.08, 1.9, 'y', [0.22, 0.23, 0.25], 0, 10) .addOrientedBox([0.35, 3.85, 0], [0.4, 0.05, 0.06], [1, 0, 0], [0.22, 0.23, 0.25]) // The fourth argument is emissive: this glows, where the environment lets emissive through. .addSphere([0.7, 3.7, 0], 0.16, [1, 0.85, 0.6], 2.5) .build() ); } ``` `MeshBuilder` collects shapes into one mesh. Everything added to one builder is one mesh and one draw, which is how a whole grey-box level becomes a single draw call. The shapes: | Method | What it adds | | ------------------------------ | ---------------------------------------------------------------------------- | | `addBox` | An axis-aligned box, from a centre and **half** extents | | `addOrientedBox` | A box turned to lie along a direction | | `addQuad` | A flat quad; its normal follows the corner order | | `addGroundQuad`, `addWallQuad` | A quad that faces up, or away from a point, whatever the corner order | | `addSphere`, `addCapsule` | Round solids; a capsule stands along Y | | `addCylinder` | A faceted cylinder along X, Y or Z | | `addTube` | A round tube of varying radius swept along a path | | `addBlob` | An irregular solid: a sphere whose radius and colour are asked for per point | | `addMesh`, `addOrientedMesh` | Another mesh merged in, placed, scaled or turned | Most take a colour, then optional `emissive` and `specular`. Builder state applies to what is added after it: `setRoughness`, `setGrain` (mineral texture, 0 to 1), `setRelief` (microscopic bumps), `setEmissiveColor`, and `setJoint`, which binds geometry to one bone of a skeleton. `build({ planarUvs: true })` also emits box-projected texture coordinates in metres, for a material that tiles across the world. For solids with holes, bevels and booleans, see [Procedural solids](https://driftengine.dev/docs/worlds/procedural-solids). ## Writing the data yourself ```ts /** A single triangle from raw arrays: every attribute covers every vertex. */ export function triangle(): MeshData { const data: MeshData = { positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]), colors: new Float32Array([1, 0.2, 0.2, 0.2, 1, 0.2, 0.2, 0.2, 1]), emissive: new Float32Array([0, 0, 0]), indices: new Uint32Array([0, 1, 2]), }; validateMeshData(data); // throws, naming the attribute, if anything does not line up return data; } ``` `positions`, `normals` and `colors` are three floats a vertex, `emissive` one, and `indices` three a triangle. Everything else is optional and named for what it does: - `specular` and `roughness`, one float each: how strongly a surface takes a highlight, and its shape. - `uvs` and `tangents`: texture coordinates, and the tangent frame normal maps need. `generateTangents` derives the second from the first. - `emissiveColor`: the colour a vertex emits, independent of its albedo. - `grain` and `relief`: procedural surface detail, so a stone wall looks like stone up close without a texture. - `layers`: which image of a texture array each face wears. - `channel`: four lanes for wind sway, a sky factor, per-vertex alpha and glass thickness. - `joints` and `weights` for skinning, four bones a vertex, and `joints2` and `weights2` for the next four where a vertex follows up to eight. The imported models that carry them keep all eight, heaviest first, and a mesh without the second four draws exactly as it did. `morphTargets` for blend shapes. `validateMeshData` checks that every attribute covers every vertex and every index names one that exists, and throws naming what is wrong. Mesh data is the same type the `.drft` container stores, so a model you import and a mesh you build are interchangeable. ## Drawing `renderer.drawMesh(mesh, model)` draws a mesh with a model matrix, usually a `SceneNode`'s `worldMatrix`, between `bindMeshPass` and `endFrame`. Two optional arguments follow: a depth layer, and a **tint**, a colour multiplied into the mesh for that one draw and reset after it. A tint is how one white mesh becomes four rows of different-coloured bricks without four meshes. `mesh.bounds` is measured at upload, ready for culling and level of detail. `renderer.disposeMesh(mesh)` frees it. ## Rewriting a mesh every frame ```ts /** A flag whose vertices move every frame: created dynamic once, rewritten in place. */ export function waveFlag(renderer: RendererApi) { const data = new MeshBuilder() .addQuad([0, 0, 0], [2, 0, 0], [2, 1, 0], [0, 1, 0], [0.8, 0.2, 0.2]) .build(); const mesh = renderer.createMesh(data, { dynamic: true }); const positions = new Float32Array(data.positions); return (time: number) => { for (let i = 0; i < positions.length; i += 3) { positions[i + 2] = Math.sin(time * 3 + data.positions[i] * 2) * 0.15 * data.positions[i]; } renderer.updateMesh(mesh, positions); return mesh; }; } ``` A mesh is immutable unless it was created `dynamic`. A dynamic one takes new positions, and normals if you have them, through `updateMesh`, without a new GPU buffer per frame, and only those two are uploaded: the colours, texture coordinates and the rest stay where they are. The vertex count is fixed for its life. A surface whose colour changes while it stays where it is, such as ground shaded with its distance from a moving camera, is created `{ dynamicColors: true }` and rewritten with `renderer.updateMeshColors(mesh, colors)`, three linear floats a vertex. Only the colours are uploaded, the bounds stay as they were, and nothing moves for motion blur or reconstruction. The option keeps the colours as floats in a buffer of their own, twelve bytes a vertex where sixteen-bit colours cost six or eight and one colour every vertex shares costs nothing, so ask for it only on a mesh you recolour. The two options are independent, and a mesh may have both. Cloth hanging in the world is drawn this way; cloth on a character is placed in the vertex stage instead, see [Ragdolls and cloth](https://driftengine.dev/docs/simulation/ragdolls-and-cloth). ## Uploading a large mesh across frames ```ts /** A large mesh uploaded over several frames, never more than two milliseconds of each. */ const budget = new StepBudget(); let pending: IncrementalMeshHandle | null = null; export function startUpload(renderer: RendererApi, data: MeshData): void { pending = renderer.createMeshIncremental(data); } /** Call once a frame. The mesh may be held and measured at once, and drawn once `complete`. */ export function continueUpload(): void { if (pending === null) return; const upload = pending.upload; budget.spend(2, () => (upload.next().done === true ? null : 'mesh')); if (pending.mesh.complete) pending = null; } ``` Creating a mesh copies all of it to the GPU at once, and a large one can take longer than a frame. `createMeshIncremental` returns a handle at once, which can be held and measured but not drawn, and an iterator that advances the upload in bounded steps. `StepBudget` spends a slice of each frame on it and reports its worst single step, so a streamed world never drops a frame to an upload. `mesh.complete` says when it has all arrived. ## Performance - Merge static geometry. One mesh drawn once beats a hundred drawn once each. - Repeat a mesh many times with [instancing](https://driftengine.dev/docs/rendering/instancing), not with a loop of `drawMesh` calls, when the copies differ only in their transforms. - Build in loading, never in the frame. `createMesh` allocates GPU memory. --- # Materials Rendering. https://driftengine.dev/docs/rendering/materials Surfaces from vertex values or image maps, compressed blocks for every device, shading models for metal, hair, skin and eyes, lightmaps and surface dials. A surface in DriftEngine can be described two ways, and they combine: - **Per vertex**, in the mesh: colour, emissive, specular, roughness, grain and relief. A whole world can be made this way with no images at all, and a merged mesh of many colours is still one draw. - **By image maps**, set as a material before the draws that use it: albedo, normal, occlusion-roughness-metalness, and emissive. This is the glTF model, so an imported model's materials arrive as exactly this. (This chapter runs the `materials` example at https://driftengine.dev/docs/rendering/materials.) ## Images `renderer.createSurfaceTexture(source, options)` uploads anything the browser calls a `TexImageSource`: an image element, an `ImageBitmap`, a canvas or a video frame. The engine ships no images and fetches none, so loading the file is yours. ```ts /** A small canvas of one colour: the whole of an ORM map whose value does not vary. */ function solid(r: number, g: number, b: number): HTMLCanvasElement { const canvas = document.createElement('canvas'); canvas.width = 4; canvas.height = 4; const ctx = canvas.getContext('2d'); if (ctx !== null) { ctx.fillStyle = `rgb(${r * 255}, ${g * 255}, ${b * 255})`; ctx.fillRect(0, 0, 4, 4); } return canvas; } ``` The option that matters most is `colorSpace`. A picture, such as an albedo or emissive map, is `'srgb'`. A map whose values are numbers, such as a normal map or an ORM map, is `'linear'`; uploaded as sRGB, its values bend toward zero and every surface looks like glass. The other options are `wrap` (`'repeat'` or `'clamp'`), `filter` for magnification, `mipmap`, on by default, and `anisotropy` for textures seen at a grazing angle. `updateSurfaceTexture` replaces the pixels and keeps the binding, and `disposeSurfaceTexture` frees one. `createSurfaceTextureArray` uploads several images of one size as one texture whose layer each face picks; see [Texture arrays](https://driftengine.dev/docs/rendering/texture-arrays). ## Compressed images `createSurfaceTexture` also takes compressed blocks as they are: a `CompressedTextureSource` names its `format`, its size and its `levels`, the stored mip chain from level 0. BC (`'bc1'` to `'bc5'`, and `'bc7'`) is what desktops sample; ETC2 (`'etc2-rgb8'`, `'etc2-rgb8a1'`, `'etc2-rgba8'`), EAC (`'eac-r11'`, `'eac-rg11'`) and ASTC (`'astc-4x4'` to `'astc-12x12'`) are what phones sample. A block texture costs a byte a texel or less on the GPU, against four for the same image decoded, and keeps the chain its author built. `colorSpace` decides between a format and its sRGB twin, as it does for an image; the one- and two-channel formats have none. `renderer.compressedFormats` lists what this device samples, and `uploadsCompressed(format, srgb, width, height, renderer.compressedFormats)` answers for one source. A source the device cannot take is refused by name, because core ships no decoder. `updateSurfaceTexture` takes blocks as well as an image: they replace the image behind the handle every draw already holds. The model loader in `@driftengine/assets` asks before it uploads. A BC texture goes up as its blocks where the device samples BC, and is decoded at load where it does not, so an imported model's images reach every device. Name a worker for that, `new DrftLoader(renderer, { bcWorker: spawnBcWorker })` with `spawnBcWorker` from `@driftengine/assets/bcWorkers`; without one the decode runs on the main thread and the loader says so once. **On a phone, the worker does more**: where the device samples ETC2 and not BC, a second worker re-encodes each decoded texture as ETC2 or EAC and swaps it in behind its handle, at half a byte a texel, or a byte with alpha, where the decoded image holds four. The picture arrives when it did before; the encode follows on a core of its own, about 0.7 s for a 2048² image on a desktop processor and several times that on a phone's. Textures compressed for a phone ahead of time skip both steps. `readKtx2` from `@driftengine/assets` reads an uncompressed KTX2 file of ASTC, ETC2, EAC or BC as the blocks it carries, and says which colour space its format names. `encodeEtc2Chain` makes ETC2 or EAC blocks and their chain from pixels you hold; run it in a worker. A two-channel BC5 or EAC normal map keeps its two channels and the lit stage rebuilds the third. ## Metalness and roughness ```ts /** * Occlusion in red, roughness in green, metalness in blue. These are data, not colours, so they * are uploaded as linear: read as sRGB they would bend toward zero and every surface would look * like glass. */ function orm(roughness: number, metal: number): SurfaceTextureHandle { return renderer.createSurfaceTexture(solid(1, roughness, metal), { colorSpace: 'linear' }); } const STEPS = 6; /** Top row: metalness from 0 to 1 at middling roughness. Bottom row: roughness at full metal. */ const metals = Array.from({ length: STEPS }, (_, i) => orm(0.35, i / (STEPS - 1))); const roughs = Array.from({ length: STEPS }, (_, i) => orm(0.05 + (i / (STEPS - 1)) * 0.9, 1)); ``` An ORM map packs three values into one image: ambient occlusion in red, roughness in green and metalness in blue. Metalness splits a surface into metal, which colours its reflection, and everything else, which reflects white. Roughness widens and softens the highlight. A material can scale each channel: `roughnessScale`, `metallicScale` and `occlusionStrength` are glTF's factors. ### A physical highlight A lamp's highlight is normally a look control: it peaks at 1 times the specular value however rough the surface, so strength and width can be set apart. A material that sets `physicalSpecular: true` takes GGX's own term instead, `π · D · Vis · F · N·L`, as a physically based renderer shades and as skin and the eye already do here. The peak is then `1 / (4 α²)` of the light head-on, where α is the roughness squared, so a polished surface's highlight is several times the look's and a rough one's lower and wider. The per-vertex `specular` value becomes the reflectance at normal incidence, F0: about 0.04 for most surfaces that are not metal. Fresnel then brightens every surface toward a grazing angle, not only a metal. It reaches lamps and the sun, on the standard, lightmap and anisotropic models; a rectangle's highlight is integrated over the rectangle with the same F0 already, so it does not change. Without `hdrScene` an 8-bit frame clips the brighter peak. The code is compiled into the lit programs the first time a material asks for it, so a scene that never does pays nothing. ## A material ```ts /** A tile pattern for the albedo, which is a picture and so is sRGB. */ function tiles(): HTMLCanvasElement { const canvas = document.createElement('canvas'); canvas.width = 256; canvas.height = 256; const ctx = canvas.getContext('2d'); if (ctx !== null) { ctx.fillStyle = '#6b6560'; ctx.fillRect(0, 0, 256, 256); ctx.fillStyle = '#8a837b'; ctx.fillRect(4, 4, 120, 120); ctx.fillRect(132, 132, 120, 120); ctx.fillStyle = '#7a736b'; ctx.fillRect(132, 4, 120, 120); ctx.fillRect(4, 132, 120, 120); } return canvas; } /** A normal map from the same tile layout: grooves between tiles, and a gentle bevel. */ function tileNormals(): HTMLCanvasElement { const size = 256; const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; const ctx = canvas.getContext('2d'); if (ctx === null) return canvas; const image = ctx.createImageData(size, size); const height = (x: number, y: number): number => { const u = ((x % 128) + 128) % 128; const v = ((y % 128) + 128) % 128; const edge = Math.min(u, 127 - u, v, 127 - v); return Math.min(1, edge / 6); }; for (let y = 0; y < size; y += 1) { for (let x = 0; x < size; x += 1) { const dx = height(x + 1, y) - height(x - 1, y); const dy = height(x, y + 1) - height(x, y - 1); const length = Math.hypot(dx, dy, 1); const i = (y * size + x) * 4; image.data[i] = ((-dx / length) * 0.5 + 0.5) * 255; image.data[i + 1] = ((-dy / length) * 0.5 + 0.5) * 255; image.data[i + 2] = ((1 / length) * 0.5 + 0.5) * 255; image.data[i + 3] = 255; } } ctx.putImageData(image, 0, 0); return canvas; } /** `planarUvs` gives the ground texture coordinates; a normal map also needs tangents. */ const groundData = new MeshBuilder() .addBox([0, -0.1, 0], [8, 0.1, 6], [1, 1, 1]) .build({ planarUvs: true }); if (groundData.uvs !== undefined) { groundData.tangents = generateTangents( groundData.positions, groundData.normals, groundData.uvs, groundData.indices, ); } const ground = renderer.createMesh(groundData); const groundMaterial = { albedo: renderer.createSurfaceTexture(tiles(), { colorSpace: 'srgb' }), normal: renderer.createSurfaceTexture(tileNormals(), { colorSpace: 'linear' }), orm: orm(0.75, 0), uScale: 0.5, vScale: 0.5, }; ``` A normal map turns the shading normal per pixel, through the mesh's tangent frame, so a mesh that uses one needs texture coordinates and tangents. `build({ planarUvs: true })` projects texture coordinates in metres, and `generateTangents` derives the tangents from them. `normalStrength` scales the effect. The rest of the fields: - `uScale` and `vScale` repeat every map of the material across the mesh's coordinates. - `uOffset` and `vOffset` move where the maps start, after the scale: a surface samples `uv * scale + offset`. That picks one cell of a flipbook or an atlas through the material, so one quad draws any cell. A strip of four frames is `uScale: 0.25` with `uOffset: frame * 0.25`. A cutout's shadow is cut from the same cell. - `cutout` discards fragments whose albedo alpha is below it: leaves, grilles, fences. A cutout also shapes the shadow the surface casts. `cutoutMode: 'dithered'` keeps a pixel by the share of it the texture covers rather than by a line through it, so a strand of hair, a lash or a fringe of leaves has a soft edge instead of a stair of pixels. The frame decides how the dither becomes coverage: a temporal resolve averages it over time, a multisampled frame turns it into samples, and a frame with neither tests hard, because a dither nothing averages is grain. A translucent draw tests hard whatever this says. - `doubleSided` draws both faces, for a curtain or a leaf card. - `emissive` and `emissiveScale` shape where a mesh glows and in what colour. A map modulates the mesh's own emission and never creates it, glTF's rule: what is emitted is the mesh's emissive times its emissive colour, or its albedo where it has none, times the map, times the scale. A mesh built with no emissive stays dark whatever map it is drawn with, and `emissiveScale` with no map bound does nothing. - `emissiveScroll` moves the emissive map alone, `[u, v]` in its own repeats a second by the environment's `surfaceTime`: lava drifting through cracks, a band of light running along a sign. `emissiveMaskLayer` names a layer of the emissive array whose alpha keeps the glow, read at the mesh's own first coordinates, before `uScale`, `uOffset`, the layers or a projection. So a glow repeated eight times across a rock is held to cracks a map spanning the rock once draws, where folding the mask into each vertex's emission spread it over whole faces of a coarse mesh. Alpha is never decoded as sRGB, so the mask is the number written, whatever the array's colour space; a layer is the array's size. Both are one switch, compiled in the first time a material asks. - `iridescentOverlay` lays a hue that turns with the view over the base colour, before it is lit: a coat's sheen running through a spectrum as it turns. Per pixel, with `N` the mapped normal, `V` toward the eye and `u` the mesh's own first coordinate, `x = N·V + u + blend (h − N·V)`, where the sheen `h` is `N·H` raised to `contrast` for `H` halfway between `V` and the overlay's `direction`, and 0 where `N·H` is at or below zero. The `ramp`, linear colours three floats each, is read at `fract(x · tiling)`, and the base moves toward the overlay blend of itself and that colour by `x · mask · weight`. Defaults: `blend` 0.6, `contrast` 1, `tiling` 2, `weight` 0.25. The `mask` is a channel of a layer of the material's `orm`, `model`, `albedo` or `emissive` array, read at the material's coordinates, and absent the overlay is laid everywhere. The lit stage has no texture binding to spare, so the ramp is thirty-two colours of uniforms, resampled from any length; that is thirty-six vectors, which WebGL2 refuses, saying so once, on a part whose lit stage has no room for them. ## Drawing with a material ```ts render() { const angle = Math.sin(time * 0.15) * 0.35; camera.position[0] = Math.sin(angle) * 9; camera.position[1] = 3.2; camera.position[2] = Math.cos(angle) * 9; camera.lookAt(0, 1.2, 0); renderer.beginFrame(CLEAR); renderer.bindMeshPass(camera, ENV); renderer.setMaterial(groundMaterial); renderer.drawMesh(ground, still.worldMatrix); for (let i = 0; i < STEPS; i += 1) { const x = (i - (STEPS - 1) / 2) * 1.5; renderer.setMaterial({ orm: metals[i] }); place.setPosition(x, 2.2, 0); place.updateWorld(); renderer.drawMesh(sphere, place.worldMatrix); renderer.setMaterial({ orm: roughs[i] }); place.setPosition(x, 0.7, 0); place.updateWorld(); renderer.drawMesh(sphere, place.worldMatrix); } renderer.setMaterial(null); renderer.endFrame(); }, ``` `setMaterial` is pass state: it applies to every `drawMesh` after it until it changes, and `bindMeshPass` clears it. Group draws by material where you can. Each change costs a slot in a per-frame ring, and repeating one mesh many times under one material is what [instancing](https://driftengine.dev/docs/rendering/instancing) is for. ### A screen showing another camera ```ts /** A 1024 by 576 capture, made once with the scene, and the camera that films it. */ export function createBroadcast(renderer: RendererApi) { const feed = renderer.createSceneCapture(1024, 576); const camera = new Camera(); camera.fovYDeg = 35; return { feed, camera, screen: { emissive: feed } }; } /** Each frame: film the world first, then draw the frame with the screen showing the film. */ export function drawWithScreen( renderer: RendererApi, broadcast: ReturnType, viewer: Camera, env: Environment, clear: Vec3, drawWorld: () => void, screenMesh: MeshHandle, screenPlacement: Float32Array, ): void { renderer.beginFrame(clear); renderer.captureScene(broadcast.feed, broadcast.camera, clear, (filming) => { renderer.bindMeshPass(filming, env); drawWorld(); }); renderer.bindMeshPass(viewer, env); drawWorld(); renderer.setMaterial(broadcast.screen); renderer.drawMesh(screenMesh, screenPlacement); renderer.setMaterial(null); renderer.endFrame(); } ``` `createSceneCapture(width, height)` makes a texture the scene can be drawn into, and `captureScene` draws it from a camera of your own: the callback is handed the camera, its matrices shaped to the capture, and draws the world exactly as it would to the screen. The texture then goes wherever an image goes, most often as a material's `emissive`, for a stadium screen, a monitor or a security feed. Capture before the frame binds its own camera, and bind it again afterwards. A capture holds light rather than display pixels, at the colour format a reflection probe takes, half floats under `hdrScene`. The output transform is held off while it is drawn, so the frame grades the screen once, with everything around it. It is the world's mesh pass alone: the sky, water and particles are in it only if the callback draws them, and no temporal resolve, bloom or other effect runs on it. It has no mip chain, so a screen seen small and far can shimmer. An emissive surface glows by the environment's `nightFactor`, so a screen meant to glow by day wants the factor up, or the capture as its `albedo` on an unlit draw. ## Shading models Most surfaces are the standard model: a diffuse term and one highlight whose width the roughness sets. A few are made of something it cannot describe, and a material names one of four others with `model`, made by a factory that checks the numbers and freezes them. Leave `model` out, or pass `null`, for the standard model. - `anisotropicModel({ strength, rotation, lift })`, for brushed metal, satin and grooved plastic: the highlight stretched along the mesh's tangent by `strength`, 0 to 1, its direction turned by `rotation` radians toward the bitangent. At strength 0 it is the standard highlight exactly. The environment is reflected about a normal bent toward the stretch, so a brushed disc shows a streak of sky. `lift` raises the highlight where it is bright, its distribution `D` becoming `D + min(3, D^1.5) · lift`, for a brushed finish that reads as polished along its streak; 0, the default, is none. - `hairModel({ shift, scatter, backlit, directionOffset })`, for strands along the mesh's tangent, running from root to tip: a white highlight shifted toward the root, a coloured second one toward the tip, a glow when a light is behind (`backlit` scales it), and the light scattered through many strands (`scatter`, 0 to 1). `shift` is the tilt of the strand's cuticle in radians, 3° by default. A card authored tip to root swaps its two highlights' ends and takes a negative shift. Light from every side (the sky, a probe's irradiance, DriftLight) reaches hair through the same lobes, evaluated for the eye's own side of the strand, so a fibre keeps its colour in the shade. Hair reflects none of the environment, because the reflected lobe already holds that light. - `skinModel({ scatterColor, radius, transmission, profile })`, for light that leaves skin a little way from where it entered: a softer, redder terminator on curved parts, a red edge to a shadow, and light through thin parts from a lamp behind them, as much as `transmission` lets through. Each colour travels `radius` metres times its share of `scatterColor` on average before it leaves, 1.2 cm for red by default; Burley's profile does that at two fifths of the distance, with a tail of light reaching about three and a half times it. Until 4.8.7 the radius was the profile's own distance, so light went two and a half times as far: a skin authored then and looking right with `'pre-integrated'` keeps its look with `radius` raised by 2.5. Scale matters: at a person's size a cheek scatters; at a statue's ten times larger, almost nothing does. - `eyeModel({ irisRadius, irisDepth, ior, corneaRoughness, axis, joint })`, for an iris seen through a cornea: the cornea bends the eye's ray, so the iris moves under it as the eye turns and reads less foreshortened than a painted one. The iris is lit as the shallow cone it is, light pooling on the side away from the source, under the cornea's sharp highlight. `axis` is the eye's forward direction in the mesh and `joint` the bone it turns with. `modelMap` is an image of a model's own channels, read at the albedo's coordinates and uploaded as `'linear'`: - anisotropic: red and green a direction in the surface, glTF's packing of −1 to 1, blue a scale on the strength, and alpha a scale on the lift, so a map storing a tenth of each region's lift takes `lift: 10`. - hair: red is the strand's specular, scaling its white highlight by twice it (0.5, or 128, is the highlight as drawn; 0 is a strand that reflects nothing off its surface, as at a root), green varies each strand's tilt by up to half of it either way, and blue is occlusion. With `directionOffset: n`, the layer `n` past the texel's own holds each strand's direction in the surface's tangent frame (red along the tangent, green along the bitangent, blue out of the surface, each packed as a normal map packs it), so a card's strands can lean out of its plane. - skin: red is thickness, 1 being two centimetres, and green curvature, 1 being a radius of a centimetre. - eye: red is the iris, 1 inside it, and green the cornea's height above it as a share of `irisDepth`. Without a map each model has its own answer: the anisotropic stretch follows the tangent, skin reads its curvature from the screen and takes a part's thickness to be its curvature's diameter, and the iris is a disc of `irisRadius` about the texture's centre. Hair, skin and the eye ignore the per-vertex `specular` value: their highlights are physical, set by their own index of refraction, and their width is the material's roughness, or the cornea's. Anisotropic metal takes its colour and strength from the ORM map as any metal does. A model costs a pipeline of its own, compiled the first time a draw asks for it, so a scene that names none pays nothing. The models belong to the forward path; the [GPU-driven](https://driftengine.dev/docs/rendering/gpu-driven) pipeline's materials have none. One more kind goes in `model`, `lightmapModel`, which is not a way of answering light but a page of light baked earlier; see [Baked lightmaps](#baked-lightmaps). ### Skin in the picture The skin model's scattering is a fit evaluated per pixel, and it cannot see past the pixel it is shading. `skinScattering: 'screen-space'`, a renderer quality option, adds Burley's blur in the picture as well. Each skin draw writes the light its diffuse is made of, shaded as if the skin were white, to a target of its own, which is spread across the pixels its scatter distance covers; the skin's colour goes to a second target and multiplies the light once it has spread, and the sum is added back before anything blended is drawn. So light crosses a shadow's edge and a nostril's rim on screen, while a brow, a freckle or a lip line painted in the albedo stays where it is drawn rather than smearing into the skin around it. Under it the fit steps back to Lambert's and the blur does the scattering; light through thin parts stays with the fit, because the picture cannot see the far side. What it costs: every skin draw is drawn three times, there are three half-float targets the size of the frame and two more under multisampling, and two full-screen passes run that leave at once wherever no skin was drawn. It needs the composite (`screenEffects`) and, on WebGL2, the `EXT_color_buffer_float` extension; without either, skin stays pre-integrated and the renderer says so once. `profile` picks which of eight scatter distances the blur uses, and the last material to name a profile sets it. A skin drawn after something blended in the same frame, or in an instanced batch, is drawn pre-integrated. ## Baked lightmaps A stage built in another tool often carries its static light baked: the light bounced off its walls, the soft shadow in its corners, most of the colour a reference render shows. A lightmap brings that bake in. Decode it into pages, each an image of irradiance and an image of the direction the light arrives from, and give every lightmapped mesh a second set of texture coordinates on its page. `examples/lightmaps/` bakes a room on the CPU, a lamp and the soft shadow of a box, and draws it this way. ```ts /** A floor lit by the left half of a page: the page uploaded, the mesh given its coordinates. */ export function bakedFloor( renderer: RendererApi, page: LightmapPage, floor: MeshData, lightmapUvs: Float32Array, albedo: SurfaceTextureHandle, ) { const lightmap = renderer.createLightmap(page); const mesh = renderer.createMesh({ ...floor, lightmapUvs }); /* Where the floor is on the page, as [scaleU, scaleV, biasU, biasV]. */ const material: SurfaceMaterial = { albedo, model: lightmapModel({ region: [0.5, 1, 0, 0] }), modelMap: lightmap, }; return { mesh, material }; } ``` A `LightmapPage` is a `width` and `height`, `irradiance` as three linear floats a texel in the units every other light here is in, and `direction` as four bytes a texel: a first-order spherical harmonic in the engine's axes, each value stored as `v * 0.5 + 0.5`. `createLightmap` uploads it as two layers of four bytes a texel: the irradiance packed as an rgb9e5 word, three 9-bit mantissas over a shared exponent, and the direction. Hand `irradiance` over as three floats a texel, or as a `Uint32Array` of words already packed, which is how a bake usually arrives and which uploads with no copy. A material made with `lightmapModel({ region })` takes it as its `modelMap`, and `region` says where the material's surfaces are on the page: `uv2 * scale + bias`, the whole page by default. The surface adds `albedo * (1 - metal) * irradiance * max(0, dot(d, n) + w)` to its diffuse, with `n` its shading normal, on top of the dynamic lights and the ambient. A bake that already holds the sky's light wants the ambient taken out of those draws, which `setAmbientSH` with nine zero coefficients does. ```ts /** Pillars in one batch, each lit by its own column of one page. */ export function bakedPillars(count: number): MeshInstances { const instances = { ...createMeshInstances(count), lightmapRegions: new Float32Array(count * 4), }; for (let i = 0; i < count; i += 1) { instances.lightmapRegions.set([1 / count, 1, i / count, 0], i * 4); } instances.count = count; return instances; } ``` Copies of one mesh in one batch each sit in their own part of the page, so an instanced batch with a lightmapped material carries `lightmapRegions`, four numbers an instance, applied before the material's own region. A batch needs them: one drawn without reads its tints as regions, and the renderer says so once. What a lightmap gives up, because everything it would take was already spent: - The second coordinates ride the grain and relief attributes, so a lightmapped surface has no procedural grain or relief, and a mesh naming both is refused. They are stored below zero, so the same mesh drawn without its page simply has neither. - An instance's region rides its tint and opacity, so a lightmapped batch has no per-instance tint. - A lightmapped material takes no other shading model, since the page is its model map. - No importer reads a second set of coordinates yet and the `.drft` container does not carry them, so the mesh is built by your own code; the GPU-driven pipeline reads no page. ## Surface dials A few properties apply to the draws that follow, without a map: - `setSurfaceReflectivity(amount)`: how much of the environment a surface mirrors, 0 to 1. Metal reflects by itself; this is for a varnished or wet dielectric. - `setEnvironmentGain(gain)`: how bright the reflected environment is, for a room too dim for its metal to read. - `setEnvironmentMixing(weight, roughnessLow, roughnessHigh)`: what every surface reflects brought to the light where it stands, `weight` the place's indirect light over the probe's, mixed in by roughness. See [Reflections](https://driftengine.dev/docs/rendering/reflections). - `setSurfaceGrain(amount)` and `setSurfaceRelief(amount, cyclesPerMetre)`: procedural mineral texture and microscopic bumps, so stone reads as stone up close. - `setSurfaceTextureRelief(scale)`: bumps from the bound albedo's own brightness, for a texture with no normal map. - `setEmissiveGain(gain)`: scale emissive for the next draws, for anything that pulses. - `setSurfaceFog(enabled)`: take the next draws out of the fog and the global medium's haze, or put them back. For a medium that should darken one thing and not another: a floor receding into the distance under figures that keep their full value however far away they stand. A translucent draw's own `fog` option still decides for that draw. Each resets with `bindMeshPass`, so a pass starts from the defaults. A material can state the first two for its own draws: `reflectivity` and `environmentGain` on a `SurfaceMaterial` override what the setters say for every draw under that material, and a material stating neither leaves its draws to the setters. That is how a static list carries them, since a list keeps each entry's material and none of the renderer's state between draws: a stage whose batches each mirror their own share of a baked reflection gives each its own material. ## Overlays: a rim, a dissolve, wrinkles `setSurfaceOverlay(overlay)` lays something over the surfaces of the draws that follow, beyond their materials: one character's whole set of materials changes together while another's does not. Like the dials above it is per draw and resets with `bindMeshPass`; pass `null` to take it off. ```ts /** A character in its heat: an orange rim over all of it, and its edges burning away. */ export function drawInHeat( renderer: RendererApi, character: readonly Part[], atlas: SurfaceTextureHandle, ): void { const noise = { scale: [0.5, 0.5], offset: [0, 0] } as const; renderer.setSurfaceOverlay({ maps: atlas, rim: { colour: [1, 0.45, 0.1], intensity: 2, noise: { region: noise, scroll: [0, 0.2], tiling: 3 }, pulse: { rate: 1.257, low: 0.6, high: 1 }, }, dissolve: { noise: { region: noise }, threshold: 0.4, edgeColour: [0.3, 0.8, 1], edgeIntensity: 4, }, }); for (const part of character) renderer.drawMesh(part.mesh, part.model); renderer.setSurfaceOverlay(null); } ``` - **`rim`** (`SurfaceRim`) glows along the silhouette: an edge `(1 − N·V)^falloff`, leaning toward normals that face up, raised to a contrast, times a noise laid in screen space and scrolled, a slow pulse on the environment's `surfaceTime`, and a mask in the mesh's uv that erases it. It is added to what the surface emits and, unlike emission, is not gated on `nightFactor`. With `mode: 'blend'` it is a colour rather than a light: the base colour is pulled toward the rim's by that edge times `alpha`, before any light reads it, so the edge is lit as the surface is and stays dark where no light reaches. There `colour` times `intensity` is held at 1 a channel, as a base colour is, and an `alpha` above 1 saturates the edge sooner. - **`dissolve`** (`SurfaceDissolve`) cuts the surface away where a noise in its uv falls under `threshold`, with a glowing band of width `edge` just above it, and can lay a colour over the surface through the same noise. 0 keeps everything and 1 cuts everything. - **`wrinkle`** (`SurfaceWrinkle`) blends a second normal map into the surface's by six region weights, read through two masks: the first mask's red, green and blue carry regions 1 to 3, the second's regions 4 to 6. A face's expressions, or veins brought up all over. **Every image is a region of one atlas**, `maps`, named by an `OverlayRegion`: its size and its corner in the atlas's uv. The lit stage has no sampler to spare for images of their own, so the atlas is read where the frame's refraction copy goes. Paint the noise, the masks and the wrinkle normal into one image, uploaded `colorSpace: 'linear'` with `mipmap: false`. Without `maps`, no image is read: a rim is smooth, and nothing dissolves or wrinkles. What it gives up: - **A draw that refracts or is glass reads none of the overlay's images**, because its own copy of the frame takes that slot. It keeps its refraction, and the engine says so once. - **The dissolve cuts the lit pass only.** Shadows and depth-only passes still see the whole surface. - **The GPU-driven pipeline draws no overlay**; a character wearing one is drawn with `drawMesh`. - **On WebGL2 the overlay takes fifteen fragment uniform vectors**, which a part offering 256 has no room for at the eight-light budget. There the overlay is refused, said once, and the draws wear none; a lower `maxLights` makes the room. WebGL2 also cannot copy a compressed atlas into the 2D image the stage reads, so upload the atlas from an image. ## Maps placed by the world A material can take its texture coordinates from where a point is in the world rather than from the mesh. Ground imported with flat coordinates, or none worth reading, then shows its texture at the size the material asks, and a wall or a rock wears one without the stretch a single projection gives a steep face. ```ts /** Sand, two repeats a metre across the ground, whatever coordinates its mesh carries. */ export function sand( colour: SurfaceTextureHandle, normal: SurfaceTextureHandle, ): SurfaceMaterial { return { albedo: colour, normal, projection: { kind: 'planar', scale: 2 } }; } /** Rock, once a metre on all three planes, blended where the surface turns between them. */ export function rock( colour: SurfaceTextureHandle, orm: SurfaceTextureHandle, ): SurfaceMaterial { return { albedo: colour, orm, projection: { kind: 'triplanar', scale: 1, sharpness: 6 } }; } ``` `projection: { kind: 'planar', scale }` lays every map across the two horizontal axes at `scale` repeats a metre. `'triplanar'` reads each map on the three planes across x, y and z and blends them by how squarely the surface faces each; `sharpness`, 4 unless given, is how quickly one plane gives way to the next. A normal map follows either: on three planes it is blended so each keeps its own detail. It is compiled into the lit stage the first time a material asks, so a scene that never asks pays nothing for it. What it gives up: - **The world's coordinates do not move with a mesh**, so a moving mesh slides under its texture. Projection is for ground, walls and rock that stand still. - **Triplanar reads every map three times**, and a texture is mirrored on the far side of each plane. - **The material's `uScale`, `vScale` and offsets do not apply**: they scale the mesh's coordinates, which a projection does not read. - **A cut-out projected material casts by its mesh's coordinates**, since shadow and depth passes read the cutout where the mesh lays it. - **On WebGL2 it takes one fragment uniform vector**, refused, said once, on a part with no room left at the light budget; a lower `maxLights` makes the room. ## Layers blended by a mask Rock with moss on it, a path worn through grass, sand drifted against a wall: one surface made of several, each with its own colour, normals and roughness at its own repeat. `layers` blends up to five of them by a mask. ```ts /** * Three layers in three arrays — rock, moss, sand, the same order in each — and a mask whose red * lays the moss and green the sand. The rock repeats forty times across the mesh, the moss three. */ export function mossyRock( albedo: SurfaceTextureHandle, normal: SurfaceTextureHandle, orm: SurfaceTextureHandle, mask: SurfaceTextureHandle, ): SurfaceMaterial { return { albedo, normal, orm, layers: { mask, repeats: [40, 3, 12] } }; } ``` Layer `i` is layer `i` of each array, so `albedo`, `normal` and `orm` are arrays whose layers are the material's in the same order, each read at the mesh's coordinates times its own repeat. The mask is read at the mesh's own coordinates and lays each layer over the ones before it: red lays layer 1 over the base, green layer 2, blue layer 3, alpha layer 4. `emissiveLayer` gives the emissive map to one layer, glowing where that layer shows; absent, it glows everywhere, as on any material. It is compiled into the lit stage the first time a material asks. Other families of layered surface blend differently, and `layers` takes them too: - **`mask: 'orm'`** reads the mask from the ORM array's layer just past the material's layers, which leaves the model's slot to a lightmap's page, so a lightmapped surface blends its layers. - **`mask: 'vertex'`** takes the weights from the vertex colour's red, green and blue, which then tints nothing. - **`blend: 'sum'`** mixes the base toward the sum of each layer times its weight, by the weights' sum held to 1, where the default lays each over the ones before it. - **Under a `projection`** the layers are placed by the world, each at its own repeats a metre, and `addMask: { layer, repeat, intensity }` adds a mask placed the same way, the ORM array's next layer, to one layer's weight: sand drifting into the gravel at a scale of its own. - **`facing: { layer, bias, sharpness }`** weighs one layer by how much the surface faces up, `saturate(bias + sharpness × (up / 2 + 1/2))`, in place of its channel: snow on the tops of rocks. - **`meshNormal: true`** lays a normal map read at the mesh's own coordinates, the normal array's layer just past the layers, under the layers' blended normal: a cliff's large shape beneath detail that repeats forty times across it. ### Layers shared between materials A texture worn by many materials, in a different tint on each, is one texture. `arrayLayers` picks which layer of the albedo, normal and ORM arrays each of a material's layers reads, so materials share one array of each kind, and `looks` gives each layer what used to be baked into its pixels: ```ts /** * Two cliffs that share one array of each kind, every texture in it once. Each cliff picks its * layers by index and gives them a look of its own; its own mask and its occlusion sit past the * shared textures, at `extrasAt` in the ORM array. */ export function sharedCliffs( albedo: SurfaceTextureHandle, normal: SurfaceTextureHandle, orm: SurfaceTextureHandle, ): SurfaceMaterial[] { const warm: SurfaceLayers = { mask: 'orm', repeats: [8, 4, 16], /* Rock, moss and sand: textures 0, 5 and 2 of every array. */ arrayLayers: [0, 5, 2], /* This cliff's mask is the ORM array's layer 30, and its occlusion the one after. */ extrasAt: 30, meshOcclusion: 0.8, looks: [{ tint: [1.2, 1, 0.85], roughness: [0.6, 0.95] }, { normalStrength: 2 }], }; /* The same rock, darker and smoother, under a different moss: nothing new uploaded. */ const cold: SurfaceLayers = { ...warm, arrayLayers: [0, 7, 2], extrasAt: 32, looks: [{ tint: [0.7, 0.75, 0.85], roughness: [0.3, 0.6] }], }; return [ { albedo, normal, orm, layers: warm }, { albedo, normal, orm, layers: cold }, ]; } ``` - **`arrayLayers`** names an array layer for each of the material's layers, base first. The same index reads all three arrays, so a texture's colour, normal and ORM sit at the same layer of each. - **`extrasAt`** is where this material's own maps start: an ORM mask, an added mask and a mesh occlusion in that order in the ORM array, and a mesh normal in the normal array. Absent, they sit just past the layers, which is no place for them once arrays are shared. - **`looks`**, one for each layer, base first: a `tint` multiplying its colour, linear and allowed above 1; the `roughness` and `metalness` ranges its ORM's green and blue are spread over, 0 to 1 where absent; a `normalStrength` its normal map's slopes are scaled by, 0 lying flat; and a `specular` in the units a mesh's vertices carry theirs, blended as the colours are, the surface's own where absent. - **A repeat may be a pair**, across and down apart: moss stretched along a trunk at `[4, 0.5]`. - **`meshOcclusion`** darkens the surface by the red of the ORM layer after the masks, read at the mesh's own coordinates, by a strength from 0 to 1: the large shading of a cliff, as `meshNormal` carries its large shape. A number darkens the blended colour, and so every light on it. The object form, `{ strength, into, range }`, can send it `into: 'ambient'` instead, darkening the ambient light alone as an ambient occlusion does and leaving the sun and the lamps as they were, and spreads its red over a `range`. These four are compiled into the lit stage the first time a material names one, as the layers are. A layered material that names none of them draws as it did, whether or not another one has. What it gives up: - **Every layer present is read wherever any shows**: five layers are fifteen reads where one material is three. - **A mask that is a map is read where a shading model's map goes**, so such a material carries no `modelMap`; given both, it is drawn as one layer, said once. A mask in the ORM array or the vertex colour leaves the slot free. Upload a mask as data, `colorSpace: 'linear'`. - **A mask, an added mask or a mesh normal in an array shares its size and format**, so a four-channel mask wants an ORM array that stores four. - **A triplanar projection lays layers on the horizontal plane**, said once: every layer read on three planes would be three times the reads. - **Layers share an array**, so they share its size and format, and a cutout reads the base layer's alpha. - **On WebGL2 it takes four fragment uniform vectors**, refused, said once, where a part has no room. Shared arrays and looks take fifteen more, refused on their own, said once, where a part has room for the layers and not for them: the layers then read layer `i` of their arrays, untinted, at one repeat each. ## Detail tiled over a surface A surface's finest grain, leather, a weave, brushed metal, a face's pores, is a small map repeated many times over it. Baked into the base maps it is lost: a 256-texel detail tiled forty times over a 2048-texel map would want some ten thousand texels a side. `detail` lays it on top of a material instead, each region of the surface with its own grain at its own repeat: ```ts /** * A jacket: leather grain over most of it, a denim weave on the collar and a brushed buckle, each * at its own repeat. The detail maps are one array: leather's normal 0, the weave's normal 1 and its * occlusion 2, the brushing 3. The region map is the ORM array's layer 1. */ export function jacket( albedo: SurfaceTextureHandle, normal: SurfaceTextureHandle, orm: SurfaceTextureHandle, maps: SurfaceTextureHandle, ): SurfaceMaterial { const detail: SurfaceDetail = { maps, regionLayer: 1, regions: [ { normalLayer: 0, repeat: 40, normalStrength: 0.8 }, { normalLayer: 1, occlusionLayer: 2, repeat: [24, 30], occlusionStrength: 0.6 }, { normalLayer: 3, repeat: 12, offset: [0.5, 0] }, ], }; return { albedo, normal, orm, detail }; } ``` - **`maps`** is an array whose layers the regions name: tangent-space normal maps, and occlusions in their red. It is read where a shading model's map goes, so a material with a `modelMap` puts its detail layers in that same array and names it here too. - **`regionLayer`** is the layer of the material's ORM array holding the region map: each texel's region as an index from 0 in its red, stored as `index / 255`, read exactly at the base coordinates so a region's edge is sharp. Absent, every texel is region 0: one detail all over, a face's pores. - **`regions`**, up to sixteen: each a `normalLayer`, an optional `occlusionLayer`, a `repeat` across the base coordinates, the same both ways or a pair, an `offset`, a `normalStrength` its slopes are scaled by and an `occlusionStrength` from 0 to 1. A texel naming a region past the last wears the last. Each texel reads its own region's detail alone, turned through a frame built on the normal the base maps made, and multiplies its occlusion into the surface's, so the base maps carry the shape and the detail rides on it. It is compiled into the lit stage the first time a material asks. What it gives up: - **The detail maps share the slot a shading model's map is read through.** A material whose `modelMap` is another array, or whose layers' mask is a map, is drawn without its detail, said once. - **The region map shares the ORM array's size and format**, and an index has to survive it exactly, so the array must be uncompressed: a compressed block blends neighbouring indices. - **A material placed by the world has no base coordinates** for its regions and repeats, so its detail is refused, said once. - **Sixteen regions are thirty-three vectors of the material's numbers.** On WebGL2 they are refused, said once, on a part with no room for them; a lower `maxLights` makes the room. On WebGPU every material's block grows by them, from 1,024 bytes to 1,536. ## Light through a thin surface A banner lit from behind, a leaf against the sun and a lampshade all show the light on their far side through themselves. `diffuseTransmission`, 0 to 1, is how much of it a material lets through: the sun, lamps, area lights and DriftLight falling on the far side reach the eye through the surface, coloured by its own colour, and are added to what lights its near side. A metal lets none through. ```ts /** Cloth seen from either side, letting most of the light behind it through. */ export function banner(cloth: SurfaceTextureHandle): SurfaceMaterial { return { albedo: cloth, doubleSided: true, diffuseTransmission: 0.7 }; } ``` `transmissionColor` names the colour the light takes instead, linear: a printed banner whose cloth glows a flat red behind the print, rather than lit through in the colours of the print. The surface is treated as thin: a sheet, not a volume, so a thick object lets as much through as a sheet would, and what passes is not blurred. A lamp's own shadow does not hide its light from the surface it shines through. Glass has its own way through (see [Translucent and additive meshes](https://driftengine.dev/docs/rendering/translucency)) and ignores this. ## Reflections A metal is only as convincing as what it reflects. With nothing else set up, it reflects a sky and ground gradient. [Reflections](https://driftengine.dev/docs/rendering/reflections) covers baked probes, environment images, planar mirrors and screen-space reflections. ## Four things that look wrong - **A material that does nothing on a sphere.** `MeshBuilder` shapes carry no texture coordinates unless you ask with `planarUvs`, and without them every pixel samples the same texel. - **A normal map that shades oddly or not at all.** The mesh has no tangents. Add them with `generateTangents`. - **Every surface looks like glass.** The ORM map was uploaded as sRGB, so its roughness collapsed toward zero. - **Hair whose bright highlight sits toward the tips.** The cards' tangents run tip to root. Pass `hairModel` a negative `shift`. --- # Texture arrays and surface effects Rendering. https://driftengine.dev/docs/rendering/texture-arrays Many images as one texture, chosen per vertex, so a merged mesh of many materials is one draw, with lit windows, rooms, wear and rain. A material binds one albedo, so a mesh that wears forty different facades would normally be forty meshes, forty draws and forty material changes. A texture array holds many images of one size as a single texture, and each vertex names the layer its face wears. One merged mesh, one draw, one material change. ## Building an array ```ts /** * Three images of one size: a facade whose windows are holes in its alpha, a sign, and the room a * window looks into. Each layer's effects are given beside it; a layer with none is `undefined`. */ export function facadeArray(renderer: RendererApi, images: readonly HTMLImageElement[]) { return renderer.createSurfaceTextureArray(images, { colorSpace: 'srgb', effects: [ { windows: { cells: [6, 12], glass: true, glow: 1.2, seed: 3 }, interior: { roomLayer: 2, depth: 0.5, lit: 0.7 }, wear: { grime: 0.35, streaks: 0.25, fade: 120 }, }, { animation: { scroll: [0.15, 0], pulse: [0.5, 0.3] } }, undefined, ], }); } ``` `createSurfaceTextureArray` returns the same kind of handle a single image does; every surface texture is an array, and a plain image is an array of one. So an array goes wherever a texture goes, into any map of a material, and every map of the material is read at the vertex's layer. An albedo array and an emissive array built in the same order pair each image with its glow by index. Every layer shares one size, because the device allocates one size for all of them. A small sign in an array of large facades pays for the large size. ## Choosing a layer per vertex ```ts /** * A builder has no layer channel, so each piece is built, given its layer, then joined. Rooms behind * windows are drawn through the mesh's tangent frame, so the pieces get tangents as well. */ function onLayer(mesh: MeshData, layer: number): MeshData { const uvs = mesh.uvs ?? new Float32Array((mesh.positions.length / 3) * 2); return { ...mesh, tangents: generateTangents(mesh.positions, mesh.normals, uvs, mesh.indices), layers: new Float32Array(mesh.positions.length / 3).fill(layer), }; } export function building(): MeshData { const tower = new MeshBuilder() .addBox([0, 20, 0], [8, 20, 8], [1, 1, 1]) .build({ planarUvs: true }); const sign = new MeshBuilder() .addQuad([-4, 3, 8.05], [4, 3, 8.05], [4, 5, 8.05], [-4, 5, 8.05], [1, 1, 1], 1) .build({ planarUvs: true }); return concatMeshes([onLayer(tower, 0), onLayer(sign, 1)]); } ``` `MeshData.layers` is one whole number per vertex, 0 for the first image. `MeshBuilder` has no layer channel, and merging a layered mesh into a builder is refused instead of silently putting every face on layer 0, so build each piece, give it its layer, and join them with `concatMeshes`. A facade with rooms behind its windows also needs a tangent frame, which `generateTangents` supplies; without one, the windows still light but the rooms are not drawn. The `.drft` container carries layers, so a baked model keeps them. ## What a layer can do Each layer may carry an effect, given in `effects` when the array is built. A layer with no effect draws exactly as an image would. **Windows.** `windows.cells` divides one repeat of the layer into a grid of windows. With `glass`, the albedo's alpha says where the glass is: 0 is a window, 1 is wall. A window can glow, by `glow` and `colour`; a vertex that names an emissive colour overrides it, so many buildings sharing one layer each keep their own window light. `seed` varies which windows do what between facades. **Rooms behind windows.** `interior` draws a room seen in parallax behind each window, from another layer of the same array: one image of a room in one-point perspective. `depth` is how deep the room is, and `lit` the share of rooms with a light on. **Wear.** `wear` adds procedural dust, grime and rain streaks, each 0 to 1, fading out past `fade` metres so a distant facade stays clean. **Animation.** `animation` scrolls the layer, pulses or flickers its emission, or plays successive layers as a flipbook, on the caller's clock. **Staying dry.** `dry` marks a layer that rain leaves alone: a covered walkway, an indoor floor. ## The scene's half ```ts /** The scene's half: how wet it is, how many windows are lit, and the clock the animations run on. */ export const NIGHT = createEnvironment({ directionalDir: [0.2, 0.9, 0.3], directionalColor: [0.2, 0.24, 0.35], ambient: [0.05, 0.06, 0.09], nightFactor: 1, emissiveGain: 1, litWindows: 0.45, lateWindows: 0.08, wetness: 0.3, surfaceTime: 0, }); ``` The environment carries the values effects read across the whole scene: - `litWindows`, the share of windows lit, which a scene sets from its time of day. Windows switch on one at a time, by a hash per window, so a rising share lights more windows instead of brightening the ones already lit. - `lateWindows`, the share that stays lit however late it gets. - `wetness`, from 0 to 1: upward surfaces darken and polish, except layers marked `dry`. - `surfaceTime`, the clock animations run on. It is yours, so a paused or replayed game holds every sign still or replays it exactly. Window light comes from the window effect itself, not from the emissive term, so it does not wait for the environment's `nightFactor`. ## Cost A scene that names no effect draws exactly what it drew before. The effects table is one small texture beside the array, bound whenever the array is a material's albedo. --- # Instancing Rendering. https://driftengine.dev/docs/rendering/instancing Thousands of copies of one mesh in one call, culled, moved every frame or played as a crowd, still draws recorded once, and foliage in the wind. Drawing a mesh a thousand times with `drawMesh` costs a thousand draws and, if the material changes between them, a thousand material changes. An instanced batch draws every copy in one call, with one material, from an array of model matrices and tints. (This chapter runs the `instancing` example at https://driftengine.dev/docs/rendering/instancing.) ## A batch ```ts /** A lumpy rock: a sphere whose radius varies by a hash of where on it you are. */ const rock = renderer.createMesh( new MeshBuilder() .addBlob( [0, 0.35, 0], (u, v) => 0.5 + hashToUnit(Math.floor(u * 7) * 31 + Math.floor(v * 5)) * 0.18, [0.55, 0.52, 0.48], ) .build(), ); const REGIONS = 4; const PER_REGION = 625; const SPAN = 120; const random = mulberry32(7); /** One batch per region, so a region out of view is skipped in one test. */ const fields: { batch: InstancedHandle; data: MeshInstances }[] = []; for (let rx = 0; rx < REGIONS; rx += 1) { for (let rz = 0; rz < REGIONS; rz += 1) { const data = createMeshInstances(PER_REGION); for (let i = 0; i < PER_REGION; i += 1) { const x = (rx + random()) * (SPAN / REGIONS) - SPAN / 2; const z = (rz + random()) * (SPAN / REGIONS) - SPAN / 2; place(data.models, i, x, 0, z, random() * Math.PI * 2, 0.2 + random() * 0.8); const shade = 0.42 + random() * 0.3; data.tints.set([shade, shade * (0.95 + random() * 0.1), shade * 0.95], i * 3); } data.count = PER_REGION; const batch = renderer.createInstanced(rock, PER_REGION, { cull: true }); renderer.uploadInstanced(batch, data); fields.push({ batch, data }); } } ``` `createMeshInstances(capacity)` allocates the per-instance arrays once: `models`, sixteen floats per instance, and `tints`, three, multiplied into the mesh's colour as a `drawMesh` tint is. `count` says how many are live. `createInstanced(mesh, capacity, options)` attaches a batch to a mesh you already uploaded, so a model with tens of thousands of triangles is not copied again. `uploadInstanced` sends the arrays to the device. ```ts /** Write a model matrix that scales, turns about Y and moves, into slot `i` of a batch. */ function place( out: Float32Array, i: number, x: number, y: number, z: number, yaw: number, s: number, ): void { const o = i * 16; const c = Math.cos(yaw) * s; const n = Math.sin(yaw) * s; out[o] = c; out[o + 1] = 0; out[o + 2] = -n; out[o + 3] = 0; out[o + 4] = 0; out[o + 5] = s; out[o + 6] = 0; out[o + 7] = 0; out[o + 8] = n; out[o + 9] = 0; out[o + 10] = c; out[o + 11] = 0; out[o + 12] = x; out[o + 13] = y; out[o + 14] = z; out[o + 15] = 1; } ``` A model matrix is sixteen floats, column-major. This helper writes one that scales, turns about Y and translates, which is most of what scattered props need. ## Culling a batch `{ cull: true }` tests the whole batch first, its enclosing box against the view and against any declared occluders, and skips it in one test when it is out of sight. Then it tests each instance by its bounding sphere. On WebGL2 the survivors are compacted on the CPU; on WebGPU a compute pass writes an indirect draw, and the two are held to the same result. **One batch per region**, as in the example, is what makes the first test pay: a region behind the camera costs one box test for all of its rocks. A mesh may have as many batches as you have regions. Compaction does not keep instance order. That is invisible for opaque geometry, and it is why blended batches are not culled on the GPU. ## Moving instances ```ts /** Crystals circling the middle: the same batch, rewritten in place every frame. */ const CRYSTALS = 240; const crystal = renderer.createMesh( new MeshBuilder().addCylinder([0, 0.6, 0], 0.18, 0.6, 'y', [0.55, 0.85, 1], 1.2, 6).build(), ); const ring = createMeshInstances(CRYSTALS); ring.count = CRYSTALS; for (let i = 0; i < CRYSTALS; i += 1) ring.tints.set([1, 1, 1], i * 3); const ringBatch = renderer.createInstanced(crystal, CRYSTALS); function moveCrystals(time: number): void { for (let i = 0; i < CRYSTALS; i += 1) { const a = (i / CRYSTALS) * Math.PI * 2 + time * 0.2; const r = 14 + Math.sin(i * 1.7 + time) * 2; place( ring.models, i, Math.cos(a) * r, 1 + Math.sin(time * 1.5 + i) * 0.8, Math.sin(a) * r, time + i, 1, ); } renderer.uploadInstanced(ringBatch, ring); } ``` A batch whose instances move is rewritten in place and uploaded every frame. Nothing is allocated, because the arrays were sized at creation and only `count` instances are written. ## Drawing ```ts render() { camera.position[0] = Math.sin(time * 0.05) * 40; camera.position[1] = 9; camera.position[2] = Math.cos(time * 0.05) * 40; camera.lookAt(0, 1, 0); moveCrystals(time); renderer.beginFrame(CLEAR); renderer.bindMeshPass(camera, ENV); renderer.drawMesh(ground, still.worldMatrix); for (let i = 0; i < fields.length; i += 1) renderer.drawInstanced(fields[i].batch, fields[i].data); renderer.drawInstanced(ringBatch, ring); renderer.endFrame(); }, ``` `drawInstanced` draws with whatever material is set, exactly as `drawMesh` does, and spends one slot of the frame's material ring for the whole batch. `drawTranslucentInstanced` is the blended twin, for glass and other see-through instances; see [Translucent and additive meshes](https://driftengine.dev/docs/rendering/translucency). ### Each instance its own opacity ```ts /** Panes pulsing out of step: an opacity an instance, uploaded with the rest of the batch. */ export function fadingPanes( renderer: RendererApi, batch: InstancedHandle, panes: MeshInstances, time: number, ): void { const alphas = panes.alphas; if (alphas !== undefined) { for (let i = 0; i < panes.count; i += 1) alphas[i] = 0.5 + 0.5 * Math.sin(time + i); } renderer.uploadInstanced(batch, panes); renderer.drawTranslucentInstanced(batch, panes, 1); } ``` `MeshInstances.alphas` holds one opacity an instance, 1 by default, which a translucent draw multiplies into the batch's own. So particles fading at different rates, or panes at different clarity, are one draw rather than a batch for each opacity. An opaque draw ignores it, unless it spends it on a screen door. ### An opaque instance faded by a screen door ```ts /** * Walls stepping out of the camera's way one at a time: each wall's opacity spent on a screen door, * so the batch stays opaque, needs no sorting and is lit as it was. */ export function clearTheView( renderer: RendererApi, batch: InstancedHandle, walls: MeshInstances, opacity: Float32Array, ): void { const alphas = walls.alphas; if (alphas !== undefined) { for (let i = 0; i < walls.count; i += 1) alphas[i] = opacity[i] ?? 1; } renderer.uploadInstanced(batch, walls); renderer.setDitherOpacity(true); renderer.drawInstanced(batch, walls); renderer.setDitherOpacity(false); } ``` `setDitherOpacity(true)` makes the draws that follow keep each instance's opacity as a share of its pixels, chosen by an 8 by 8 pattern, and draw the rest not at all. Nothing is blended or sorted, an instance at 1 is drawn whole and one at 0 is not drawn, and a wall half gone is lit and shadowed as a whole one is. It is per draw like the material dials and `bindMeshPass` turns it off. The pattern is the one `setDitherFade` uses, so a level of detail crossfading while its instance fades still covers that instance's share of the pixels once. What it gives up: a fade reads as grain while it lasts, which a temporal resolve smooths and a plain frame does not, so keep it to a few frames. Shadows are cast whole. A lightmapped batch fades too: its opacities ride its page regions, in steps of a sixty-fourth, which is the pattern's own resolution. ### Each instance its own texture cell ```ts /** A batch whose instances each name a cell of a flipbook of `frames` frames in one row. */ export function createFlipbookBatch(capacity: number) { return { ...createMeshInstances(capacity), uvRegions: new Float32Array(capacity * 4) }; } /** Each particle on its own frame: the cell's scale, then its offset, per instance. */ export function showFrames( renderer: RendererApi, batch: InstancedHandle, particles: ReturnType, frameOf: (particle: number) => number, frames: number, ): void { for (let i = 0; i < particles.count; i += 1) { particles.uvRegions.set([1 / frames, 1, frameOf(i) / frames, 0], i * 4); } renderer.uploadInstanced(batch, particles); renderer.drawTranslucentInstanced(batch, particles, 1); } ``` `MeshInstances.uvRegions` holds four numbers an instance, `[scaleU, scaleV, offsetU, offsetV]`, applied to the mesh's texture coordinates before the material's own `uScale` and `uOffset`. Mesh particles each on their own frame of a flipbook, or props wearing different tiles of one atlas, are one draw rather than a batch for each cell. Absent, every instance wears the whole texture. It applies to opaque and translucent draws alike, and a cutout instance's shadow is cut by its own cell. The cell rides the bottom row of the instance's matrix, which a placement made of a turn, a scale and a move leaves unused, so an instanced placement must be affine; every placement of a solid object is. An instanced batch can cast shadows: the shadow caster sink accepts instanced batches as well as meshes. Instancing gives up skinning and morph targets on the instanced mesh, because every instance would share one pose. A crowd plays a bone animation instead. ## A crowd: bone animation in the vertex stage ```ts /** One figure placed many times, each copy playing `clip` from a phase and at a rate of its own. */ export function createCrowd( renderer: RendererApi, figure: MeshHandle, clip: BoneAnimationClip, places: readonly Float32Array[], ) { const animation = renderer.createBoneAnimation(clip); const batch = renderer.createInstanced(figure, places.length, { animation }); const crowd = { ...createMeshInstances(places.length), clocks: new Float32Array(places.length * 2), }; places.forEach((model, i) => { crowd.models.set(model, i * 16); crowd.clocks[i * 2] = i * 0.37; // a phase, in seconds crowd.clocks[i * 2 + 1] = 0.9 + (i % 5) * 0.05; // a rate: 1 is the clip's own speed }); crowd.count = places.length; renderer.uploadInstanced(batch, crowd); return { animation, batch, crowd }; } ``` `createBoneAnimation(clip)` takes a clip as a turn and a place for each bone at each of its frames, and `InstancedOptions.animation` plays it on every instance of a batch. Each vertex follows one bone: the one its mesh's second coordinates name, u times the clip's `boneScale`, so the figure's mesh must carry `lightmapUvs`. `MeshInstances.clocks` holds a phase in seconds and a rate an instance, and `setAnimationTime(seconds)` sets the clock they all read. Set it once a frame **before the shadows are drawn**, as the wind is set, or a figure and its shadow play different moments. Every instance then moves at the frame's rate and out of step with its neighbours, in the colour pass and in every shadow, with nothing on the processor. What it gives up against skinning is the blend, since a vertex follows one bone; an animated batch is culled whole rather than instance by instance; and under DriftTR or temporal antialiasing a crowd's own movement is not in the frame's motion, so a fast clip seen large softens a little. `disposeBoneAnimation` releases the clip. ## Static draws: recorded once, replayed every frame ```ts /** A stage's props that never move, enumerated once and kept: replay it each frame instead. */ export function recordStage( renderer: RendererApi, props: readonly { mesh: MeshHandle; model: Float32Array; material: SceneCasterMaterial }[], ): StaticDrawsHandle { return renderer.createStaticDraws((sink) => { for (const prop of props) sink.mesh(prop.mesh, prop.model, prop.material); }); } ``` `createStaticDraws` takes the same enumeration `drawSceneCasters` does, once, and keeps it: rigid meshes and instanced batches, each with its material. `drawStaticDraws(stage)` draws it into the open mesh pass under whatever camera, lights and fog `bindMeshPass` set, so the same list serves the frame, a mirror and a capture. On WebGPU a list is a render bundle for each view, replayed with one call and recorded again only when something it was recorded against changes; WebGL2 replays the entries itself, and the picture is the same. 412 draws cost a frame 0.65 ms of main thread drawn one by one and 0.13 ms as a list. A list draws whole in every view, so it culls by list: split a world into lists by region and draw the ones in view. A skinned mesh or a scatter batch is refused, since both change every frame. The meshes, batches and materials stay yours: dispose the list, or make it again, before anything it holds, and make it again when a material it holds changes. `disposeStaticDraws` releases it. ## Foliage: scatter batches `createScatter(base, data)` is a different kind of batch, for grass, flowers and small plants. It owns its own base geometry, sways with the wind you pass to `drawScatter`, and is uploaded once at creation, since foliage never moves. Call `uploadScatter` only for a scatter that does. A scatter is lit by the sun and the ambient only, never by point lights: a field of grass shaded by every lamp in the scene is a cost nobody wants. Anything a lamp must reach belongs in a mesh or an instanced batch instead. --- # Splines, ribbons and lines Rendering. https://driftengine.dev/docs/rendering/splines-and-lines Curves sampled by arc length, banked surfaces swept along them with gaps and colliders, the exact ground on a route, and world-space strokes with real width. Three tools for anything that follows a path: a `Spline` says where the path goes, `buildRibbon` sweeps a surface along it, and `RibbonSurface` answers where the ground is on it. Separately, a line batch draws strokes with a real width in metres, for trajectories, trails and debug rays. ## A spline ```ts /** Control points carry a bank, in radians, and a width, in metres, as well as a position. */ const points: SplinePoint[] = [ { x: 0, y: 0, z: 0, bankRad: 0, widthM: 8 }, { x: 40, y: 4, z: -30, bankRad: 0.35, widthM: 7 }, { x: 90, y: 2, z: -20, bankRad: -0.2, widthM: 7 }, { x: 130, y: 10, z: 30, bankRad: 0, widthM: 9 }, ]; const route = new Spline(points); console.info(`${route.lengthM.toFixed(1)} m long`); ``` `Spline` is a Catmull-Rom curve **sampled by arc length**, so samples are evenly spaced in metres whatever the curve does. Sampling by parameter bunches them in tight corners and stretches them on straights, which would give a swept surface huge triangles on the fast sections and a width that pulses through every bend. Each control point carries a bank, the roll about the direction of travel, and a width. Both follow the points through a smooth curve, so there is no crease at a control point. `sampleAt(distanceM, out)` gives the position at a distance along the route with its frame: the tangent, the surface normal after banking, and the right-hand direction. The frame is carried along from the previous sample, never rebuilt from world up, so it cannot flip when the route climbs vertically. ## A ribbon ```ts /** A slab swept along the route, with one gap a player has to jump. */ export function buildRoute(renderer: RendererApi) { const holes = [{ fromM: 70, toM: 78 }]; const { mesh, colliders } = buildRibbon(route, { color: [0.36, 0.38, 0.44], stepM: 1, thicknessM: 0.6, holes, }); const surface = new RibbonSurface(route, { holes }); return { mesh: renderer.createMesh(mesh), colliders, surface }; } ``` `buildRibbon` sweeps a closed slab along the spline and returns mesh data and colliders built from the same corners, so what you see is what you hit. **Holes** are stretches where the surface isn't there; geometry and colliders both respect them, because a gap that is drawn but still solid looks like a jump and plays like a floor. The options build more than a road: `edgeBandM` and `edgeSide` build only a strip along one edge, `lateralFromM` and `lateralToM` a band between two offsets, `liftM` raises it, so a kerb or a painted line is another ribbon over the same spline. `shade` varies the colour per cross-section, and `fromM` and `toM` build one stretch. ## The ground on a route ```ts const hit = createSurfaceHit(); /** Where the ground is in a column, and where along the route that is. */ export function groundUnder( surface: RibbonSurface, x: number, z: number, y: number, ): number | null { if (!surface.sample(x, z, hit, y)) return null; // over a gap, or off the route // hit.distanceM is how far along, hit.lateralM how far off the centre line, hit.normal* the face. return hit.y; } ``` `RibbonSurface` answers the question a character controller and a vehicle actually ask: in this column, where is the surface, and which way does it face? It answers with the exact banked surface, not the colliders' boxes, whose flat tops sit at the height of the highest corner. It also says how far along the route the point is, how far off the centre line, and how much width is left before the edge, which is most of what a racing game's rules need. A query costs a grid lookup and a fixed number of Newton steps. The count is fixed so that it is the same on every machine, which [determinism](https://driftengine.dev/docs/concepts/determinism) needs. `RibbonSurface` is one kind of `GroundSurface`. `BoxSurface` is another, for flat pads; `heightSurface` wraps a function of your own, or several stacked, so a road can pass under a road; `colliderSurface` turns a set of colliders into ground; and `CompositeSurface` asks several and keeps the best answer. The character controller and the vehicle both take one as their `ground`. ## Lines with real width (This chapter runs the `lines` example at https://driftengine.dev/docs/rendering/splines-and-lines.) WebGL2 draws one-pixel lines on almost every driver, and WebGPU draws no wide lines at all, so the engine expands each segment into a quad that faces the camera. ```ts /** One stroke of 220 segments, allocated once. `capacity` is segments, not points. */ const POINTS = 221; const segments = createLineSegments(POINTS - 1); const batch = stage.renderer.createLines(POINTS - 1, 'example-trail'); const path = new Float32Array(POINTS * 3); ``` A segment buffer and a line batch are allocated once, at a fixed capacity. `capacity` counts segments, one fewer than the points that make them. ```ts segments.count = setPolyline(segments, path, POINTS); stage.renderer.beginFrame(CLEAR); stage.renderer.bindMeshPass(stage.camera, DAYLIGHT); stage.renderer.drawMesh(ground, still.worldMatrix); stage.renderer.drawLines( batch, segments, still.worldMatrix, stage.camera, DAYLIGHT, STROKE, width, 1, softness, /* The floor: at least two millimetres of half-width per metre away, about a pixel. */ 0.002, ); ``` `setPolyline` rewrites the buffer in place from a flat list of points and returns how many segments are live. `drawLines` takes the batch, the segments, a model matrix, the camera, the environment, then a colour, a width **in metres**, an opacity, an edge softness, and a minimum width per metre of distance, which stops a far stroke from thinning below a pixel and flickering. A last `additive` argument makes a stroke add light instead of covering what is behind it. Lines are blended and fogged like anything else in the world. For a stroke that is light itself, an arc or a beam, see [Particles and effects](https://driftengine.dev/docs/rendering/particles), which draws bolts. --- # Translucent and additive meshes Rendering. https://driftengine.dev/docs/rendering/translucency Glass that colours the light through it, refraction, light that adds instead of covering, untoned draws, and transparency in any order. `drawTranslucentMesh(mesh, model, opacity, options)` draws a mesh blended over what is already in the frame. Draw translucent things after the opaque ones they show, and, unless order-independent transparency is on, back to front among themselves. ## Glass ```ts /** A frosted green pane: it lets light through, blurs what is behind it, and tints it. */ export function drawPane(renderer: RendererApi, pane: MeshHandle, model: Float32Array): void { renderer.drawTranslucentMesh(pane, model, 1, { glass: { transmission: 0.85, frost: 0.35, tint: [0.75, 0.95, 0.85] }, }); } ``` `glass` makes a pane that shows what is behind it by how much light it lets through and how little it reflects at the angle you see it from, blurred by how frosted it is and tinted by its colour. It keeps its own highlight. Glass also casts coloured light. With the `glassShadows` quality option at its default, `'full'`, light that passes through a pane takes its colour in the sun's and the lamps' shadows: a stained window throws a coloured patch on the floor. `'half'` halves the memory that costs, and `'off'` makes glass cast nothing. ## Refraction ```ts /** A thick lens that bends what is behind it and absorbs a little per metre, as real glass does. */ export function drawLens(renderer: RendererApi, lens: MeshHandle, model: Float32Array): void { renderer.drawTranslucentMesh(lens, model, 0.25, { refraction: 0.02, refractTint: [0.92, 0.97, 1], thicknessM: 0.08, }); } ``` `refraction` bends what is behind the surface, by sampling a copy of the frame's colour offset along the shading normal, so a normal map bends it too: a heat haze or a distortion wearing a noise map shimmers rather than acting as a smooth lens. An unlit draw reads its normal map for this alone. `refractTint` is what survives one metre of the medium, per channel, and `thicknessM` is how many metres the light crosses face-on; absorption follows the Beer-Lambert law, so a thick piece of tinted glass is darker than a thin one. A per-vertex channel can vary thickness across a mesh. A frame that refracts nothing takes no copy and pays nothing. ## Adding light ```ts /** A lamp's light cone: added onto what is there, so its dark parts are invisible, not black. */ export function drawBeam(renderer: RendererApi, cone: MeshHandle, model: Float32Array): void { renderer.drawTranslucentMesh(cone, model, 0.6, { additive: true, lit: false, depthWrite: false }); } ``` `additive: true` adds the mesh's colour times its opacity onto what is there and never darkens it. That is the right blend for light itself: a lamp's beam, a glow shell, a spark. Drawn blended, the dark parts of a light cone would show as a dark cone; drawn additively they are invisible. A sum needs no order, so additive draws are never held back for sorting. ## Exactly its own colour ```ts /** A marker that is exactly its colour, untouched by light, haze or the tone curve. */ export function drawMarker(renderer: RendererApi, marker: MeshHandle, model: Float32Array): void { renderer.drawTranslucentMesh(marker, model, 0.9, { lit: false, fog: false, toneMapped: false }); } ``` `lit: false` draws the mesh as its vertex colour times its texture, with no lighting of any kind. `fog: false` keeps it out of the haze and the underwater tint. `toneMapped: false` skips the tone curve, which is right for a meter or an interface element whose colour must be exact. The three are independent. ## When order matters Blending is order-dependent: a pane drawn after another pane behind it composes correctly, and the other way round does not. Sorting back to front fixes most scenes and cannot fix two panes that intersect, a pane inside another, or a pane with smoke inside it. The `orderIndependent` quality option replaces the ordering with weighted blending, whose sum and product do not depend on order. It is exact for one layer and a close approximation for several. Off by default. Two options decide how a set of blended surfaces resolves against itself: - `depthWrite: false` keeps a draw out of the depth buffer, which a set of overlapping panes, or a model whose interior is glass, wants. One pane alone should write depth, or the sky drawn later paints over it. - `depthLayer` orders surfaces that lie exactly on top of each other, such as a sign on a wall. ## Instanced `drawTranslucentInstanced(batch, data, opacity, options)` is the same for an instanced batch. It takes the same options except a per-vertex thickness, which an instanced draw cannot carry. --- # Decals Rendering. https://driftengine.dev/docs/rendering/decals Marks on surfaces two ways: baked into a mesh once from its own triangles, or projected every frame onto whatever was drawn. A mark on a surface, such as a scorch, a puddle, a stain or a painted line, can be made two ways, and which one you want depends on whether the surface it lands on changes. ## Baked into a mesh ```ts /** A scorch mark on a road: the road's own triangles, clipped to a box and lifted off it. */ export function scorch(renderer: RendererApi, road: MeshData, x: number, y: number, z: number) { return renderer.createMesh( projectDecal(road, { center: [x, y, z], halfExtents: [1.2, 1.2, 0.6], forward: [0, -1, 0], up: [0, 0, 1], color: [0.2, 0.18, 0.16], }), ); } ``` `projectDecal` clips the receiving mesh's own triangles to a projector box and returns new mesh data, lifted a couple of millimetres off the surface. It is exact, it is lit exactly as the surface is lit, and after the frame that built it, it costs one ordinary draw. It is decided once, against the mesh as it stood, so it suits anything static: road markings, stains on a wall, a crater. The box is a centre, half extents across, up and along the projection, the direction the mark is projected along, and which way is up in the mark. `facingCos` limits how far a surface may turn away from the projector and still be marked, so a mark on a floor doesn't smear down the side of a step. ## Projected every frame ```ts /** A wet patch that follows a moving thing, decided each frame from the depth already drawn. */ const wet = new DecalProjector({ center: [0, 0, 0], halfExtents: [1.2, 1.2, 0.6], forward: [0, -1, 0], up: [0, 0, 1], color: [0.55, 0.6, 0.7], softness: 0.6, }); /** After the opaque geometry it lands on, before `endFrame`. */ export function drawWetPatch(renderer: RendererApi, x: number, y: number, z: number): void { wet.setPose([x, y + 0.3, z], [0, -1, 0], [0, 0, 1]); renderer.drawDecal(wet); } ``` A `DecalProjector` stays alive, and `drawDecal` marks whatever the frame has drawn inside its box, from the depth buffer. That is what a surface that deforms, streams in, or has no geometry on the CPU needs: cloth, a heightfield being rewritten, a skinned character, an instanced crowd. `setPose` and `setSize` move it without allocating, so a mark can follow something every frame. A projected mark **multiplies** what is under it: it darkens and tints, takes the receiver's lighting, and cannot brighten. White marks nothing and black is a hole. Its shape is a soft-edged ellipse, and `softness` sets how much of its radius is edge. It needs `screenEffects`, because it reads the frame's depth; without it, the renderer says so on the console and draws no marks. A frame draws at most thirty-two. ## Laid into the base colour A projected mark multiplies the finished pixel, so where the surface under it glows, a lettered floor or a lit panel, the mark dims the glow as well. A shadow a body throws on a lit floor, a footprint or a stain changes what the surface is instead: it darkens the colour light falls on and leaves what the surface emits, its roughness and its normal as they are. `setBaseDecals` lays such marks, each a box like a projector's, an image read across its face, and how much of it lands: ```ts /** A shadow under something standing on the floor, its box moved in place each frame. */ const under: [number, number, number] = [0, 0.2, 0]; const shadow: BaseDecal & { opacity: number } = { center: under, halfExtents: [0.3, 0.4, 0.5], forward: [0, -1, 0], up: [0, 0, -1], image: 0, opacity: 1, }; const laid: BaseDecal[] = [shadow]; /** Once a frame, before the draws it marks: its image redrawn, its box moved, fading with height. */ export function layShadow( renderer: RendererApi, images: readonly HTMLCanvasElement[], x: number, z: number, height: number, ): void { under[0] = x; under[2] = z; shadow.opacity = Math.max(0, 1 - height); renderer.setBaseDecalImages(images); renderer.setBaseDecals(laid); } ``` The base colour moves toward the image's colour by its alpha times `opacity`, before any light is added, and the surface is then lit and glows as it would. An image is a square of `BASE_DECAL_TILE` texels, 128, read as a picture: its colour is decoded from sRGB and its alpha is as it is. Rewriting the images once a frame is what they are for and costs an upload of the squares; changing how many there are costs more. The decals are held until the next call, across passes, so a reflection shows them too. `facingCos`, 0.2 by default, keeps a mark aimed at a floor off the sides of what stands on it, judged by the geometric normal so a normal map's bump does not cut it. A surface that stands in a decal's box and is not what it lands on, such as a body over its own shadow, says `receivesDecals: false` in its material. A frame lays at most eight. They take thirty-four of the lit shader's uniform vectors, so WebGL2 refuses them, saying so once, on a part that has no room, and the GPU-driven pipeline does not draw them. ## Which to use | | Baked, `projectDecal` | Projected, `drawDecal` | Base colour, `setBaseDecals` | | -------------- | --------------------------------- | ---------------------------------------------- | --------------------------------------- | | Surface | Static mesh you hold the data for | Anything drawn, including moving and deforming | Anything drawn by the lit pass | | Cost per frame | One draw | One pass over the box's pixels | A test per decal in every lit pixel | | Look | Any colour, lit, can glow | Multiplies only; an ellipse | An image, lit, leaves the glow as it is | | Needs | The mesh data | `screenEffects` | Room for 34 uniform vectors on WebGL2 | | Limit | None | 32 a frame | 8 a frame | For marks that must survive a replay, such as a scorch left by a weapon that a replay must reproduce, the writable texture overlay records every mark in the game's input log; see the Worlds section. --- # Lights Rendering. https://driftengine.dev/docs/rendering/lights Point lights, spots, rectangular lights, measured photometric profiles and cookies, how a frame picks the lights it shades, and thousands of them. A scene is lit by the environment, which carries one directional light and a hemispheric ambient fill, and by any number of fixtures: point lights, spots and rectangles. Emissive surfaces add light of their own colour. This chapter is about the fixtures; the sun, the sky and the air are in [Sky and atmosphere](https://driftengine.dev/docs/rendering/sky-and-atmosphere), and the shadows the sun casts are in [Shadows](https://driftengine.dev/docs/rendering/shadows). (This chapter runs the `lights` example at https://driftengine.dev/docs/rendering/lights.) ## Point lights ```ts /** Two lamps on posts, one of them flickering, and a downlight aimed at the floor between pillars. */ const lamps: PointLightSource[] = [ { x: -6, y: 2.7, z: 1.5, r: 2.4, g: 1.5, b: 0.7, radius: 10, flicker: 0, shadowNear: 0.2, sourceRadius: 0.08, }, { x: 6, y: 2.7, z: 1.5, r: 2.4, g: 1.3, b: 0.55, radius: 10, flicker: 0.3, shadowNear: 0.2, sourceRadius: 0.08, }, { x: 0, y: 4.5, z: -2, r: 4.5, g: 3.6, b: 2.6, radius: 9, flicker: 0, shadowNear: 0.2, sourceRadius: 0.05, dirX: 0, dirY: -1, dirZ: 0, coneInnerDeg: 70, coneOuterDeg: 85, iesProfile: 0, }, ]; ``` A `PointLightSource` is a position, a colour and a `radius`: the distance at which its light reaches zero. Colours are linear and may exceed one, which is how a light is made brighter. - `flicker` modulates the colour; zero keeps the light steady. It is driven by the time you pass to the selection, so a held clock holds every flame still and a replay flickers the same way. - `sourceRadius` is the emitter's size in metres. It widens the shadow's penumbra and spreads the highlight a polished surface shows, so a lamp close to a glossy panel reads as a small bright disc instead of a speckle. - `shadowNear` is where its shadow begins, and the next sections explain why it matters. How a light fades is a quality option. `pointLightFalloff: 'smooth'`, the default, shapes the curve to the radius, zero exactly at the edge and gentle near the source. `'inverseSquare'` is the physical law, windowed so the light still ends at its radius, and is far brighter close in. The strip under the example switches between them. A light may name its own fall instead, with `falloffExponent`: `(1 - (d/R)^2)^n`, `R` its radius and `n` the exponent, with no distance term at all. It is the falloff other tools give a light without inverse-square falloff, so a rig authored in one keeps its shape: a fill meant to light a whole hall across a hundred metres does, where the inverse square would have it gone a few metres out. Absent or 0, the light takes the frame's falloff. Each chosen light's exponent reaches the environment as `env.lightFalloffExponents`, filled from the selection's `falloffExponents` beside the cones. Water, DriftLight's volume and DriftRay's bounce read it too, so the light falls the same way on every surface it reaches. ## Choosing the lights a frame shades ```ts /** Sized from the renderer, so the shader shades the nearest lights and never an arbitrary few. */ const chosen = createPointLightBuffer(renderer.shadedLights); function chooseLights(focusX: number, focusZ: number): void { const eye = scene.camera.position; selectPointLights( lamps, eye[0], eye[1], eye[2], chosen, time, DEFAULT_POINT_LIGHT_VIEW_RANGE, focusX, 0.6, focusZ, ); env.lightCount = chosen.count; env.lightPositions = chosen.positions; env.lightColors = chosen.colors; env.lightRadii = chosen.radii; env.lightSourceRadii = chosen.sourceRadii; env.lightWeights = chosen.weights; env.lightDirections = chosen.directions; env.lightConeCos = chosen.coneCos; env.lightIesProfiles = chosen.iesProfiles; env.lightFalloffExponents = chosen.falloffExponents; env.activeLightWorldIndices = chosen.sourceIndex; for (let slot = 0; slot < chosen.count; slot += 1) { const spot = chosen.sourceIndex[slot] === SPOT; /* The cookie's tile, and which way is up in it: a cookie with no axis is not projected. */ env.lightCookies[slot] = spot ? 0 : -1; env.lightIesAxes[slot * 3] = spot ? 1 : 0; } env.areaLights = windowBuffer; } ``` A world may hold thousands of lights, and a frame shades the nearest few. `selectPointLights` picks them, nearest first, within a view range of the point you give it (180 metres unless you say otherwise), and packs them into a `PointLightBuffer`. Copy the buffer into the environment as shown, every frame, and the next mesh pass is lit by it. **Size the buffer from `renderer.shadedLights`.** The shader shades up to sixteen point lights at once, and on a WebGL2 device with few uniform registers the renderer builds a smaller shader and says so on the console. A buffer wider than the shader would leave an arbitrary subset lit; a buffer sized from the renderer leaves the nearest ones lit, which is a smaller scene instead of a flickering one. Lights near the edge of the chosen set fade in and out by their `weights` instead of popping. `considered` against `count` tells you how many lights were offered and how many won a slot: 63 offered and 10 bound is a scene to prune. The selection takes two points. The first, usually the camera, orders the lights to shade. The second, the last three arguments, is where whatever might cast a shadow is standing, usually the player, and it orders the shadow maps. A third-person camera sits behind its character, and a fire the character stands beside must keep its shadow even when the camera is out of the fire's reach. ## Lighting channels ```ts /** The channel a character's own lights are on. The stage's lights stay on 1, the default. */ export const CHARACTER_LIGHTS = 2; /** * After the selection, each chosen light's channel from the source it came from: the key light on * the character's channel, everything else on the stage's. */ export function lightChannels(env: Environment, chosen: PointLightBuffer, keyLight: number): void { const channels = env.lightChannels; if (channels === undefined) return; for (let slot = 0; slot < chosen.count; slot += 1) { channels[slot] = chosen.sourceIndex[slot] === keyLight ? CHARACTER_LIGHTS : 1; } } /** The character takes the stage's light and its own; the floor, naming nothing, the stage's. */ export const characterMaterial: SurfaceMaterial = { lightChannels: 1 | CHARACTER_LIGHTS, }; ``` A light shades a surface only where their lighting channels share a bit. Each chosen light's mask is `env.lightChannels`, one a slot, filled from the source it came from as the cookies and profile axes are; each material's is `SurfaceMaterial.lightChannels`. Both are whole masks from 1 to 255, and 1 by default, so a scene that names none is lit exactly as before. The use is a character's own key and rim lights: on a channel of their own, they light the character and leave the floor around it as the stage's lights have it. Channels belong to point and spot lights, in the fixed path and the froxel table alike. The sun, the sky, the probes, rectangles, DriftLight and the GPU-driven pipeline light every surface whatever its mask. ## Spots ```ts /** A spot high over the camera's shoulder, aimed down at the floor in front of the pillars. */ const SPOT = lamps.length; lamps.push({ x: 0, y: 7, z: 7, r: 4, g: 3.8, b: 3.4, radius: 16, flicker: 0, shadowNear: 0.2, sourceRadius: 0.04, dirX: 0, dirY: -1, dirZ: -0.55, coneInnerDeg: 18, coneOuterDeg: 24, }); ``` A direction and two cone angles make a point light a spot. Inside `coneInnerDeg` the light is at full strength, outside `coneOuterDeg` it is zero, and between them the edge is smooth. A light with a direction and no `coneOuterDeg` stays a point light. A spot's shadow uses the same map a point light's does, which covers the whole sphere, so a narrow cone uses a small part of it. A 45 degree cone gets about 0.38 of the map's linear resolution, a 10 degree cone about 0.13: comfortable for a lamp, visibly coarse for a stage spotlight. ## Cookies ```ts /** A cookie is any image the spot projects: here a window frame, white panes and black bars. */ function windowFrame(): HTMLCanvasElement { const size = 128; const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; const paint = canvas.getContext('2d'); if (paint === null) return canvas; paint.fillStyle = '#000'; paint.fillRect(0, 0, size, size); paint.fillStyle = '#fff'; const pane = size / 3; const bar = size / 16; for (let row = 0; row < 2; row += 1) for (let column = 0; column < 2; column += 1) paint.fillRect( size / 6 + column * (pane + bar), size / 6 + row * (pane + bar), pane - bar, pane - bar, ); return canvas; } ``` A cookie is an image a spot projects, such as a window frame, a grille or the shadow of leaves. White passes the light, black stops it, and a colour tints it. `setSpotCookies` uploads a set once, as tiles of one atlas, and a light uses a tile by setting its slot of `lightCookies` in the environment. The engine ships no cookie images; any image or canvas of your own will do. A cookie fills the spot's outer cone, so one image works in a narrow spot and a wide one. It is oriented by the light's slot in `lightIesAxes`, the direction that is up in the image, and **a cookie on a light with no axis is not projected at all**. The example sets both in the loop that copies the selection into the environment. ## Photometric profiles ```ts /** * A photometric profile built in code: intensity that falls to nothing sixty degrees off the aim. * The downlight asked for row 0 of the atlas with `iesProfile: 0`. */ function downlight(): PhotometricProfile { const steps = 19; const verticalAngles = new Float32Array(steps); const candela = new Float32Array(steps); for (let i = 0; i < steps; i += 1) { const degrees = (i / (steps - 1)) * 180; const t = Math.max(0, 1 - degrees / 60); verticalAngles[i] = degrees; candela[i] = 1000 * t * t; } return { verticalAngles, horizontalAngles: new Float32Array([0]), candela, maxCandela: 1000 }; } ``` A photometric profile is a fixture's measured intensity by angle. Manufacturers publish them as IESNA LM-63 files, and `readIesProfile` in `@driftengine/assets` reads one: ```ts /** Load a manufacturer's LM-63 file and hand it to the renderer as row 0 of the atlas. */ export async function loadFixture(renderer: RendererApi, url: string): Promise { const text = await (await fetch(url)).text(); renderer.setIesProfiles([readIesProfile(text)]); } ``` `setIesProfiles` uploads a set once, since a fixture's distribution does not change while the game runs, and a light picks its row with `iesProfile`. Passing an empty list clears them, and the lights go back to plain lights. The reader refuses a file whose `TILT` is anything but `NONE`, since that fixture carries a correction table for being mounted at an angle. A profile is measured from the light's aim, so **give a profiled light a direction and a cone**, as the downlight in the example does with a wide cone that leaves the shaping to the profile. A street light or a wall washer throws more one way than another, and its profile has several horizontal planes; the light's slot in `lightIesAxes` says where the profile's azimuth zero points. ## Rectangular lights ```ts /** The lit window: a rectangle that emits along `right × up`, which here is into the courtyard. */ const windows: AreaLightSource[] = [ { x: 0, y: 2.4, z: -5.8, r: 2.4, g: 3.2, b: 4.8, rightX: 1, rightY: 0, rightZ: 0, upX: 0, upY: 1, upZ: 0, halfWidth: 2.2, halfHeight: 1.1, castsShadow: true, shadowRange: 18, shadowNear: 0.2, }, ]; const windowBuffer = createAreaLightBuffer(); selectAreaLights(windows, windowBuffer); ``` An `AreaLightSource` is a rectangle that emits: a window, a softbox, a lit panel. `right` and `up` are its axes, `halfWidth` and `halfHeight` its size, and it emits along `right × up`. It is one-sided unless `twoSided` is set, so a window does not light the wall it is set into. `selectAreaLights` normalises the axes and makes them perpendicular, and `env.areaLights` takes the buffer. The fixed path shades up to four rectangles (`maxAreaLights`); with `clusteredLights` on, the rest go through the froxel table with the point lights, as [Clustered shading](#clustered-shading) describes. `barnDoorAngle` hangs barn doors on a rectangle: a flap hinged at each edge, standing that many degrees from its normal, `barnDoorLength` metres long (20 cm when absent). At 90 they fold flat and hide nothing; smaller narrows the light to the opening they leave, a softbox becoming a beam. Each fragment shades the part of the rectangle no door's tip hides, light and highlight alike, on the fixed path and through the froxel table. Each door is taken as endless along its hinge, so where two meet the corner they hide is square rather than mitred, and a shadowed rectangle's map is still baked from its whole face. A rectangle does not cast a shadow unless `castsShadow` is set, and then it must say how far its shadow reaches with `shadowRange`, since a rectangle has no radius to take it from. It casts into the same shadow array the point lights use, so it needs `pointShadows` on, and **the same list, in the same order**, must go to `selectAreaLights`, `prepareStaticPointShadows` and `updatePointShadows`: the order is what ties a slot to a rectangle. ## Light shadows ```ts /** The two caster lists: baked once and kept, and drawn again every frame. */ const still: ShadowCasters = (sink) => sink.mesh(courtyard, fixed.worldMatrix); const moving: ShadowCasters = (sink) => sink.mesh(block, blockNode.worldMatrix); /** Size the shadow array once, for every lamp and every rectangle that casts. */ renderer.prepareStaticPointShadows(lamps, windows); ``` Point lights cast by default. Two lists of casters describe the scene to the shadow system: the geometry that never moves, which is baked into a light's map when the light first matters and kept, and the geometry that moves, which is drawn every frame into live maps centred on the casting point from the selection. `prepareStaticPointShadows` sizes the shadow array for the world's lights once, at load. Without it nothing casts, and the renderer says so on the console once. ```ts chooseLights(blockX, blockZ); renderer.updatePointShadows( lamps, chosen.sourceIndex, chosen.count, blockX, 0.6, blockZ, time - shadedAt, still, moving, chosen.shadowIndex, chosen.shadowCount, windows, ); shadedAt = time; ``` Every frame, after the selection, `updatePointShadows` binds the chosen lights' maps, bakes what has changed and redraws the live maps. Maps are borrowed from a pool sized to the light budget plus four, so memory follows how many lights can be shaded, never how many the world contains. A light entering the set is often already baked, because the four spare maps hold the next-nearest lights. Three things decide whether a light's shadow is good: - **`shadowNear` small, but outside the fixture.** It clips every caster, and a lamp's own housing inside it throws a hard square across the floor much larger than the housing. - **A steady radius.** The radius is the map's far plane, so a light whose radius is animated is re-baked every frame and takes the budget from every other lamp. Set `castsShadow: false` on lights that pulse, and on small lights that were never meant to cast. - **The bake budget.** `pointShadowFacesPerFrame`, two faces by default, spreads static bakes over frames, and raising it makes lamps cast sooner. `liveShadowFacesPerFrame`, twelve by default, bounds the live ones; lowering it spreads a moving caster's shadow over two or three frames, so it trails a fast character slightly, and saves frame time on a phone. `pointShadowFaceSize` sets the resolution, 512 by default. ## Thousands of fixed lights ```ts /** Thousands of street lamps that never move, bucketed once into twenty-metre cells. */ export function streetLighting(lamps: readonly PointLightSource[], shaded: number) { const grid = createLightGrid(lamps, 20); const chosen = createPointLightBuffer(shaded); return { chosen, /** The same choice `selectPointLights` makes, looking only at the cells near the eye. */ choose(x: number, y: number, z: number, time: number): PointLightBuffer { selectGridLights(grid, x, y, z, chosen, time, DEFAULT_POINT_LIGHT_VIEW_RANGE); return chosen; }, }; } ``` `selectPointLights` visits every light in the list each frame. For a city's fixed street lamps, `createLightGrid` buckets them once into cells and `selectGridLights` looks only at the cells near the eye. The choice is the plain scan's exactly, tie for tie. A light that moves must be re-bucketed, so a scene's few moving lights stay in a plain list. Lights the frame does not shade still light the world when they belong to a DriftLight field, which sums every fixed light into textures the shader reads; see [DriftLight](https://driftengine.dev/docs/rendering/driftlight). ## Clustered shading ```ts /** * With `clusteredLights: true` a fragment shades only the lights in its own froxel, so the buffer * can be far wider than the sixteen the plain path binds. */ export const crowded = createPointLightBuffer(MAX_CLUSTERED_LIGHTS); ``` With the `clusteredLights` quality option on, the view is divided into froxels, each fragment shades only the lights in its own froxel, and the budget becomes 320 lights. Size the buffer to `MAX_CLUSTERED_LIGHTS`, as above. It costs one texture unit on WebGL2 and a binning pass every frame, on the main thread on WebGL2 and on the GPU on WebGPU: measured at 0.411 ms with sixteen lights and 2.6 ms with 256. Binning cost follows a light's area on screen, so a scene of a few enormous lights pays most and gains least, and the fixed path is the better choice there. Off by default. Shading cost follows how many lights each froxel holds, which grows with how much the lights overlap on screen. At 3840 by 2160, 320 lights of radius 8 crowded around the view hold 13.5 lights in an occupied froxel on average and cost 7.4 ms of shading on a desktop GPU; at radius 12 the same lights cost 12.7 ms. A light with a cone, a profile, a cookie, a point shadow, channels or a falloff exponent of its own is read in six texels and a plain one in two, and a frame whose lights are all plain never reads the other four. A spot is binned by its cone, not only by the sphere its radius draws: a froxel the cone cannot reach takes nothing from it, so a narrow spot with a long reach costs the froxels it lights. ### More rectangles than four ```ts /** * A row of ceiling panels, more than the fixed four. With `clusteredLights` on, the rectangles past * `maxAreaLights` are shaded through the froxel table, each out to its `range`. */ export function ceilingPanels(env: Environment, count: number): void { const panels: AreaLightSource[] = []; for (let i = 0; i < count; i += 1) { panels.push({ x: -10 + i * 2, y: 3.5, z: 0, r: 6, g: 6, b: 5.4, /* It emits along right x up, which is straight down. */ rightX: 1, rightY: 0, rightZ: 0, upX: 0, upY: 0, upZ: 1, halfWidth: 0.6, halfHeight: 0.15, range: 6, }); } const buffer = createAreaLightBuffer(count); selectAreaLights(panels, buffer); env.areaLights = buffer; } ``` With the table on, rectangles past the fixed `maxAreaLights` are binned beside the point lights and shaded exactly as the fixed ones are, highlight and all. They cast no shadow, and each is windowed to zero at its `range`, in metres from its centre; a rectangle that names none reaches as far as its light on its own axis stays above a thousandth of a scene unit. Without the table, a rectangle past the fixed ones is not drawn, and the renderer says so once. ## Light from surfaces Emissive surfaces glow in their own colour, by vertex or by map; see [Materials](https://driftengine.dev/docs/rendering/materials). Three environment fields govern them: - `nightFactor` is the switch: at 0 nothing emits, whatever the mesh says. A daylit scene with a lit sign in it sets it to 1. - `emissiveGain` is how strongly. - `nightEmissive` adds emission only where the directional light does not reach, for city lights on a planet that turns: they show on the night side and not on the day side. It needs the `nightEmissive` quality option, which compiles the term in. An emissive surface does not light its neighbours the way a fixture does. To light the floor under a glowing panel, put a light there too, as the example does with its window and its lamps. --- # Shadows Rendering. https://driftengine.dev/docs/rendering/shadows The sun's shadow map focused around the player, its static, peeled and moving layers, one caster list for every pass, and the quality dials. The directional light, the sun or the moon, casts through one shadow map that covers a sphere around a point you choose, usually the player. Point lights, spots and rectangles cast through their own maps, described in [Lights](https://driftengine.dev/docs/rendering/lights). Both read the same list of casters. ## A shadow in three calls ```ts /** * Everything in the world, said once. The shadow pass and the colour pass both draw from this, * so nothing can cast a shadow without being seen, or be seen without casting one. */ const casters: ShadowCasters = (sink) => { sink.mesh(levelMesh, still.worldMatrix); sink.mesh(playerMesh, playerNode.worldMatrix); for (let i = 0; i < crateNodes.length; i += 1) sink.mesh(crateMesh, crateNodes[i].worldMatrix); for (let i = 0; i < orbs.length; i += 1) { if (!orbs[i].taken) sink.mesh(orbMesh, orbNodes[i].worldMatrix); } }; const lightMatrix = new Float32Array(16); ENV.lightViewProj = lightMatrix; ENV.shadowStrength = 0.8; ``` A `ShadowCasters` function names everything that casts by calling the sink it is handed. It is called once per shadow layer and once per cube face, so it allocates nothing: it closes over the meshes and reads them. The same function draws the colour pass with `drawSceneCasters`, so nothing can be seen without casting or cast without being seen. ```ts function render(alpha: number, frameDt: number): void { // Input is sampled here, at the edge of the simulation: a step reads what this left behind. touch.tick(performance.now()); // Read here, not in simulate: while paused, simulate is not called at all. if (actions.consumePress('pause')) paused = !paused; if (!paused) clock += frameDt; placeEverything(alpha); const at = playerNode.position; follow(at[0], at[1], at[2], frameDt); // The shadow map covers 16 metres around the player, which is everything the camera sees. ENV.shadowDepthSpan = computeLightMatrix( ENV.directionalDir, at[0], at[1], at[2], 16, renderer.shadowMapSize, lightMatrix, ); renderer.beginShadowPass(lightMatrix, 'static'); renderer.drawShadowCasters(casters); renderer.endShadowPass(); renderer.beginFrame(SKY); renderer.bindMeshPass(camera, ENV); renderer.drawSceneCasters(casters); drawHud(); renderer.endFrame(); } ``` Every frame the first game: 1. Computes the light's matrix with `computeLightMatrix(direction, x, y, z, radius, size, out)`. It covers a sphere of `radius` metres around the focus and returns the depth span, which the environment needs as `shadowDepthSpan`. 2. Draws the casters into the map between `beginShadowPass` and `endShadowPass`. 3. Binds the mesh pass with an environment whose `lightViewProj` is that matrix and whose `shadowStrength` is above zero. Focusing the map on the player is what buys resolution: fitting the whole world spends most of the map on geometry nobody is looking at. The matrix is snapped to whole texels, so edges do not swim as the focus moves. Near the edge of the covered sphere shadows fade out instead of being cut. Set `shadowStrength` to 0 whenever the map is not drawn, at night for instance: a stale map is never sampled then. ## Static, peeled and moving layers The map has three layers, drawn one at a time and read together, and each is cleared only when its pass begins: - `'static'`, for the world that does not move. - `'static-peel'`, the same casters again. A single depth map keeps only the first surface the sun meets; the peel keeps the second. Each caster's shadow fades with its own distance from what it falls on, so without the peel a tall caster far above would hide the shadow of a nearer one. - `'dynamic'`, for whatever moves. ```ts /** * The still world is drawn into its layers only when the light's matrix moves, which it does in * whole texels; whatever moves is drawn into the dynamic layer every frame. */ export function sunShadows( renderer: RendererApi, env: Environment, still: ShadowCasters, moving: ShadowCasters, ): (x: number, y: number, z: number) => void { const matrix = new Float32Array(16); const drawnWith = new Float32Array(16); env.lightViewProj = matrix; env.shadowStrength = 0.85; return (x, y, z) => { env.shadowDepthSpan = computeLightMatrix( env.directionalDir, x, y, z, 40, renderer.shadowMapSize, matrix, ); if (matrix.some((value, i) => value !== drawnWith[i])) { renderer.beginShadowPass(matrix, 'static'); renderer.drawShadowCasters(still); renderer.endShadowPass(); renderer.beginShadowPass(matrix, 'static-peel'); renderer.drawShadowCasters(still); renderer.endShadowPass(); drawnWith.set(matrix); } renderer.beginShadowPass(matrix, 'dynamic'); renderer.drawShadowCasters(moving); renderer.endShadowPass(); }; } ``` Since the static layers keep what was drawn into them, a scene can redraw them only when the matrix moves, and draw its movers every frame. The first game draws everything into `'static'` every frame, which is simpler and right for a small level. `directionalShadowDepthLayers: 1` drops the peel and its memory; the default is 2. ### The moving layer on a square of its own The still world wants a wide square, so distant roofs keep their shadows; a character wants a tight one, so its own shadow is sharp. Each layer can have its own. The moving layer is read through the matrix its pass was drawn with, so draw it through a small square around what moves, and leave the environment's `lightViewProj` the static layer's: ```ts /** * Whatever moves on a square of its own, six metres around the character, so its shadow is as * sharp as the map allows while the still world keeps a square wide enough for distant roofs. */ export function tightMovers( renderer: RendererApi, env: Environment, moving: ShadowCasters, around: readonly [number, number, number], ): void { computeLightMatrix( env.directionalDir, around[0], around[1], around[2], 3, renderer.shadowMapSize, movingMatrix, ); renderer.beginShadowPass(movingMatrix, 'dynamic'); renderer.drawShadowCasters(moving); renderer.endShadowPass(); } const movingMatrix = new Float32Array(16); ``` Nothing else changes: a scene that draws both layers with one matrix draws exactly as it did, and the moving layer's own matrix is compiled into the lit stage only the first time a frame draws that layer with a different one. The tight square belongs inside the wide one, since a receiver outside the wide square takes no sun shadow at all. On WebGL2 the moving matrix takes five fragment uniform vectors; where a part has no room for them it is refused, said once, and the layer is read through the environment's matrix, so draw both layers with that matrix there. ## Every kind of caster ```ts /** One list for every kind of caster: a mesh, a cutout, a skinned figure and an instanced batch. */ export function townCasters( town: { house: MeshHandle; houseModel: Float32Array }, hedge: { mesh: MeshHandle; model: Float32Array; leaves: SurfaceTextureHandle }, hero: { mesh: MeshHandle; model: Float32Array; palette: Float32Array }, trees: { batch: InstancedHandle; data: MeshInstances }, ): ShadowCasters { return (sink) => { sink.mesh(town.house, town.houseModel); /* A cutout casts the leaves, not the card they are painted on. */ sink.mesh(hedge.mesh, hedge.model, { albedo: hedge.leaves, cutout: 0.5 }); /* The same palette the visible draw uses, or the shadow is the bind pose. */ sink.skinnedMesh(hero.mesh, hero.model, hero.palette); sink.instanced?.(trees.batch, trees.data); }; } ``` The sink takes rigid meshes, skinned meshes with the palette the visible draw used, instanced batches, and scatter batches with the same wind the visible draw used. A caster drawn one way and shadowed another throws a shadow that has come loose from it: a skinned figure submitted as a plain mesh casts its bind pose. A material may ride along. A cutout material, one with an albedo map and a `cutout` threshold, casts the shape its alpha leaves, so a leaf card casts a leaf. A glass material writes no depth; with `glassShadows` on it casts coloured light instead, as [Translucent and additive meshes](https://driftengine.dev/docs/rendering/translucency) describes. ## Quality | Option | Default | What it does | | ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------- | | `directionalShadows` | `true` | Whether the sun casts at all. | | `directionalShadowMapSize` | 2048 | The map's side, in texels. `renderer.shadowMapSize` reports it. | | `shadowFilterTaps` | 12 | Filter taps per shadow lookup, 4, 8 or 12, shared with point lights. | | `directionalShadowDepthLayers` | 2 | 2 keeps the peel, 1 drops it. | | `directionalShadowMaxDistance` | 1000 | How far a shadow may reach along the ground from its caster before it dissolves. Not a camera distance. | | `directionalShadowMaxSlope` | 60 | How low the sun may stand, as horizontal metres per vertical metre, before shadows fade: 60 is 1°. | | `glassShadows` | `'full'` | Coloured light through glass: `'full'`, `'half'` or `'off'`. | The defaults keep a shadow to the edge of its map, which fades it there, and keep shadows until the sun is about a degree above the horizon. Until 4.13.0 they were 6 and 3, which dissolved any shadow longer than six metres, so a building's walls cast nothing on its floor, and dropped every shadow below about 18° of sun. A scene whose long shadows streak at a low sun lowers `directionalShadowMaxSlope`, and gives up the evening's last shadows for it. There is no bias to tune. The filter follows the plane of the surface it lands on, so a grazing surface does not stripe itself, and a small fixed tolerance keeps contact shadows attached. --- # Light in the air Rendering. https://driftengine.dev/docs/rendering/light-in-the-air Shafts of light with dust in them, cut to shape by a window's shadow, fire and smoke plumes, and a medium that fills a room with light. Light is seen on surfaces, and in the air only where something in the air catches it. The engine draws that three ways: a volume of light inside a hull you place, plumes of fire and smoke, and a medium that fills the whole frame. Haze over distance is fog, in [Fog and weather](https://driftengine.dev/docs/rendering/fog-and-weather). (This chapter runs the `air` example at https://driftengine.dev/docs/rendering/light-in-the-air.) ## Shafts and beams ```ts /** * A shaft through a window is a slice of a very wide cone whose apex is far out toward the sun. * The hull is round and wider than the window; the window's own shadow cuts it square. */ const REACH = 30; const shaftHull = buildLightVolume({ nearM: REACH, lengthM: REACH + 10, spread: 2.2 / REACH, color: [1, 0.86, 0.62], }); const shaft = renderer.createMesh(shaftHull); /** The hull opens along its own +Z, so its matrix turns +Z to the way sunlight travels. */ function aimAlong(out: Float32Array, at: Vec3, travel: Vec3): void { const [zx, zy, zz] = travel; const side = Math.hypot(zz, zx); const xx = zz / side; const xz = -zx / side; out.set([xx, 0, xz, 0, zy * xz, zz * xx - zx * xz, -zy * xx, 0, zx, zy, zz, 0, ...at, 1]); } const length = Math.hypot(...SUN); const travel: Vec3 = [-SUN[0] / length, -SUN[1] / length, -SUN[2] / length]; const shaftModel = new Float32Array(16); aimAlong( shaftModel, [6.1 - travel[0] * REACH, 2.3 - travel[1] * REACH, -travel[2] * REACH], travel, ); ``` A light volume is a beam from a lamp, a cone under a street light, or a shaft of sun through a window. `buildLightVolume` builds its hull, a closed cone frustum opening along its own +Z: `lengthM` is how far the light reaches, `spread` is the cone's half-width over distance, and `nearM` is where the drawn part starts. A shaft through a window is a slice taken far down a very wide cone whose apex is out toward the sun, which is what `nearM` is for. `sides` sets how round the outline is, twelve by default; the light inside is round whatever the hull. ```ts renderer.drawLightVolume(shaft, shaftModel, camera, 0.8, REACH + 10, 2.2 / REACH, { nearM: REACH, dust: 0.35, dustScaleM: 0.8, driftM: [time * 0.05, 0, time * 0.02], sunShadow: 1, env, }); renderer.drawPlumes(smoke, camera, time, env, 0.2, 0); renderer.drawPlumes(fire, camera, time, env, 0.2, 0); ``` `drawLightVolume(mesh, model, camera, strength, length, spread, options)` walks each pixel's line of sight through the hull and adds what the air there would scatter. **Pass the same `length`, `spread` and `nearM` the hull was built with.** They are read in the hull's own units, and a draw that disagrees with its hull either ends at a hard edge or disappears. `strength` fades the whole volume, for a lamp coming up at dusk, and is clamped to 1. The options: - `dust`, 0 to 1, gives the air structure: 0.2 to 0.5 reads as motes in sunlight, more as smoke. `dustScaleM` is the size of a cell of the dust field and `driftM` where the field has drifted to, a position so the same instant always draws the same frame. - `sunShadow`, 0 to 1, cuts the volume by the sun's shadow map at every step of the walk. That is what makes the round hull in the example square: the window frame shadows the air as well as the floor. It needs `env` and a renderer built with `directionalShadows`. - `medium` ties the volume to the weather: `{ atmosphere, fullAtDensity }` draws it as authored at that fog density, dimmer in clearer air and no brighter in thicker. A headlight in fog then reads differently from the same headlight on a clear night. A volume is depth tested, so a beam passes behind whatever stands in front of it, and it occludes nothing. The `lightVolumeSamples` quality option, 32 by default, is how many steps each ray takes; the walk is dithered per pixel, which turns banding into grain. A frame that draws no volume pays nothing. ## Fire and smoke ```ts /** Fire adds light; smoke covers it. One batch each, placed once. */ const fire = renderer.createPlumes([{ x: -1, y: 0.8, z: 4.5, width: 0.35, height: 1.1 }], { material: 'fire', blend: 'additive', windResponse: 0.1, }); const smoke = renderer.createPlumes( [ { x: -1, y: 1.6, z: 4.5, width: 0.5, height: 1.4 }, { x: -0.9, y: 2.6, z: 4.4, width: 0.8, height: 1.4 }, ], { material: 'smoke', blend: 'alpha', windResponse: 1, tint: [0.35, 0.33, 0.32] }, ); ``` `createPlumes(placements, options)` makes a batch of plumes, each a position, a half-width and a height, animated on the GPU. A plume is two crossed blades fixed in the world, so walking around a fire shows it from every side. The options: - `material`: one the engine ships, `'fire'`, `'smoke'` or `'arcane'`. - `blend`: `'additive'` for what emits light, `'alpha'` for what covers it. - `windResponse`: how far the plume leans per metre a second of wind at its crown. Smoke is carried; a flame is anchored to its fuel. - `sizePulse`: how much the quads swell and shrink. It is visual only, so a gameplay volume must keep its own fixed size. - `tint`: the colour, white by default. `drawPlumes(plumes, camera, time, env, windX, windZ)` draws a batch after the opaque scene; pass the same wind the grass and the dust use. A batch is placed once, since fires do not move, and `setPlumeScale(plumes, index, scale)` resizes one plume, 0 to hide it: an oil slick that burns on a cycle. The `plumeNoiseOctaves` quality option sets how much detail the noise has, 3 by default. A plume does not light anything. The brazier in the example has a flickering point light beside its fire for that. ## The air itself ```drs fn breathe(air: mut Air, renderer: Renderer, dt: f32) { // Half of the change a second, either way. air.present = air.present + math.clamp(air.wanted - air.present, 0 - dt * 0.5, dt * 0.5) // Extinction per metre, how much of it comes back as light, how far forward it scatters, and // how far the march looks. A density of 0 is no air at all, and costs nothing. render.medium(renderer, 0.035 * air.present, 0.9, 0.6, 40) } ``` The example's air is a DriftScript module. Its switch says whether the room should hold air, and `breathe` eases toward that and sets the medium with `render.medium`, the script's form of `setGlobalMedium(density, albedo, anisotropy, maxDistance)`. That call fills the frame with a participating medium and marches every pixel's line of sight through it, adding the sunlight the air there scatters toward the eye. Where the sun's shadow map says a point is in shade, it adds nothing, which is how a window throws shafts across the whole room and a doorway its shape onto the floor. - `density` is extinction per metre. 0.02 leaves a wall 50 metres away a third obscured, 0.1 is thick weather, and above about 0.5 nothing past a room is visible. **0 is off, and off is free**: nothing is allocated and no pass runs. - `albedo`, 0 to 1, is how much of what the air takes out comes back as light: near 1 for fog, cloud and steam, lower for soot. - `anisotropy`, -1 to 1, is how much the medium scatters forward. Haze is strongly forward, around 0.6, which is why the air around a low sun glows and the air behind you does not. - `maxDistance` is where the medium ends: past it the air neither scatters nor absorbs. A medium standing for the near part of the environment's haze hands the rest of the ray to that haze by setting the environment's `fogStart` to the same distance, so the two never lay one stretch of air twice. `setGlobalMedium` also takes one object, `{ density, albedo, anisotropy, maxDistance, ... }`, with more the four numbers cannot say: - `albedo` may be a colour, a share a channel: a faintly blue haze returns the sky's blue a little more readily than its red. - `heightFalloff` and `baseY` thin the medium above `baseY` as the environment's haze thins, and `layer2` adds a second layer, `{ density, heightFalloff, baseY }`. Together they make the medium the same haze the environment draws, lit. - `sunScatter` and `skyScatter`, 1 by default, scale how strongly the sun and the sky's fill scatter, each a share of how strongly it lights a surface. - `skyFill` is the sky's fill as a colour of the medium's own, in the units of the environment's `ambient`, which `skyScatter` then scales. Absent, the medium scatters the ambient. A scene lit by a sky's cubemap, probes and a bake keeps its flat ambient for what falls outside them, so that ambient is the wrong colour for the sky's light in the air, and changing it would relight those surfaces too. The fill is one colour from every side, as the ambient is. - `lampScatter`, 0 by default, lets the lamps scatter too: the frame's per-pixel lamps, each shaped by its falloff and its cone and cut by its own shadow maps, so a lamp behind a post throws the post's shadow into the air. Each lamp's `lightMediumScatter` in the environment, 1 where absent, scales its own. A photometric profile or a cookie shapes a lamp's pool on a surface and not its glow in the air. The medium is a dial and is held until changed, so weather can move every frame. What it may cost is a quality option: `globalMediumSteps` is the march's step count, **0 by default, which turns the medium off whatever the frame asks for**. 24 suits a room, 48 a landscape under a low sun, and 64 is the most. `globalMediumHalfResolution`, on by default, marches a quarter of the pixels and upsamples by depth. On parts the engine knows are weak, steps are capped at 16 unless `capabilityClamp` is off. The example sets the ceiling once, at 48, and its switch only moves the density: at 0 nothing runs, so the ceiling costs nothing until the air is there. The medium is composited before the post chain, so bloom sees a lit fog bank as brightness. It reads the sun's shadow map only on frames that drew it, with `shadowStrength` above zero. --- # DriftLight Rendering. https://driftengine.dev/docs/rendering/driftlight Every fixed light in a scene lights the world, near or far: the lights the frame does not shade summed into an occluded volume. A frame shades a limited number of lights exactly: sixteen on the plain path, a few hundred with clustered shading. A gallery of seven hundred candles therefore leaves every wall past the nearest few dark, until the camera walks up to it. DriftLight sums every fixed light once into a volume of light and direction, occluded by the scene's own walls, and the shader reads that volume wherever the frame's exact choice does not reach. Near the camera lights are shaded exactly; past them the summed light stands in, and a two-metre band crossfades between the two so nothing pops. (This chapter runs the `driftlight` example at https://driftengine.dev/docs/rendering/driftlight.) ## A field for a scene ```ts /** Three rows of candles along each wall, thirty centimetres apart. None of them casts. */ const candles: PointLightSource[] = []; for (const side of [-1, 1]) for (const y of [1, 1.6, 2.2]) for (let x = -LENGTH + 2; x <= LENGTH - 2; x += 0.3) candles.push({ x, y, z: side * (WIDTH - 0.4), r: 0.5, g: 0.27, b: 0.08, radius: 1.2, flicker: 0, shadowNear: 0.05, sourceRadius: 0.005, castsShadow: false, }); ``` The lights are ordinary `PointLightSource` records. None of them casts a shadow here: seven hundred shadow maps are not what a candle needs, and the field brings its own occlusion. ```ts /** Each slab baked into a distance field, which is what stops summed light passing through it. */ const walls: GlobalFieldInstance[] = slabs.map((slab) => ({ source: bakeObjectSdf(new MeshBuilder().addBox(slab.centre, slab.half, [1, 1, 1]).build(), 96), transform: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), })); const field = renderer.createLightField(candles, { fields: walls }); field.scale = flag('driftlight', 'on') === 'on' ? 1 : 0; ``` `createLightField(lights, options)` makes the field and marks each light `inLightField`, which tells the selection that the light is also summed, so no pixel counts it twice. `fields` are the distance fields that occlude the summed light: here each slab of the gallery is baked with `bakeObjectSdf` from `@driftengine/assets`, so light from the candles beyond the partition does not reach the near face of it. A field made without them is unoccluded. The other options: - `spacing`, a third of a metre by default: the distance between samples. A brick of samples spans a metre. - `band`, two metres by default: how wide the crossfade between exact and summed light is. - `fadeSec`, half a second by default: how long the summed light takes to fade in once the field is whole. Zero for a field baked behind a loading screen. ## Baking and following ```ts /* Bricks until four milliseconds of this frame are spent, so the walk stays smooth on a slow machine too; once the field is whole it fades in over half a second. */ const until = performance.now() + 4; while (!field.ready && performance.now() < until) field.bake(4); const [x, y, z] = camera.position; selectPointLights(candles, x, y, z, chosen, time, DEFAULT_POINT_LIGHT_VIEW_RANGE); env.lightCount = chosen.count; env.lightPositions = chosen.positions; env.lightColors = chosen.colors; env.lightRadii = chosen.radii; env.lightSourceRadii = chosen.sourceRadii; env.lightWeights = chosen.weights; /* Where the exact choice is complete, so the shader knows where the field takes over. */ field.follow(chosen.complete, x, y, z, time - shadedAt); shadedAt = time; ``` `bake(bricks)` bakes that many bricks and no more, and reads no clock, so the build is deterministic and pacing it is the scene's. The example bakes four at a time until four milliseconds of the frame are gone, so the walk stays smooth while the field fills, on a slow machine too; a fixed count per frame costs a fast machine nothing and stalls a slow one. `progress` is how much is done, for a loading screen, and `ready` says the field is whole. The volume is not used until every brick has landed, then fades in. `follow(complete, x, y, z, dt)` tells the field where the frame's exact choice is complete. The selection's `complete` is a distance from its centre: a point nearer than that is reached only by lights the frame shades exactly, at full strength, so the field can leave it alone. The field shrinks its radius at once when the choice shrinks, and grows it back slowly. A scene has one field at a time; creating another replaces it, and `disposeLightField` lets it go. `scale` dims everything the field summed at once, for dawn or a power cut. ## What it gives up - **Highlights.** Summed light lights surfaces; it puts no specular highlight on them. The exact lights near the camera do. - **Flicker past the choice.** The volume holds each light's steady colour. - **Occlusion by anything that moves.** Only the fields given at construction shadow it. - **The lights as they change.** The field sums the lights as they stood when it was made, from a copy, so a scene that dims its lamps later uses `scale`. ## A whole city A street lamp reaches thirty metres and stands every forty, so a city is lit almost everywhere and a sparse volume of bricks buys nothing. For a world, `bakeDenseField` sums every fixed light offline into one dense grid: at eight metres a sample, a city two kilometres across and 128 metres tall is 256 × 16 × 256 samples, 16 MB on the GPU. The grid may be at most 256 samples along x and z and 128 along y. ```ts /** Offline, in a build script: sum every lamp over two kilometres at eight metres a sample. */ export function bakeCityLight(lamps: readonly PointLightSource[]): DenseLightVolume { return bakeDenseField(lamps, 'smooth', null, [-1000, 0, -1000, 1000, 128, 1000], 8); } /** And store it in the world's file, as one `LVOL` chunk. */ export function writeWorld(world: DrftSource, lamps: readonly PointLightSource[]): ArrayBuffer { return writeDrft({ ...world, lightVolume: bakeCityLight(lamps) }); } ``` The bake buckets lights before it sums them, so each sample considers only the lamps that can reach it, and it may take seconds, which is why it belongs in a build script. Its `distance` argument occludes, as the scene field's distance fields do, or is `null` for none. The `.drft` format carries the result as one `LVOL` chunk. ```ts /** In the game: the volume arrives with the file, and the lamps it summed are marked as summed. */ export async function openCity( renderer: RendererApi, url: string, lamps: PointLightSource[], ): Promise { for (const lamp of lamps) lamp.inLightField = true; await streamDrft(await fetch(url), { onLightVolume: (volume) => renderer.createWorldLightField(volume, { fadeSec: 0 }), }); } ``` `createWorldLightField(volume)` hands the volume to the renderer whole. It carries no list of the lights it came from, so the scene marks them `inLightField` itself. The exact lights near the eye are found with the light grid from [Lights](https://driftengine.dev/docs/rendering/lights), which makes the same choice as the full scan over twenty thousand lamps, measured 20 to 30% faster. At eight metres a lamp's pool is a few samples across, which is why the volume only stands in past the exact lights, where a pool is a few dozen pixels on screen. --- # DriftRay Rendering. https://driftengine.dev/docs/rendering/driftray Light that bounces, traced on the GPU through signed distance fields into the probe grid every frame, so a room follows its own changes. WebGPU only. Light that arrives at a surface after bouncing off another is what makes a room with a red wall pink. DriftRay is the engine's ray tracing: rays marched through signed distance fields in compute shaders, a few hundred per probe, which fill the probe grid the shading already reads. WebGPU exposes no ray-tracing hardware, so the rays step through distance fields instead of triangles. What DriftRay adds over a probe grid baked once is that it follows. A baked grid keeps the light it was baked with; a traced one refreshes five probes a frame, so when a wall is repainted or the sun moves, the bounce changes with it over the next sweeps of the grid. The example's 32 probes come round every seven frames. In the example the sunlit wall turns from red to blue every six seconds; with DriftRay off, the far wall keeps the bounce from when the room loaded. (This chapter runs the `driftray` example at https://driftengine.dev/docs/rendering/driftray.) ## Turning it on ```ts /** * Indirect light only where it runs, and a probe array for it to write into. Turning it on or off * changes what the renderer is built with, so the switch builds a new one in place. */ const quality = (traced: string) => (backend: string) => ({ indirectLight: traced === 'on' && backend === 'webgpu', reflectionProbeSize: 64, directionalShadows: true, directionalShadowMaxDistance: 12, outputTransform: 'aces' as const, }); const scene = await openScene(quality(flag('driftray', 'on')), build); ``` `indirectLight` is a quality option, off by default and WebGPU only. Asked for on WebGL2, it lights nothing and says so once on the console, and the grid keeps its baked light; passing quality as a function of the backend, as here, asks each backend only for what it does. The traced light is written into the probe array, so `reflectionProbeSize` must allocate one. ## What the rays can hit ```ts /** Each slab as a distance field, baked at its own origin and placed by a matrix. */ const placed = slabs.map((slab) => ({ slab, field: bakeObjectSdf(new MeshBuilder().addBox([0, 0, 0], slab.half, WHITE).build(), 64), model: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ...slab.centre, 1]), })); /** Declared every frame: what the rays may hit, and what colour each surface is. */ function declareFields(renderer: RendererApi, paint: Vec3): void { for (const { slab, field, model } of placed) renderer.addDistanceField(field, model, slab.painted ? paint : WHITE); } ``` A ray can only hit what has a distance field. `bakeObjectSdf(mesh, resolution)` from `@driftengine/assets` bakes one from mesh data: `resolution` is voxels along the mesh's longest axis, and the voxels are cubes, so a thin wall keeps its thickness. The sign comes from how many surfaces separate a point from the open air around the grid, not from triangle winding, so single-sided walls, rooms open to the sky and models exported inside out all bake correctly. A gap narrower than about a voxel reads as sealed. Baking is offline work in a real game. The `.drft` format carries a model's fields as an `SDFV` chunk, and `streamDrft` hands them over through `onFields`. `addDistanceField(field, model, albedo)` declares a field for this frame: where it stands, by a matrix with uniform scale only, and what colour its surface is, which is what a bounce off it carries. Declarations are cleared at every `beginFrame`, so a scene declares its fields every frame, and a field it stops declaring stops lighting. The renderer composes them into one world field around the camera at `endFrame`. ## The probes ```ts /** A grid of probes through the room, rasterised once so the first frame is already lit. */ renderer.setProbeGrid({ origin: [-1.8, -0.6, -1.8], spacing: [1.2, 1.2, 1.2], counts: [4, 2, 4], }); env.shadowDepthSpan = computeLightMatrix( env.directionalDir, 0, 0, 0, 6, renderer.shadowMapSize, lightMatrix, ); renderer.beginShadowPass(lightMatrix, 'static'); renderer.drawShadowCasters(casters); renderer.endShadowPass(); renderer.bakeProbeGrid([0, 0, 0], (probeCamera) => { renderer.bindMeshPass(probeCamera, env); renderer.drawMesh(rooms.red, fixed.worldMatrix); }); ``` `setProbeGrid` places the probes, on a lattice through the space to be lit. The rasterised `bakeProbeGrid` before the first frame is optional: a traced grid starting black climbs to the same answer on its own, and the bake only means the first frames are already lit. ```ts declareFields(renderer, blue ? BLUE : RED); ``` Each frame then traces five probes, 256 directions each, and each refresh keeps four fifths of what its probe held, which removes the shimmer two refreshes of the same probe would otherwise show. `renderer.indirectBakeMs` reports what the last refresh took on the device, where the device can time itself. ## What gets bounced Rays that hit a surface light it with the sun, the frame's exact point lights, each shadowed through the distance field, and the light DriftLight summed, so a brazier's light bounces as well as the sun's. Rays that escape read the sky the frame drew. Measured against a path tracer of the example's kind of room, the far wall's red comes out at 187.7 where the reference says 194.6 to 218.0. A hit takes the colour of its field cell's nearest surface, and the world field's finest cells are 17 centimetres, so a corner where two colours meet bounces a little of each. ## Baked bounce, without DriftRay Every probe grid bounces light once, traced or not. A grid baked with `bakeProbeGrid` captures the lit room from each probe, so a WebGL2 frame still has a bounce; it is the light the room had when it was baked. [Reflections](https://driftengine.dev/docs/rendering/reflections) covers probes in full: baking, a single environment probe, and loading a sky. --- # Reflections Rendering. https://driftengine.dev/docs/rendering/reflections What shiny surfaces show: the sky gradient, a captured room, a grid of probes baked a little at a time, bounced light and an HDR sky. A metal shows almost nothing but what it reflects, and a glossy floor half of it, so what the environment looks like decides how those surfaces read. The engine reflects one of three things, from cheapest to best: 1. **The sky gradient.** With no probe, a reflective surface mirrors the environment's `ambient` above and `ambientGround` below, mixed by the reflected direction. It still varies with the view, and nothing renders black. 2. **A captured room.** A probe photographs the scene around a point once, and surfaces reflect that. 3. **A grid of probes**, so a reflection near the door shows the door and one by the window shows the window. Every probe also lights: its diffuse convolution is the ambient light at that point, so a probe grid is also the scene's bounced light. [DriftRay](https://driftengine.dev/docs/rendering/driftray) traces that grid every frame on WebGPU. ## Turning probes on `reflectionProbeSize` sets each probe's resolution and is 0, off, by default; set it to allocate the probe array. `environmentReflections`, on by default, is the switch a settings screen turns off. Every probe call returns `false` and does nothing when no probe was allowed, on a profile without a size or a device without a texture unit to spare, so a scene may issue them unconditionally. ## A captured room ```ts /** One probe in the middle of a finished room, baked once the room exists. */ export function captureRoom( renderer: RendererApi, drawRoom: (camera: Camera) => void, clear: Vec3, ): boolean { return renderer.bakeReflectionProbe([0, 1.6, 0], clear, drawRoom); } ``` `bakeReflectionProbe(origin, clear, drawFace)` hands `drawFace` a camera aimed at each of the six faces in turn, and the callback draws the scene exactly as it does for the screen: `bindMeshPass`, the world's draws, the sky. Then the six faces are convolved into the levels a rough or a smooth surface samples. Six draws of the scene, once; after that one texture fetch per reflective pixel. **Bake after the world exists.** A probe baked in a constructor captures a room that has not been built yet. Shadow maps baked before the probe are fine and are the normal order. The callback re-enters the mesh pass only, so what a scene draws in a later pass, particles and light volumes, is absent from the capture; draw the sky inside the callback. ## A grid of probes ```ts /** * A grid of probes through a courtyard, baked two faces a frame so no frame pays for a whole * probe. The grid is not used until every probe has landed. */ export function pacedGrid( renderer: RendererApi, drawScene: (camera: Camera) => void, clear: Vec3, ): () => boolean { renderer.setProbeGrid({ origin: [-12, 1.5, -12], spacing: [8, 4, 8], counts: [4, 2, 4] }); const probes = 4 * 2 * 4; let probe = 0; let face = 0; return function step(): boolean { if (probe === probes) return true; renderer.bakeProbe(probe, clear, drawScene, { faces: [face, 2] }); face += 2; if (face === 6) { face = 0; probe += 1; } return probe === probes; }; } ``` `setProbeGrid({ origin, spacing, counts })` places probes on a lattice, and a surface blends the eight around it. `bakeProbeGrid` bakes them all in one call, for a scene that can afford a stall at load. `bakeProbe(index, clear, drawFace, options)` bakes one, and its `faces` option draws only some of its six faces, so the cost spreads over frames: a probe of a scene with millions of triangles is otherwise the most expensive thing in its frame. Finish one probe before starting the next. The grid is not sampled until every probe has been baked, so a paced grid keeps the old light until the last one lands. `crossfade: true` on the grid blends each sweep of bakes into the next, for a grid re-baked continuously under a moving light. It costs three times the layers and a sweep of lag. ## Light that bounces ```ts /** * Each bake lit by the last, so light bounces deeper into an enclosed space with every sweep. A * scene that holds one moment bakes the grid two or three times. */ export function bounceInto( renderer: RendererApi, drawScene: (camera: Camera) => void, clear: Vec3, ): void { for (let sweep = 0; sweep < 3; sweep += 1) renderer.bakeProbeGrid(clear, drawScene, { bounce: true }); } ``` A probe sees the scene lit by the sun and the ambient, so a grid holds one bounce of light. An enclosed space is lit mostly by the second bounce and later; a courtyard's arcades came out about two stops darker than a reference render with one. `bounce: true` lights what each probe sees with the grid's previous bake, so every sweep adds a bounce, and two or three sweeps converge. It costs nothing extra. Light that leaks through a wall into a probe is bounced again too, so a leak grows with each sweep. ## A photographed sky ```ts /** A photographed sky, from a Radiance `.hdr` file, as the environment everything reflects. */ export async function loadSky(renderer: RendererApi, url: string): Promise { const bytes = new Uint8Array(await (await fetch(url)).arrayBuffer()); return renderer.setEnvironmentImage(readRadianceHdr(bytes)); } ``` `readRadianceHdr(bytes)` from `@driftengine/assets` reads a Radiance `.hdr` file into linear radiance, and `setEnvironmentImage(image)` makes it the environment: the faces go into the same cube a bake fills and the same convolution runs, so a loaded sky lights and reflects exactly as a baked one would. It is a grid of one at the origin, since a sky is the same everywhere. ## Captures from another tool ```ts /** * A reflection capture baked in another tool, into one layer of the grid `setProbeGrid` declared: * prefiltered as the environment is, the other layers left as they are. */ export async function loadCapture( renderer: RendererApi, layer: number, url: string, ): Promise { const bytes = new Uint8Array(await (await fetch(url)).arrayBuffer()); return renderer.setProbeLayerImage(layer, readRadianceHdr(bytes)); } ``` A stage made in another engine reflects its own captures, each an image taken where it stands. Fit them to a grid: declare one with `setProbeGrid`, and for each point hand `setProbeLayerImage(layer, image)` the image of the capture whose reach holds it. Each image is projected and prefiltered into its layer exactly as `setEnvironmentImage` treats the environment, and the other layers keep what they hold. ## A draw's own ambient ```ts /** * A character lit by where it stands: nine coefficients of the light around it, red, green and * blue of each, sampled from a baked volume every frame and set around its draws alone. */ export function drawLitWhereItStands( renderer: RendererApi, character: MeshHandle, placement: Float32Array, coefficients: Float32Array, ): void { renderer.setAmbientSH(coefficients); renderer.drawMesh(character, placement); renderer.setAmbientSH(null); } ``` `setAmbientSH(coefficients)` gives the draws that follow an ambient of their own: nine second-order spherical-harmonic coefficients of the light arriving from every side, red, green and blue of each, 27 numbers. A character walking through a stage whose indirect light was baked into a volume samples the volume where it stands every frame and sets the result around its own draws, so it takes the light of its spot rather than the frame's. It replaces the diffuse ambient only; a glossy surface still reflects the probes. `null`, or the next `bindMeshPass`, gives the frame's ambient back. ## Prefiltered reflections By default each level of a probe is a smaller picture of the room. With `environmentPrefilter` on, each level is the room convolved with the reflection lobe of the roughness that level stands for, which is the physically correct answer and much blurrier at the same roughness. Turn it on for materials authored for it; surfaces authored against the default read as a wash. `environmentPrefilterSamples` sets the convolution's cost, 32 by default, 16 and 128 for the low and high tiers. ## Per-draw dials ```ts /** A polished floor in a dim hall: reflect fully, and lift what is reflected. */ export function polishedFloor(renderer: RendererApi, env: Environment, camera: Camera): void { renderer.bindMeshPass(camera, env); renderer.setSurfaceReflectivity(1); renderer.setEnvironmentGain(1.6); } ``` `setSurfaceReflectivity(amount)` says how much of the environment the next surfaces mirror, and `setEnvironmentGain(gain)` how bright that environment is, for a hall whose captured probe is dimmer than the light a polished floor should show. `bindMeshPass` resets both. See [Materials](https://driftengine.dev/docs/rendering/materials) for the rest of a surface. `setEnvironmentMixing(weight, roughnessLow, roughnessHigh)` brings what every surface reflects, metal or not, to the light where it stands. A probe is captured at one place and seen from many, so a figure standing where the indirect light is twice what the probe saw reflects the probe too dimly against everything lit around it. `weight` is that ratio, the place's indirect light over the probe's own average brightness, above 1 or below. A mirror keeps the capture as it is and a rough surface takes the whole weight, mixed by a smoothstep between the two roughnesses, 0.1 and 0.3 by default. `bindMeshPass` resets it to 1, which is none. ## Reflecting what the frame drew ```ts /** * A polished stone floor that reflects what the frame drew on it, weighed as the stone itself * would: four per cent head-on, rising toward the horizon, at the stone's roughness. */ export const stoneFloor = new ReflectiveSurface({ center: [0, 0, 0], halfExtents: [12, 12, 0.2], forward: [0, -1, 0], up: [0, 0, 1], strength: 0.04, fresnel: true, roughness: 0.2, }); /** Submitted each frame between `beginFrame` and `endFrame`, and traced when the frame ends. */ export function drawFloorReflection(renderer: RendererApi): void { renderer.drawReflection(stoneFloor); } ``` A `ReflectiveSurface` is a box; the surfaces inside it that face back along its `forward` axis reflect what the frame has already drawn. `drawReflection` submits it each frame, and when the frame ends a ray is marched from every pixel it covers against the frame's own depth. It follows the surface per pixel, whatever its shape, and is exact where an object meets the floor; it cannot reflect anything off screen or hidden behind the surface. It needs `screenEffects`, and says so once where there are none. `strength` is the share of what the ray finds that lands on the surface, one number over the box. With `fresnel: true` it is the surface's reflectance head-on instead, and each pixel returns `strength · A + B` of what it finds: the split-sum BRDF at its own view and the box's `roughness`, the fit the lit stage reflects its environment by. A floor then reflects more toward the horizon than underfoot, and the share follows the camera, as a real floor's does. The roughness and reflectance are the box's rather than each pixel's; for each pixel's own, see the next section. ## Every surface by its own material ```ts /** * Every opaque lit surface reflecting the frame by its own material: a glossy panel mirrors what * stands on it, a satin one shows it softened, and past a roughness of 0.5 a surface keeps the * probes' reflection alone. A quality option, so chosen when the renderer is built. */ export const reflectiveQuality: RenderQualityOptions = { screenEffects: true, hdrScene: true, screenSpaceReflections: { maxRoughness: 0.5 }, }; ``` `screenSpaceReflections` makes every opaque lit surface reflect the frame, each by its own material rather than by a box's. The lit stage leaves behind, per pixel, how much of the environment it reflected there and at what roughness, and a ray marched against the frame's depth swaps that share of the probe for what it finds. So one floor mesh with one ORM map mirrors the figures standing on its glossy panels and barely shows them on its matte ones. Rougher surfaces show a softer reflection, and past `maxRoughness` a surface keeps the probes' reflection alone, faded over the last quarter below it. `true` takes `DEFAULT_FRAME_REFLECTIONS`; a `FrameReflections` sets the ceiling, the march's reach, thickness and steps, and the blur. What a surface reflects is what the lit stage already reflected: a metal by its metalness, a dielectric where `setSurfaceReflectivity` or its material asks for a reflection. A surface that reflects no environment reflects no frame either. Where a ray leaves the frame or finds nothing, the probe's reflection stays. It needs `screenEffects` and `hdrScene`, since the swap is made in scene light, and a frame of one sample; where it has none of these it says so once and draws the probes alone. On WebGPU it draws every opaque lit draw a second time, without its lamps, into two half-float targets. On WebGL2 the draws write those targets beside their colour. Either way it then marches each reflective pixel. Draws through the GPU-driven pipeline are reflected, but do not reflect. Water reflects through its own planar mirror; see [Water](https://driftengine.dev/docs/rendering/water). For a wet street, see [Wet surfaces](https://driftengine.dev/docs/rendering/wet-surfaces). --- # Sky and atmosphere Rendering. https://driftengine.dev/docs/rendering/sky-and-atmosphere A procedural sky with sun, moon, stars and clouds, a celestial clock for a real latitude and date, and a palette that lights the hours. The sky is drawn, not loaded: a gradient with a sun disc, a sunset band that follows the sun's height, a moon with its phase, stars at night and clouds carried by the wind. Where the sun and moon stand comes from a celestial clock, and what the hours look like from a palette you write. The example runs a midsummer day at forty degrees north in ninety seconds; `?hour=19` starts it at dusk. (This chapter runs the `sky` example at https://driftengine.dev/docs/rendering/sky-and-atmosphere.) ## Drawing the sky ```ts renderer.beginFrame(sky.horizon); renderer.bindMeshPass(camera, env); renderer.drawMesh(setMesh, still.worldMatrix); /* Last, so it fills only what the world left empty. */ renderer.drawSky(camera, sky, env); renderer.endFrame(); ``` `drawSky(camera, sky, env)` is the frame's last opaque draw and fills only the pixels the world left empty. Its `SkyColors` say: - `top`, `horizon` and `deep`: the zenith, the horizon, and the colour below the horizon. - `sunDir` and `sunColor`: where the sun is and how bright its disc is. `sunAngularRadius`, in radians, is how large the disc looks, independent of how much light it gives. - `moonDir`, `moonColor`, `moonAngularRadius` and `moonPhase`, 0 to 1 across the cycle: the moon is a shaded sphere lit from the side its phase says. - `nightFactor`: how much of the night sky shows, which is the stars. - `cloudOffsetX` and `cloudOffsetZ`: how far the cloud layer has drifted, in metres. Accumulate the same wind the smoke and the grass answer to, so the biggest moving thing in the frame agrees with the smallest. The sunset band is driven by the sun's elevation alone. It is strongest as the sun touches the horizon and gone once the sun is well up or well down, so a sun pointing straight down, which is how a world says it has no sun, gives no sunset. The sun and moon fade out below the horizon. The sky is fogged by the same atmosphere as the world, so a distant hill and the horizon behind it agree. ## The celestial clock ```ts /** A site names where the sky is: forty degrees north, on the meridian, keeping UTC. */ const SITE = { latitudeDeg: 40, longitudeDeg: 0, utcOffsetHours: 0 }; /** Midsummer, and a day that lasts ninety seconds, starting before sunrise or at `?hour=`. */ const MIDSUMMER = Date.UTC(2026, 5, 21); const DAY_SECONDS = 90; const START_HOUR = flagNumber('hour', 3.5); /** Where the world's north points, as an angle in the xz plane from +x toward +z: here, -z. */ const NORTH = -Math.PI / 2; const celestial = createCelestialState(); function hourAt(seconds: number): number { return (START_HOUR + (seconds / DAY_SECONDS) * 24) % 24; } ``` `celestialStateAt(whenMs, north, out, site)` writes the sun's and the moon's directions, the `dayFactor` and `nightFactor`, each 0 to 1 and smooth across twilight, and the `moonPhase`. `north` is where the world's north points, as an angle in the xz plane from +x toward +z. With a `CelestialSite`, the sun is placed by the standard solar-position arithmetic: a declination from the day of the year, an hour angle from the clock, and an altitude and azimuth from those and `latitudeDeg`. Naming `longitudeDeg` or `utcOffsetHours` makes `whenMs` a UTC instant and derives the site's own hour from it, so every machine draws the same sky for the same arguments. `dayOfYear` overrides the date for a world on a calendar of its own, and `obliquityDeg` changes the planet's tilt. Without a site, the sun swings through a fixed arc that peaks at 66 degrees every day, and the hour is read through the host machine's time zone. Worlds tuned against that arc keep it. The clock is presentation. Derive `whenMs` from your game's own time, as the example does, and keep it out of anything the simulation decides; see [Determinism](https://driftengine.dev/docs/concepts/determinism). `moonIllumination(phase)` is the lit fraction of the moon, for scaling moonlight. ## A daylight palette ```ts /** The day's light, keyed by how much day there is: night, the warm edge of dusk, and noon. */ const palette = createDaylightPalette([ { at: 0, sunColor: [0, 0, 0], moonColor: [0.16, 0.2, 0.3], skyTop: srgbColor(0.004, 0.006, 0.016), skyHorizon: srgbColor(0.02, 0.03, 0.06), skyDeep: srgbColor(0.01, 0.012, 0.02), ambient: [0.02, 0.025, 0.04], ambientGround: [0.01, 0.01, 0.014], fogColor: [0.02, 0.025, 0.04], fogDensity: 0.01, shadowStrength: 0.5, emissiveGain: 2, exposure: 2.4, }, { at: 0.35, sunColor: [1.6, 0.8, 0.4], moonColor: [0, 0, 0], skyTop: srgbColor(0.12, 0.16, 0.32), skyHorizon: srgbColor(0.9, 0.5, 0.3), skyDeep: srgbColor(0.2, 0.15, 0.15), ambient: [0.18, 0.16, 0.2], ambientGround: [0.08, 0.06, 0.05], fogColor: [0.5, 0.36, 0.3], fogDensity: 0.008, shadowStrength: 0.7, emissiveGain: 1, exposure: 1.4, }, { at: 1, sunColor: [2, 1.9, 1.7], moonColor: [0, 0, 0], skyTop: srgbColor(0.18, 0.36, 0.78), skyHorizon: srgbColor(0.62, 0.74, 0.9), skyDeep: srgbColor(0.3, 0.34, 0.4), ambient: [0.3, 0.36, 0.48], ambientGround: [0.14, 0.12, 0.1], fogColor: [0.6, 0.7, 0.85], fogDensity: 0.005, shadowStrength: 0.9, emissiveGain: 0, exposure: 1, }, ]); const light = createDaylightState(); ``` A day's lighting is data: sun and moon colours, the three sky colours, the hemispheric ambient, fog colour and density, shadow strength, emissive gain and exposure, at points along any number you choose. The example keys it by `dayFactor`; a courtyard might key it by the sun's elevation in degrees, or a game by the hour. `resolveDaylight(at, palette, out)` blends the two nearest keys, linearly for colours and in stops for exposure, and allocates nothing. ```ts const hour = hourAt(time); celestialStateAt(MIDSUMMER + hour * 3_600_000, NORTH, celestial, SITE); resolveDaylight(celestial.dayFactor, palette, light); /* Whichever body is up lights the world; the sky draws both and hides what has set. */ const body = celestial.dayFactor > 0.5 ? celestial.sunDir : celestial.moonDir; env.directionalDir = body; const moonlight = moonIllumination(celestial.moonPhase); for (let c = 0; c < 3; c += 1) env.directionalColor[c] = light.sunColor[c] + light.moonColor[c] * moonlight; env.ambient = light.ambient; env.ambientGround = light.ambientGround; env.fogColor = light.fogColor; env.fogDensity = light.fogDensity; env.shadowStrength = light.shadowStrength; env.emissiveGain = light.emissiveGain; env.nightFactor = celestial.nightFactor; sky.top = light.skyTop; sky.horizon = light.skyHorizon; sky.deep = light.skyDeep; sky.sunDir = celestial.sunDir; sky.moonDir = celestial.moonDir; sky.moonPhase = celestial.moonPhase; sky.nightFactor = celestial.nightFactor; sky.cloudOffsetX = time * 1.5; sky.cloudOffsetZ = time * 0.6; exposure = easeExposure(exposure, light.exposure, time - shownAt, 1.5); renderer.setOutputExposure(exposure); shownAt = time; ``` Every frame the example asks the clock, resolves the palette, and copies the answer into the environment and the sky. Whichever body is up is the directional light, and its shadow follows it. Lamps come on with `nightFactor`, on a steeper curve so they are off all afternoon. ## Exposure through the day Noon and midnight differ by more than a screen can show, so the exposure moves with the light. `easeExposure(current, target, dt, halfLife)` moves toward the palette's exposure in stops, with the half-life you choose, and `renderer.setOutputExposure` applies it. Easing it, instead of setting it, is what reads as an eye adapting. Exposure needs `outputTransform: 'aces'`; see [Colour and motion](https://driftengine.dev/docs/rendering/colour-and-motion). ## Lighting from the sky The sky colours the picture, and the hemispheric ambient lights the world. For reflections of the sky, and for lighting from a photographed sky loaded from an HDR image, see [Reflections](https://driftengine.dev/docs/rendering/reflections). --- # Fog and weather Rendering. https://driftengine.dev/docs/rendering/fog-and-weather Height fog and linear fog, the underwater atmosphere, one wind for the scene, rain that stops under roofs, lightning, and storm debris. Weather is several effects that must agree with each other: fog thick enough to hide the far end of the street, rain leaning the way the smoke leans, clouds drifting the same way, the ground wet where it rains. The example runs one street through three weathers; switch them in the strip. (This chapter runs the `weather` example at https://driftengine.dev/docs/rendering/fog-and-weather.) ## The weather, in DriftScript The example's weather is a DriftScript module, and the page draws what it says. The kinds of sky are an enum, `Sky`, and a `match` for each quantity names what each kind does to the fog, the gloom, the rain and the wind, so a fourth sky does not compile until it has its numbers: ```drs // Each quantity, for each kind of sky. A sky added to `Sky` stops these compiling until it has its // own numbers. fn fogFor(kind: Sky) -> f32 { return match kind { Clear => 0.003 Rain => 0.012 Storm => 0.014 } } fn gloomFor(kind: Sky) -> f32 { return match kind { Clear => 0 Rain => 0.3 Storm => 1 } } fn rainFor(kind: Sky) -> f32 { return match kind { Clear => 0 Rain => 0.6 Storm => 1 } } fn windFor(kind: Sky) -> f32 { return match kind { Clear => 3 Rain => 3 Storm => 9 } } ``` and once a frame `advance` eases every quantity toward what the switch asked for, so a storm rolls in over a few seconds instead of switching on, and the road takes a minute to dry after the rain. It also decides when lightning strikes, with a gap drawn from `drift/random` by the number of strikes so far, so a replay strikes at the same moments. ```drs // One frame of weather. Answers whether lightning strikes on this one. fn advance(sky: mut Weather, dt: f32) -> bool { sky.fog = toward(sky.fog, fogFor(sky.kind), 0.004, dt) sky.gloom = toward(sky.gloom, gloomFor(sky.kind), 0.3, dt) sky.rain = toward(sky.rain, rainFor(sky.kind), 0.4, dt) sky.wind = toward(sky.wind, windFor(sky.kind), 2, dt) // The road gets wet in seconds and dries over a minute. if sky.rain > 0.05 { sky.wetness = toward(sky.wetness, 1, 0.3, dt) } else { sky.wetness = toward(sky.wetness, 0, 0.02, dt) } sky.flash = math.max(sky.flash - dt * 4, 0) if sky.kind != Sky.Storm { return false } sky.nextStrike = sky.nextStrike - dt if sky.nextStrike > 0 { return false } // The gap to the next one comes from how many there have been, so a replay strikes alike. sky.strikes = sky.strikes + 1 sky.nextStrike = random.range(sky.strikes, 2, 7) sky.flash = 1 return true } ``` ```ts /* The script moves the weather on, and says whether lightning strikes this frame. */ const strikes = exported(weather, 'advance')(sky, dt); env.fogDensity = sky.fog; env.wetness = sky.wetness; env.fogFar = 110 - sky.gloom * 40; for (let c = 0; c < 3; c += 1) { env.fogColor[c] = CLEAR_FOG[c] + (STORM_FOG[c] - CLEAR_FOG[c]) * sky.gloom; env.ambient[c] = ambient[c] + sky.flash * 0.9; } wet.reflectionStrength = 0.7 * sky.wetness; profile.baseSpeed = sky.wind; profile.gustSpeed = sky.wind * 0.45; advanceWindField(wind, profile, time, dt, 1); heavens.cloudOffsetX = wind.driftX; heavens.cloudOffsetZ = wind.driftZ; rain.update(dt, x, y, z, wind.velocityX, wind.velocityZ); /* How hard it rains is how many of the drops are drawn. */ rain.segments.count = Math.floor(rain.segments.count * sky.rain); if (strikes) { const n = sky.strikes; const bx = (hashToUnit(n) - 0.5) * 12; const bz = z - 45 - hashToUnit(n + 99) * 20; bolts.strike(bx, 70, bz, bx + (hashToUnit(n + 7) - 0.5) * 20, 0, bz, n); } bolts.update(dt); ``` The page holds the `Weather` record, writes the switch into `kind`, and turns the record into fog, wetness, wind, rain and bolts. Under `npm run examples`, an edit to `weather.drs` is patched into the running page and the sky carries on from where it was; the rest of this chapter is what the page does with the numbers. ## Fog ```ts /** Dense near the ground and thinning with height; or a clear near field and a wall of grey. */ const env = createEnvironment({ directionalDir: [-0.3, 0.35, -0.6], directionalColor: [0.5, 0.48, 0.52], ambient: [0.16, 0.18, 0.22], ambientGround: [0.06, 0.06, 0.07], fogColor: [0.24, 0.26, 0.3], fogDensity: 0.003, fogHeightFalloff: 0.08, fogBaseY: 0, fogMode: flag('fog', 'exponential') === 'linear' ? 'linear' : 'exponential', fogNear: 12, fogFar: 110, wetness: 0, nightFactor: 1, emissiveGain: 1.2, }); ``` Fog is part of the environment, and everything drawn with that environment is fogged by it: meshes, the sky, lines, plumes, bolts and particles. A translucent draw can opt out with `fog: false`. - `fogDensity` is extinction per metre where the fog is thickest, at height `fogBaseY`. Small numbers go a long way: the example uses 0.003 for a clear evening, 0.012 for rain and 0.014 for a storm. - `fogHeightFalloff` thins it with height: at `y` the density is `fogDensity` times `exp(-(y - fogBaseY) · fogHeightFalloff)`. Zero is a uniform medium, right for a room; a value like 0.05 makes a valley hazy and the view from the ridge clear. - `fogColor` is what distant things fade to. Match it to the sky's horizon, or the horizon line shows. - `fogStart` is how far along the view ray the haze begins, in metres; it is 0, at the camera, unless set. Nearer than that the air is perfectly clear, and beyond it the haze is the same extinction, integrated from that point on. A faint, bright fog starting ten metres out hazes a far crowd and leaves the figures in front of the camera sharp, where the same fog from the eye would veil the whole frame. It does nothing in `'linear'` mode, which has `fogNear`. - `fogLayer2` is a second layer of haze, `{ density, heightFalloff, baseY }`, summed with the first along every ray: a ground mist under a high summer haze, each thinning at its own rate. - `fogMaxOpacity`, 0 to 1, is the most of a surface the haze may hide. Below 1 a skyline keeps that much of itself however much air lies in front of it. - `fogCutoff` is a distance past which the haze hides nothing at all, the sky included: for a sky or a backdrop that brings its own haze painted in. - `fogSunGlow` is the sun's light the haze scatters toward the eye, `{ color, exponent, start }`: `color` looking straight at the sun through haze that hides everything, falling off as the cosine of the angle from the sun to the power `exponent`, and beginning `start` metres past where the haze begins. It follows `directionalDir` unless given a `direction` of its own, and it is added on top of the fog rather than mixed in, so a far ridge seen into a low sun burns gold. The densities and falloffs are in natural units: what survives a stretch of haze is `exp(-density · metres)`. A haze authored in base two, its surviving light `2^(-∫ρ)` and its density falling as `2^(-f · Δy)`, is `density: ρ · (ln 2)²` and `heightFalloff: f · ln 2` here. `fogMode: 'linear'` is a different look: nothing at all nearer than `fogNear`, the fog colour completely at `fogFar`, and a straight ramp between. It cannot be had from the exponential curve at any density. Fog darkens what is behind it, and with `fogSunGlow` it glows toward the sun; it does not know where the sun's shadows fall. For air that scatters light through those shadows, shafts through a window and a lamp's glow cut by what stands in front of it, see [Light in the air](https://driftengine.dev/docs/rendering/light-in-the-air). ## Under water `env.underwater` gives the water column its own atmosphere: `surfaceY`, the `color` light converges toward under the surface, a `fogDensity` for the water, and a `transitionDepth` over which the camera crosses smoothly from one to the other. Below the surface the sky is replaced by the water's colour. The `underwaterAtmosphere` quality option, on by default, allows it. [Water](https://driftengine.dev/docs/rendering/water) covers the surface itself. ## One wind ```ts /** One wind for everything. It gusts and wanders, and repeats exactly every forty seconds. */ const profile: WindProfile = { directionX: 1, directionZ: 0.3, baseSpeed: 3, gustSpeed: 1.5, directionWander: 0.3, cycleSeconds: 40, phase: 0, }; const wind = createWindField(); ``` A `WindProfile` describes a wind: a prevailing direction, a base speed, gusts on top of it, how far the direction wanders, and a cycle after which the whole signal repeats exactly. `sampleWind(profile, time, out)` gives the velocity at a moment. `advanceWindField(field, profile, time, dt, driftScale)` does the same and also accumulates `driftX` and `driftZ`, the distance the wind has carried something, which is what clouds and dust need: a wandering direction multiplied by an absolute time would jump them whenever the direction moved. Sample it once a frame and pass the same field to everything that moves in it: the rain's `update`, the plumes' `windX` and `windZ`, the grass in `drawScatter`, the sky's cloud offset, a light volume's `driftM`, and the debris below. A system that samples its own wind is a second wind. ## Rain ```ts /** Drops around the viewer, drawn as streaks along their motion. */ const rain = new RainField({ count: 2400, radiusM: 14, heightM: 12, speedMps: 11, streakSec: 0.05, }); const drops = renderer.createLines(rain.segments.capacity, 'rain'); const RAIN_COLOUR: Vec3 = [0.5, 0.55, 0.62]; ``` `RainField` keeps a box of drops around the viewer and draws each one as a streak along its motion, which is what rain looks like in a photograph. `count` drops fill a box `radiusM` wide and `heightM` high; `speedMps` is the fall speed, about 9 for rain, 2 for drizzle and 14 for hail, and can change while it runs; `streakSec` is the shutter time a streak shows. `update(dt, x, y, z, windX, windZ)` moves the drops and rebuilds the streaks around the viewer, and `drawLines` draws them like any other line batch. Give the field a `ground` surface and drops land on it and stop under roofs: a drop with something over it is not drawn. A drop closer than `clearM`, one metre by default, is not drawn either, since a camera never holds that in focus. The drops' positions are a hash of their index, with no clock and no random number, so the same viewer at the same moment sees the same rain. To rain harder or lighter without rebuilding the field, draw a share of the segments: set `segments.count` lower after `update`. ## Wet ground `env.wetness`, 0 to 1, darkens and polishes every upward surface, except materials that say they stay dry. It is a dial, so a scene can let the ground dry slowly after the rain stops. [Wet surfaces](https://driftengine.dev/docs/rendering/wet-surfaces) covers it, and puddles. ## Lightning ```ts /** Arcs from the clouds to the ground, re-drawn many times a second while they live. */ const bolts = new BoltPool({ capacity: 3, nodes: 33, lifeSec: 0.4, jitter: 0.08, restrikeHz: 16 }); const boltBatch = renderer.createBolts(bolts.segments.capacity, 'lightning'); ``` `BoltPool` holds arcs that strike between two points and are re-drawn many times a second while they live, which is the crackle a smoothly animated line cannot give. `nodes` is the points along each arc, a power of two plus one; `jitter` how far they wander off the straight line, as a share of the span; `restrikeHz` how often a live arc takes a new path. `strike(x0, y0, z0, x1, y1, z1, seed, brightness, lifeScale)` starts an arc, and the path comes from `seed`, never from `Math.random`, so a replay strikes the same bolts. `update(dt)` advances the pool and `drawBolts` draws its segments with a core colour, an edge colour and a width. Varying `lifeScale` per strike makes a volley die like several discharges instead of one switch. The pool advances; it does not evaluate at a time. Rendering one plan twice at different frame rates, for a preview and an export, gives two different arcs. For that case, fill `BoltSegments` yourself from a seed and an absolute time and hand it to `drawBolts`. A bolt is light the eye sees, not light the world receives: the example brightens the ambient for a moment after each strike to make the flash. ## Debris in a storm ```ts if (rain.segments.count > 0) renderer.drawLines(drops, rain.segments, IDENTITY, camera, env, RAIN_COLOUR, 0.006, 0.7, 0.4); renderer.drawBolts( boltBatch, bolts.segments, camera, env, time, [1, 1, 1.3], [0.45, 0.55, 1], 0.9, 3, ); renderer.drawWindStreaks(debris, camera, wind, time, [0.35, 0.33, 0.3], env); ``` `createWindStreaks` makes a lattice of wind-borne debris in a box that follows the camera, and `drawWindStreaks(streaks, camera, wind, time, tint, env)` draws it only once the wind is strong enough to be worth seeing: nothing below `onsetSpeed`, six metres a second by default, full strength at `fullSpeed`, eleven. Debris in a breeze is noise; debris in a gale tells the player why their glide is drifting. Under water, the engine leaves it out. --- # Water Rendering. https://driftengine.dev/docs/rendering/water One water for sea, lake, fountain and canal: waves the wind builds, Fresnel and planar reflections, caustics, and the view from below. The sea, a lake, a fountain basin and a flooded corridor are the same water with different numbers: every body gets the waves, the Fresnel reflection, the highlight, the fog and the mirror, and differs only in how dense it is, how built-up its waves are and whether it has edges. The example is the open sea beside a pier; switch the wind in the strip and watch the sea change. (This chapter runs the `water` example at https://driftengine.dev/docs/rendering/water.) ## The sea ```ts /** The sea: no bounds, so it is endless and follows the camera; dense, so it hides its floor. */ const sea = renderer.createWater(); const seaBody: WaterBody = { level: 0, deepColor: srgbColor(0.03, 0.07, 0.1), shallowColor: srgbColor(0.08, 0.16, 0.18), density: 0.95, }; ``` `createWater()` builds the surface: a grid that follows the camera and is snapped to whole cells, so a fixed number of vertices covers an endless ocean without the surface sliding underfoot, with a flat skirt carrying it to the horizon. The waves are Gerstner waves, so crests are sharp and troughs broad. Its optional arguments are the cells per side of the wave-bearing sheet, its width in metres (500) and how far the skirt reaches (4,000). A `WaterBody` describes what is drawn: - `level`, the resting height of the surface. - `deepColor` and `shallowColor`. - `density`, 0 to 1: how much of what lies beneath the water hides, looking straight down. A sea hides its floor; a fountain shows its tiles; 0 is glass. At a grazing angle every water surface is a mirror, which is Fresnel and not a property of the liquid. - `visibility`, 0 to 1, fades the whole surface; 0 draws nothing. - `mirror`, 0 to 1, how much it reflects regardless of angle. Zero is physics, right for the sea; a pool is looked into from above, where Fresnel alone reflects a few per cent, so it may cheat. - `waveScale`, the waves as a multiple of what the wind builds: 1 for open sea, a fraction for a basin. - `agitation`, 0 to 1, for water the weather cannot reach. Omitted, the body takes its state from the wind. ```ts renderer.beginFrame(HORIZON); /* The world again, mirrored across the water's plane, for the next water draw to sample. */ const mirrored = renderer.beginPlanarReflection(camera, seaBody.level, HORIZON); if (mirrored !== null) { drawWorld(mirrored); renderer.endPlanarReflection(); } drawWorld(camera); renderer.drawWater(sea, camera, time, seaBody, env, wind.velocityX, wind.velocityZ); renderer.drawCaustics(caustics, camera, time, env, wind.velocityX, wind.velocityZ); renderer.endFrame(); ``` `drawWater(water, camera, time, body, env, windX, windZ)` draws a body after the opaque scene and after the sky, since its far edge fades into what is behind it. Pass the scene's one wind: wind builds waves, it does not just push them, so a calm sea is nearly flat and a gale raises steep crests that break into foam. `seaStateForWind(speed)` returns the same steepness and foam the renderer uses, for anything in the game that needs to agree with what is drawn. ## Bounded bodies ```ts /** A fountain basin: clear enough to see the tiles, a little mirror, and only a breath of wave. */ export const basin: WaterBody = { level: 0.6, deepColor: srgbColor(0.05, 0.12, 0.14), shallowColor: srgbColor(0.2, 0.32, 0.3), density: 0.25, mirror: 0.35, waveScale: 0.12, bounds: { centreX: 0, centreZ: 0, halfM: 2.5 }, }; ``` `bounds` turns the endless sea into a rectangle of water exactly where it is put: a centre, and half extents either as one `halfM` for a square or as `halfX` across and `halfZ` along. ```ts /** A canal three metres across and forty long, running north-east. */ export const canal: WaterBody = { level: -0.4, deepColor: srgbColor(0.03, 0.06, 0.05), shallowColor: srgbColor(0.08, 0.14, 0.1), density: 0.8, waveScale: 0.3, bounds: { centreX: 20, centreZ: -10, halfX: 1.5, halfZ: 20, forwardX: 1, forwardZ: -1 }, }; ``` `forwardX` and `forwardZ` turn the rectangle to point where a canal runs, given as a direction because a channel usually arrives as one, from a road graph or a spline's tangent. A canal that bends is one body per straight run. ```ts /** A flooded corridor: the wind never reaches it, so it says how stirred it is itself. */ export const tank: WaterBody = { level: -1, deepColor: srgbColor(0.02, 0.03, 0.03), shallowColor: srgbColor(0.06, 0.08, 0.07), density: 0.9, agitation: 0.15, bounds: { centreX: 0, centreZ: 40, halfX: 2, halfZ: 12 }, }; /** The sea state the renderer would use for a wind, for gameplay that wants the same answer. */ export const choppy = seaStateForWind(8); ``` ## Reflections The example's frame opens with a planar reflection: `beginPlanarReflection(camera, level, clear)` returns a camera mirrored across the water's plane, the scene is drawn again from it, and `endPlanarReflection` finishes the target that the next water draw samples. Draw the same things in both passes, with the water left out of its own reflection; a function that draws the world for a given camera, like the example's `drawWorld`, keeps the two the same. It returns `null` when the profile has no reflection target, so a scene skips the pass without a second branch. The reflection is one plane, so it is exact for one water level. The target exists when the `water` and `waterReflections` quality options are on, which they are by default, or when `planarReflections` asks for it in a scene with no water; `waterReflectionScale` sets its size against the frame, and `waterReflectionFilterTaps`, 1, 5 or 9, how much water blurs it. A wet road can sample the same mirror, as [Wet surfaces](https://driftengine.dev/docs/rendering/wet-surfaces) shows; other surfaces reflect probes, in [Reflections](https://driftengine.dev/docs/rendering/reflections). ## Caustics ```ts /** The underside of the deck, two centimetres below it, as a sheet the water lights from below. */ const caustics = renderer.createCaustics([ { spans: [ { x0: -3, z0: 2, x1: 3, z1: 2, y: 1.58 }, { x0: -3, z0: -40, x1: 3, z1: -40, y: 1.58 }, ], waterY: 0, }, ]); ``` Light passing through waves gathers into a moving net on whatever is near the water: the floor of a pool, the underside of a bridge or a jetty, a cave mouth. `createCaustics(sheets)` takes the lit surfaces as sheets, each a row of cross-sections, and the `waterY` of the water lighting it. Place a sheet a couple of centimetres off the surface it lights, on the side it is seen from, as the example does under the deck. `drawCaustics(caustics, camera, time, env, windX, windZ, strength)` adds the light after the opaque scene; it is computed from the same wave field as the surface, so the net moves with the crests above it. It fades out within about a dozen metres of the water. `createCaustics` returns `null` when the profile has water off or there are no sheets, and `drawCaustics` accepts `null`, so a world without caustics needs no branch. ## Under the surface With `env.underwater` set, a camera below `surfaceY` sees the water column: distance fades to the water's colour, the sky is replaced by it, and crossing the surface is a smooth transition over `transitionDepth`. See [Fog and weather](https://driftengine.dev/docs/rendering/fog-and-weather). ## Quality | Option | Default | What it does | | --------------------------- | ------- | ------------------------------------------------------------------------------- | | `water` | `true` | Whether water is drawn at all. Off, every water and caustics call does nothing. | | `waterResolution` | 128 | Cells per side of the wave-bearing sheet. | | `waterReflections` | `true` | The planar reflection target, for water. | | `planarReflections` | `false` | The same target in a scene without water. | | `waterReflectionScale` | 1 | The reflection target's size against the frame. | | `waterReflectionFilterTaps` | 9 | Blur taps on the reflection: 1, 5 or 9. | | `underwaterAtmosphere` | `true` | The water column's own fog under the surface. | --- # Wet surfaces Rendering. https://driftengine.dev/docs/rendering/wet-surfaces A world that gets wet in the rain and dries after, puddles that fade at their rims and mirror the street, and the sheen of an oil slick. Rain changes the ground in two ways. Everything that faces up darkens and turns glossy, and water gathers in the low places, where it mirrors the street. The engine draws the first with one number on the environment and the second with films: thin transparent surfaces laid over the world. The example's rain and storm both wet the street; the clear weather leaves it dry. (This chapter runs the `weather` example at https://driftengine.dev/docs/rendering/wet-surfaces.) ## The world gets wet `env.wetness`, from 0 to 1, darkens and polishes every upward surface. It is a dial: raise it as rain starts, and lower it slowly after the rain stops, so the street dries over a minute and not in a frame. Surfaces that rain cannot reach, a covered walkway or an interior floor, stay dry when their texture-array layer is marked `dry`; see [Texture arrays](https://driftengine.dev/docs/rendering/texture-arrays). ## Puddles ```ts /** Puddles down the middle of the road: feathered patches lying a centimetre above it. */ const roadLine = new Spline( [8, -20, -50, -80].map((z) => ({ x: 0, y: 0, z, bankRad: 0, widthM: 8 })), ); const puddles = [ { fromM: 4, toM: 16, centreM: -1.2, halfWidthM: 1.6, seed: 3 }, { fromM: 22, toM: 40, centreM: 1.4, halfWidthM: 2.2, seed: 8 }, { fromM: 48, toM: 60, centreM: -0.4, halfWidthM: 1.8, seed: 13 }, { fromM: 66, toM: 84, centreM: 0.8, halfWidthM: 2.4, seed: 21 }, ].map((patch) => renderer.createMesh( buildFilmPatch(roadLine, { ...patch, liftM: 0.012, color: [0.012, 0.014, 0.018] }), ), ); /** They mirror across the road's own plane, a little roughened by the stone under them. */ const wet = { reflectionStrength: 0.7, reflectionPlaneY: 0, roughness: 0.25 }; ``` `buildFilmPatch(spline, options)` builds the shape a spill has: an irregular patch that follows a surface's curve and bank and dissolves at its rim. A patch with a hard edge reads as a sticker whatever it is made of, because a real puddle is thinnest where it ends, so the patch carries a coverage value per vertex, 1 in the middle and 0 at the edge, which the film shader turns into transparency. Its options: - `fromM` and `toM`, the stretch of the spline it covers, in metres along it. - `centreM` and `halfWidthM`, where it sits across the spline and how wide it is. - `liftM`, its height above the surface: about a centimetre, so it never fights the road for the depth buffer. - `color`, and a `seed` for its outline. The same seed and window give the same puddle on every device. Any mesh can be drawn as a film; the patch builder is for the common case of water lying on a road. ## Drawing a film ```ts /* The street mirrored across the road, for the puddles to show. */ const wetEnough = sky.wetness > 0.02; const mirrored = wetEnough ? renderer.beginPlanarReflection(camera, 0, heavens.horizon) : null; if (mirrored !== null) { drawWorld(mirrored); renderer.endPlanarReflection(); } drawWorld(camera); if (wetEnough) for (const puddle of puddles) renderer.drawFilm(puddle, camera, time, env, 0.16, wet); ``` `drawFilm(mesh, camera, time, env, sheen, options)` draws a film after the world, blended and without writing depth, so it lies on the surface it was built against. Its options: - `reflectionStrength`, 0 to 1, how much of the mirrored street shows. It is weighted by the viewing angle on top, as a reflection is: a puddle underfoot shows almost nothing, one down the street shows everything. It needs a planar reflection drawn this frame for the film's plane, which is the road's own height, named by `reflectionPlaneY` even though the patch is lifted a centimetre above it. A film on any other plane gets no reflection, never the wrong one. - `roughness`, 0 to 1. Zero is a mirror. A wet road is water lying in stone, which scatters what it reflects into streaks, so a little roughness makes a puddle meet the dry road around it without a hard rim. `roughnessCyclesPerMetre`, 60 by default, is how coarse that roughness is; match it to the `setSurfaceRelief` scale of the surface beside it, and the wet and the dry read as one material. The planar reflection is the one water uses; [Water](https://driftengine.dev/docs/rendering/water) describes it. Its target exists when the `water` and `waterReflections` quality options are on, as they are by default, so a street that has turned water off asks for it with `planarReflections: true`. Draw the same world into it that the frame draws, from a function both passes call. ## Sheen `sheen` is iridescence, the green-to-magenta bands of fuel on water, and **not a wetness dial**. Raising it to make a road look wetter makes it look oily. For wet tarmac at night, 0.15 to 0.18 is the range a game found by testing; the example uses 0.16. An oil slick wants much more. --- # Post-processing Rendering. https://driftengine.dev/docs/rendering/post-processing The scene target screen effects need, brightness kept above white, bloom, ambient occlusion, and multisampled and temporal antialiasing. Screen-space effects work on the finished picture, so the scene has to be drawn somewhere they can read it. This chapter covers the effects that make a frame look finished: bloom, ambient occlusion and antialiasing. The tone curve, exposure, colour grading and the camera's own effects, motion blur and depth of field, are in [Colour and motion](https://driftengine.dev/docs/rendering/colour-and-motion). (This chapter runs the `postprocess` example at https://driftengine.dev/docs/rendering/post-processing.) ## The scene target `screenEffects`, on by default, draws the scene into an off-screen target and composites it to the canvas at the end of the frame. Every effect in this chapter needs it. Off, there is no post stage at all: the scene draws straight to the canvas, nothing extra is allocated, and that is the honest low-end setting, since the target costs one write and one read of every pixel whatever runs on it. ## Brightness above white `hdrScene` keeps the scene's real brightness to the end of the frame, in half floats, and applies the tone curve once there. Without it, each surface is clipped to the range 0 to 1 as it is shaded, and a lamp at five times white and a sheet of white paper arrive at the end as the same colour. It also grades the sky, particles, films and water consistently with the world. It changes the picture slightly even where nothing is brighter than white, so it is off by default. It needs `screenEffects`, and a device that cannot render to float targets keeps the eight-bit target. ## Bloom ```ts /** * Ambient occlusion decides what the renderer allocates, so its switch builds a new renderer. * Bloom's ceiling is set once with the range it needs, and its switch moves the dial. */ const quality = (ao: string) => ({ ambientOcclusion: ao === 'on' ? 1 : 0, ambientOcclusionRadius: 0.6, hdrScene: true, bloom: 0.9, bloomThreshold: 1.2, outputTransform: 'aces' as const, directionalShadows: true, }); ``` `bloom`, 0 to 1, is how far a bright pixel spreads past its own edges: what a lamp, a star or a neon strip needs to read as overwhelming. `bloomThreshold` is how bright a pixel must be to bloom, in scene units: 1 means "brighter than white", where only sources of light sit. The threshold is subtracted, not cut, so there is no edge where a gradient crosses it. **Bloom and `hdrScene` are a pair.** Without the range, nothing in the scene is above 1 when bloom looks at it, a threshold of 1 finds nothing, and the renderer says so when it is built. The bloom is added in linear scene units and the tone curve then rolls off the sum. ```ts /** Emissive, so it is brighter than 1 in scene units and is the only thing bloom can find. */ const lampMesh = new MeshBuilder(); lampMesh.addBox([0, 0, 0], [0.35, 0.35, 0.35], [1, 0.82, 0.55], 1.6); const lamp = renderer.createMesh(lampMesh.build()); ``` The lamp is emissive, and emissive light is switched by the environment's `nightFactor`. At 0 the lamp emits nothing and bloom finds nothing above the threshold, which is easy to mistake for bloom not working; the example's dusk environment sets it to 1. `setBloom(scale, threshold)` moves both per frame. A threshold compared before exposure means a different on-screen brightness at every exposure, so a scene whose exposure moves through a day passes the threshold it wants on screen divided by the exposure. ### How bloom answers ```ts /** * A colour comes in over two units past the threshold rather than having the threshold taken off * it, and each of the six levels, finest first, is weighted by a stage's own tint. Both thresholds * are compared before exposure, so a frame exposed by `exposure` divides them by it. */ export function stageBloom(renderer: RendererApi, exposure: number): void { renderer.setBloom(1, 0.1 / exposure, { ramp: 2 / exposure, tints: [ 0.35, 0.35, 0.35, 0.14, 0.14, 0.14, 0.12, 0.12, 0.12, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.06, 0.06, 0.06, ], }); } ``` The third argument of `setBloom` is a `BloomResponse`, for a scene authored against a different bloom. `ramp`, in scene units, brings a colour in gradually from the threshold, none of it at the threshold and all of it that far past, where the default subtracts the threshold; a very low threshold with the subtraction keeps almost every light at full strength and washes the frame. `tints` weights each of the `BLOOM_LEVELS` levels, finest first, three numbers a level; white is the identity, and a tint may pass one to carry a strength. Neither costs a pass, and a frame that names no response blooms as it did. ## Ambient occlusion `ambientOcclusion`, 0 to 1, darkens where surfaces meet: a box on a floor, a wheel in its arch, the inside of a panel gap. It is most of what makes a model sit in a room instead of floating over it. It compares depth with its neighbours inside the pass that already holds depth, so it costs no extra target and no second draw of the scene. 1 is the top of the range and useful mostly to see where it lands while tuning. `ambientOcclusionRadius` is how far it looks, in metres, so a two-centimetre gap darkens the same from across the room as from close up. Match it to the gaps that matter: half a metre, the default, for a room or a vehicle, more for a landscape. `setAmbientOcclusionFade(distance, radius)` fades it out with distance: whole up to `distance` metres from the eye and gone `radius` metres past it. Far off, the depth buffer's steps are metres apart and the estimate shades them in rings across a sky dome or a mountain range; past the fade those pixels are left open and skip the work. It is held until changed and does nothing where `ambientOcclusion` is 0. A negative distance, the default, fades nothing. Occlusion is measured from the depth the opaque world leaves, and glass, smoke, water, text and lines write none, so it darkens only the part of a pixel they let through: smoke in front of a corner stays the colour of the smoke, and a pane at 0.85 opacity takes 0.15 of the darkening behind it. Light added on top, such as sparks or a glow, is darkened with the surface it lands on. A pass of your own says which of these its blending is; see [Custom passes](https://driftengine.dev/docs/rendering/custom-passes). ## Antialiasing With `screenEffects` on, the canvas's own antialiasing is turned off, because only one full-screen triangle reaches the canvas and it has no edges. Something has to replace it. ```ts /** The sample count decides how the scene target is allocated, so changing it builds a new renderer. */ const quality = (samples: string) => ({ sceneSamples: Number(samples), directionalShadows: true }); const scene = await openScene(quality(flag('samples', '1')), build); controls([ { key: 'samples', label: 'sceneSamples', value: flag('samples', '1'), options: [ { text: '1 (off)', value: '1' }, { text: '4', value: '4' }, ], change: (value) => scene.rebuild(quality(value)), }, ]); ``` - `sceneSamples` multisamples the scene target: 1 is off, 4 is usual. It works on geometry edges and leaves texture detail alone, and costs memory bandwidth in proportion to the samples. - `temporalAa` antialiases across frames: the projection moves a fraction of a pixel each frame and the result blends into where the last frame was. It costs one texture and one pass, against multisampling's multiplied fill rate. It is exact for a still world under a moving camera. An object that moves is followed where its draws name a `Mover` (see the DriftTR chapter) or last frame's model matrix, and a mesh rewritten with `updateMesh` or a point skin is followed without one: on WebGL2 those are drawn again into a motion target at the end of the frame, so their pixels are read from where they stood, and an object that names none is rejected from the history where its colour gives it away, which leaves a faint trail where it crosses something close to its own colour. Instanced batches and cloth keep the camera's motion on WebGL2, and so does a multisampled frame, each said once. WebGPU follows movers through DriftTR. Both are off by default. The example's posts lean a few degrees off vertical, which is where missing antialiasing shows most. **Call `renderer.cameraCut()` before the first frame of a new shot.** Everything temporal reads the previous frame through the previous view, and a cut looks to the renderer exactly like a very fast camera: without the call, the first frame after a respawn or a seek blends in a picture of somewhere else. ## Transparency in any order `orderIndependent` replaces sorted blending of translucent draws with weighted blending, whose sum does not depend on order: two panes that intersect stop fighting. It costs two targets and a second draw of the translucent geometry. See [Translucent and additive meshes](https://driftengine.dev/docs/rendering/translucency). ## What it costs Every option here is a quality option, fixed when the renderer is built, because each one decides what is allocated or which shader is compiled. Changing one means a new renderer: the example's ambient occlusion switch builds one in place, and the lamp carries on circling. Bloom shows the other way to switch: its ceiling is set once with the range it needs, and `setBloom` moves the dial in the running frame. The exposure, grade and camera dials are in [Colour and motion](https://driftengine.dev/docs/rendering/colour-and-motion). --- # Colour and motion Rendering. https://driftengine.dev/docs/rendering/colour-and-motion The tone curve, exposure and an eye that adapts, colour grading with a lookup table, vignette, grain and fades, depth of field and motion blur. The last things done to a frame decide how it looks more than most of what came before: how light values become screen values, how the eye adapts, what colour the whole picture leans, and what a camera does to it, focus and blur. The example puts all of them on one colonnade at dusk, with its lens written in DriftScript; every switch under it changes the running frame. (This chapter runs the `look` example at https://driftengine.dev/docs/rendering/colour-and-motion.) ## Ceilings and dials ```ts /** The ceilings: what each effect may cost. The per-frame dials below say how much of it to use. */ const stage = await openStage({ outputTransform: 'aces', hdrScene: true, bloom: 0.35, bloomThreshold: 1.1, depthOfField: 0.02, cameraMotionBlur: 1, sceneSamples: 4, }); ``` Most of these effects come in two halves. A quality option, fixed when the renderer is built, says whether the effect exists and how much it may cost: `depthOfField` is how far a defocused point may spread, `cameraMotionBlur` how much blur is possible. A setter, called per frame, says how much of that the frame wants. A device that cannot afford an effect caps it in one place, and a game turns it up and down without rebuilding anything. ```ts /** Each switch changes the running frame: a dial the lens reads, or a grade set once. */ controls([ { key: 'grade', label: 'grade', value: flag('grade', 'warm'), options: ['none', 'warm', 'cool'].map((g) => ({ text: g, value: g })), change: (value) => applyGrade(value), }, { key: 'focus', label: 'focus', value: flag('focus', 'on'), options: onOff, change: (value) => { lensState.focusing = value === 'on' ? 1 : 0; }, }, { key: 'blur', label: 'motion blur', value: flag('blur', 'on'), options: onOff, change: (value) => { lensState.blurring = value === 'on' ? 1 : 0; }, }, ]); lensState.focusing = flag('focus', 'on') === 'on' ? 1 : 0; lensState.blurring = flag('blur', 'on') === 'on' ? 1 : 0; ``` That is why the example's switches need no new renderer: the ceilings are set once, and a switch writes the share of them the lens takes. ## The lens, in DriftScript ```drs fn present(lens: mut Lens, renderer: Renderer, turnRate: f32, dt: f32) { render.exposure(renderer, 1.2) // Focused on the figure 21 metres down the floor, with three metres sharp. render.focus(renderer, 21, 3, lens.focusing) // Blur only while the camera turns fast, in full at three radians a second: always on, it is a // filter nobody reads as speed. render.motionBlur(renderer, math.clamp(turnRate / 3, 0, 1) * lens.blurring) if lens.fade > 0 { lens.fade = math.max(lens.fade - dt, 0) render.veil(renderer, 0, 0, 0, lens.fade / 2) } } ``` The lens is a DriftScript module. `drift/render` gives a script the per-frame dials, `exposure`, `focus`, `motionBlur`, `speedBlur`, `bloom`, `bloomAbove`, `medium` and `veil`, and none of the quality ceilings, so a script decides how the frame looks within what the device was allowed. It takes the renderer as an argument; the page calls `present` once a frame. ```ts /** * Load a compiled `.drs` module and bind it. Most of the modules the examples import need no host; * `drift/navigation` needs the graph it routes over, which is what `services` is for. */ export function hostScript(compiled: unknown, services: HostServices = {}): DriftModule { const module = loadModule(compiled as Record); const bound = bindModule(module, services); if (!bound.bound) throw new Error(bound.reason); return module; } /** One of the module's exports, by name: a function, or the factory a `data` declaration makes. */ export function exported(module: DriftModule, name: string): T { const value = module.exports[name]; if (value === undefined) throw new Error(`the script exports no ${name}`); return value as T; } ``` ```ts /** The lens, hosted: its record lives here, so a patched module carries on from it. */ const lens = hostScript(lensScript); interface Lens { focusing: number; blurring: number; } const lensState = exported<() => Lens>(lens, 'createLens')(); type Present = (lens: Lens, renderer: RendererApi, turnRate: number, dt: number) => void; if (import.meta.hot) { import.meta.hot.accept('./lens.drs', (next) => { if (next !== undefined) patchModule(lens, next as Record, { Lens: [lensState] }); }); } ``` The page loads the compiled module, binds the engine capabilities it imports, and holds the `Lens` record itself. When the dev server delivers an edited `lens.drs`, `patchModule` swaps the functions and keeps the record, so the focus and the fade carry on from where they were with the new code running. Open the example under `npm run examples`, change the focus distance in `present`, and save. The grade, the eye's adaptation, the vignette and the grain are not bound for scripts, so the example sets them in TypeScript. ## The tone curve `outputTransform` turns scene light into screen colour. - `'srgb'`, the default, applies the display's transfer curve without a tone curve, so a channel above 1 clips on its own. - `'none'` writes values as they are computed. It reads as dark and muddy unless every colour in the world was chosen under it, and it was the default until 4.13.0. - `'aces'` rolls highlights off smoothly before that, so bright light keeps its colour. It is the usual choice, and it is what exposure, grading and the eye below need. - `'shoulder'` keeps sRGB's midtones exactly and eases only the highlights. Past 0.8, the brightest channel rolls toward 1 and the other two are scaled with it, so an overbright red spark stays red where `'srgb'` would clip each channel and turn its core pink. It has none of ACES's toe or desaturation. Use it to match a renderer that grades this way, or when the midtones must stay as authored. - `'filmic'` is a film curve shaped by five numbers, and it holds mid grey where it is: 0.18 of scene light comes out at 0.18, where `'aces'` gives about 0.11. A straight segment through mid grey meets a soft toe below and a shoulder above, in the ACEScg working space, with the ACES reference's glow and red modifier around it. Its numbers are held until changed, by `renderer.setFilmicCurve({ slope, toe, shoulder, blackClip, whiteClip })`; a renderer starts with `DEFAULT_FILMIC_CURVE`, which is slope 0.88, toe 0.55, shoulder 0.26 and the clips 0 and 0.04. A longer `toe` lifts the shadows, a larger `shoulder` rolls the highlights off sooner, and the two clips let black crush and white clip. A grading tool's look is matched by passing its numbers rather than by baking the difference into a colour grade, whose lattice has the fewest steps exactly where two curves differ most, in the shadows. It is applied by the composite alone, so it needs `screenEffects` and `hdrScene`; without them every pass grades with `'aces'`, and the renderer says so once. **If a scene looks dark and flat, try `'aces'` with an `outputExposure` before touching a light.** The default stays `'none'` only so no existing game changes. With `screenEffects` on, the curve is applied once at the end of the frame; without it, each pass applies it itself. ## High dynamic range displays `highDynamicRange: true` asks for a canvas whose highlights run past paper white, as far as the display can show. It is had only where three things hold: the renderer is on WebGPU, the frame keeps its light past white (`screenEffects` and `hdrScene`), and the display reports a high dynamic range. `renderer.displayRange` says which range the frame goes out in, `'high'` or `'standard'`, and `renderer.displayRangeReason` says why, so a game can choose a look graded for the output it got. WebGL2 always answers `'standard'`: it draws into an eight-bit canvas. On a high range, tell it the display's paper white and peak, as `renderer.setDisplayLuminance(203, 1000)` does for a display whose white is 203 nits and whose peak is a thousand. `setDisplayLuminance(paperWhite, peak)` takes the two in any one unit; their ratio is how far above white the highlights may reach. Paper white stays where it was, and so does everything below it: under `'filmic'` the shoulder rolls off toward the display's peak instead of toward white, with the toe and mid grey unchanged, and a colour grade colours a highlight without clipping it back to white. On a standard display it changes nothing. A host without a browser display query answers it with `createRenderer`'s `highDynamicRangeDisplay` option. ## Exposure and the eye ```ts /* The lens: exposure, focus on the figure, blur while turning, and the fade in. */ exported(lens, 'present')(lensState, renderer, turnRate, dt); /* What a script does not reach: the eye's adaptation, the vignette and the grain. */ renderer.setAutoExposure(0.6, dt); renderer.setVignette(0.35); renderer.setFilmGrain(0.025, Math.floor(time * 60)); ``` `setOutputExposure(exposure)` scales scene light before the tone curve, per frame; a script sets the same dial with `render.exposure`, as the lens does. The engine does not decide when it should change: a game knows it walked into a cave, and the renderer could only find out a frame late. Easing toward a target with `easeExposure` is two lines; see [Sky and atmosphere](https://driftengine.dev/docs/rendering/sky-and-atmosphere). `setAutoExposure(strength, dt)` is the eye adapting to what the frame actually shows. The finished scene is metered on the GPU each frame, a held brightness moves toward it, about 78% of the way in a second, and the frame is scaled toward middle grey by `strength` of the stops between, at most six either way. `setOutputExposure` becomes a bias on top, so night can stay darker than day. The time is yours, so a held capture passes 0 and holds. Every pixel counts the same; there is no spot metering. `setLocalExposure(strength)` brings each region of the frame toward the frame's own brightness, at most three stops. A sunlit courtyard holds fifty times the light on its paving that it holds under its arcades, and one exposure leaves one of the two black or white; this lifts the shade as shade. About 0.5 is a photograph's latitude. `setLocalExposure` also takes a shape, `{ highlightContrast, shadowContrast, detail, blurredBlend, middleGreyBias, range }`, which turns each region about middle grey at the frame's exposure rather than about the frame's metered brightness. A region keeps `highlightContrast` of its stops from grey where it is brighter and `shadowContrast` where it is darker, so 1 leaves it as it is and 0 brings it all the way to grey; each pixel keeps `detail` of its own stops from its region, so above 1 sharpens the texture a curve would flatten. `blurredBlend`, 0.4 by default, leans a region's level from its own band of brightness toward its tile's average, `middleGreyBias` adds stops to grey, and `range`, 8 by default, is the furthest a region moves. A night metered far below grey is pulled toward grey by this form, which is what it is for; one held dark keeps the single number. Both need `screenEffects` and `hdrScene`, and say so once on the console when they lack them. ## Colour grading ```ts /** * A grade is a lookup table over display colours. Start from the identity and bend it: here every * colour leans warmer or cooler, the highlights more than the shadows. */ function gradeLut(look: 'warm' | 'cool'): ColourGradeLut { const lut = identityGradeLut(17); const warm = look === 'warm' ? 1 : -1; for (let i = 0; i < lut.data.length; i += 4) { const r = lut.data[i] / 255; const g = lut.data[i + 1] / 255; const b = lut.data[i + 2] / 255; const light = (r + g + b) / 3; const tilt = (0.3 + light) * 0.07 * warm; lut.data[i] = Math.round(Math.min(1, Math.max(0, r + tilt)) * 255); lut.data[i + 1] = Math.round(Math.min(1, Math.max(0, g + tilt * 0.3)) * 255); lut.data[i + 2] = Math.round(Math.min(1, Math.max(0, b - tilt)) * 255); } return lut; } const grades = { warm: gradeLut('warm'), cool: gradeLut('cool') }; function applyGrade(name: string): void { renderer.setColourGrade(name === 'warm' ? grades.warm : name === 'cool' ? grades.cool : null); } applyGrade(flag('grade', 'warm')); ``` `setColourGrade(lut, strength)` applies a lookup table over display colours after the tone curve: the look of the whole picture, a warm evening or a cold morning. A `ColourGradeLut` is a cube of `size` points per axis, as eight-bit RGBA, red fastest and blue slowest; 32 and 33 are what grading tools export, and 64 is the most. `identityGradeLut(size)` is a table that changes nothing, which is where a grade built in code starts. The grade is held until set again, and uploaded only when the table changes, so calling it every frame is free. `null` removes it. It needs `screenEffects`. ## Vignette, grain and fades - `setVignette(strength)` darkens the corners as a lens does, before the tone curve: 0.5 is about 1.2 stops at the corner. - `setChromaticAberration(intensity, start)` parts the colours toward the frame's edges as a simple lens does: red and green land nearer the centre than blue, by their wavelengths' distance from it. `intensity` is a percentage, from 0 for none; `start` is how far out the fringe begins, as a share of the half-frame, 0 at the centre. Under heavy motion blur or depth of field the fringe softens with the blur. - `setFilmGrain(strength, seed)` adds grain in display values, after the grade; 0.03 is fine grain. The seed is yours: a new one each frame for grain that moves, the same one for a still that is identical run to run. - `setFrameVeil(r, g, b, alpha)` lays a colour over the finished frame for fades and dips: `(0, 0, 0, 1)` is exact black and `(1, 1, 1, 1)` exact white. It sits after the tone curve and before grain and vignette, so a dip takes the whole image down together, and bloom never sees it. **It is cleared with every frame**: call it each frame of a transition, and one that forgets to stop cannot leave the screen black. In a script it is `render.veil`, which the lens fades in with. ## Depth of field `setDepthOfField(distance, range, scale)` focuses the lens: `distance` to the subject in metres, `range` the depth that stays sharp, and `scale` how much of the `depthOfField` ceiling to use, so 0 turns it off for a moment for free; the lens's `render.focus` is the same call, with the focus switch as its `scale`. Racking focus is yours, for the same reason exposure is: the game knows what the camera is looking at. A ceiling of 0.02 is a strong defocus, two per cent of the frame's height. It costs eight taps on the pixels out of focus and one comparison elsewhere. ## Motion blur `setCameraMotionBlur(scale, maxShare)`, or `render.motionBlur` in a script, scales the `cameraMotionBlur` ceiling for this frame; `maxShare` is the longest smear, as a share of the frame, 0.03 unless given. The blur comes from the camera's movement between frames, so it smears a whip pan or a fast flight and leaves a still frame untouched. **Ramp it with speed**, as the example does from the camera's turn rate: blur that is always on stops reading as speed within seconds and becomes a filter. It costs eight taps on moving pixels. **Under DriftTR each drawn object is blurred by its own motion**: a draw that names where it was last frame (a `Mover`, as the reconstruction asks for anyway) smears along its own path, so a kick or a thrown body blurs while a still stage behind it stays sharp. Without a reconstruction, and on WebGL2, the camera's motion alone blurs the frame, and the renderer says so once when a draw names its previous placement. `setSpeedRush(strength)`, `render.speedBlur` in a script, is a second speed cue, applied to the finished image, for the moments a game wants to say "fast". Both are held until changed. Call `renderer.cameraCut()` on the frame a shot changes, or the first frame of the new shot is blurred along the jump from the old one. --- # DriftTR Rendering. https://driftengine.dev/docs/rendering/drifttr Draw the scene at a fraction of the output size and rebuild the full picture from this frame and the ones before it, on WebGPU. Most of a frame's cost is shading pixels. DriftTR, the engine's temporal reconstruction, shades fewer: the scene is drawn smaller, jittered a fraction of a pixel differently each frame, and a compute pass rebuilds the full-size picture from this frame and the history of the ones before. At a ratio of 1.5 the scene draws 44% of the output's pixels and saves the rest of the fragment work; a measured scene went from 3.1 milliseconds of GPU time to 2.45. (This chapter runs the `drifttr` example at https://driftengine.dev/docs/rendering/drifttr.) ## Turning it on ```ts /** * How many output pixels each drawn pixel stands for, on each axis; 0 is off. It decides how every * target is sized, so the switch builds a new renderer in place. */ const quality = (ratio: string) => (backend: string) => ({ reconstruction: backend === 'webgpu' ? Number(ratio) : 0, outputTransform: 'aces' as const, directionalShadows: true, }); const scene = await openScene(quality(flag('ratio', '1.5')), build); ``` `reconstruction` is how many output pixels each drawn pixel stands for, on each axis, from 1.3 to 2. 0, the default, is off and draws exactly what the renderer draws without it, as does a negative number. A positive value outside the range is clamped to its nearer end: below 1.3 the saving is eaten by the reconstruction's own cost, and above 2 no reconstruction holds an edge. It needs WebGPU, since the reconstruction is a compute pass; on WebGL2 the scene draws at full size, which is why the example asks only WebGPU for it. The example's readout shows what was drawn against what is shown. `renderer.sceneWidth` and `sceneHeight` are the drawn size; a custom pass that sizes its own targets must read them, not the canvas, or it draws a corner of the world into a target the size of the scene. ## What it needs from your draws The reconstruction finds where every pixel was last frame. For the still world and a moving camera, the depth says so. For something that moved, the draw has to say: ```ts /** One identity per moving object, passed with every draw of it, so its motion can be followed. */ const blockMover = createMover(); ``` ```ts renderer.drawMesh(block, blockNode.worldMatrix, 0, null, blockMover); ``` `createMover()` makes an identity for one moving object; pass it with every draw of that object, and the renderer keeps last frame's model matrix and, for a skinned draw, last frame's pose. A mover drawn twice in one frame is two objects wearing one identity, and the renderer warns once. Passing last frame's model matrix in the same place works too. Some draws need nothing: - **Instanced batches** and meshes rewritten with `updateMesh` are their own identity. - **Blended draws** (translucent meshes, particles, plumes, films, bolts, lines and text in the world) are drawn after the reconstruction, at the output size. - **Light volumes** are marched inside the reconstructed picture and keep their own history. **And call `renderer.cameraCut()` at every cut.** Nothing detects one: without it, the first frames of a new shot blend in the last one. ## What it gives back, and what it does not The history is read where each surface was, kept within the colour range of its neighbourhood, and refused where depth, motion or normals say it is another surface, so a moving object leaves no ghost. What it cannot give back is the resolution it did not draw: an edge that never moves is softer than in a full-size frame at any ratio. Measured against a native frame with four samples, still edges err by about 8 levels at 1.5, where a native frame with one sample errs by 3. A multisampled frame is not reconstructed, and the renderer says so once: choose one or the other. A custom pass is handed the frame's jitter on its contexts, `ctx.jitter`, to apply with `jitterClip`; see [Custom passes](https://driftengine.dev/docs/rendering/custom-passes). Deterministic replays are unaffected: the same replay fingerprints the same with reconstruction on at any ratio as with it off. --- # The GPU-driven pipeline Rendering. https://driftengine.dev/docs/rendering/gpu-driven A second pipeline for very large scenes on WebGPU: the device culls, picks detail and draws clusters, and shades once per material. The forward renderer draws what you tell it to, one call at a time, and a frame of ten thousand objects is ten thousand calls. The GPU-driven pipeline moves those decisions onto the device. Each frame the GPU culls every object against the view, chooses the level of detail each one has earned, culls the surviving clusters of triangles against a depth pyramid built that frame, compacts what is left into one indirect draw into a visibility buffer, and shades it with one dispatch per material. The CPU uploads the scene once and, each frame, says where the camera is. The example draws 2,500 rocks, each its own mesh. (This chapter runs the `gpu-driven` example at https://driftengine.dev/docs/rendering/gpu-driven.) It needs indirect draws and compute, so it runs on WebGPU only. ## Asking for it ```ts /** The pipeline is a renderer option, and asking for it where it cannot run throws. */ const stage = await openStage( { outputTransform: 'aces', hdrScene: true, directionalShadows: false }, { pipeline: 'gpu-driven' }, ).catch((error: unknown) => { const readout = document.querySelector('#backend'); if (readout !== null) readout.textContent = 'This example needs WebGPU, and this page has none.'; console.info(error); return null; }); ``` `pipeline: 'gpu-driven'` among `createRenderer`'s options is the permission, and **asking for it where it cannot run throws**, with the reason. It does not fall back, because a silent fallback ships a game a pipeline it does not have, and the difference would only show as a frame time on somebody else's machine. The example catches the refusal and says so on the page. The pass writes linear light for the end of the frame to grade, so a profile with a tone curve also needs `hdrScene`; without it the pass warns that the picture will be flat. ## What it draws Its material is a subset of the forward path's: vertex colour, one directional light with its highlight and its shadow, the hemispheric ambient, reflections from a probe, metalness, roughness, an emissive add, DriftTexture materials decoded on the device, alpha-tested cutouts, blended and glass surfaces. A scene holds at most 64 materials. `setMaterial`, surface grain and relief, point lights and skinning do not reach it. **Read that list before reaching for it**: it is a pipeline for a lot of static geometry, a city, a forest, a voxel world, and the forward path draws the rest. ## Clusters ```ts /** A mesh, split into clusters of about 128 triangles: the unit the device culls and draws. */ function clustered(mesh: MeshData, material: number): GpuDrivenMesh { const set = buildClusters(mesh, 128); return { positions: mesh.positions, normals: mesh.normals, colours: mesh.colors, clusters: { count: set.count, triangleOffsets: set.triangleOffsets, triangleCounts: set.triangleCounts, boundsCentre: set.boundsCentre, boundsRadius: set.boundsRadius, coneAxis: set.coneAxis, coneCutoff: set.coneCutoff, /* One level of detail: every cluster is its own finest and coarsest. */ ownError: new Float32Array(set.count), parentError: new Float32Array(set.count).fill(Infinity), indices: set.indices, }, material, }; } ``` The unit the device culls and draws is a cluster of about 128 triangles. `buildClusters(mesh, 128)` from `@driftengine/assets` splits a mesh into them, each with a bounding sphere and a cone of normals, so a cluster facing away or hidden behind nearer geometry is skipped without being drawn. `ownError` and `parentError` drive the level of detail. With one level, as here, every cluster is its own finest and coarsest. `buildClusterDag(set, mesh)` builds a graph of simplified levels, and the device then draws, for each part of a mesh, the coarsest level whose error projects to less than `lodThreshold` pixels. Clustering is build work: a million triangles take about 650 milliseconds. The `.drft` format stores a mesh's clusters and their level graph as an `MSHL` chunk. ## The scene ```ts /** Every rock a mesh of its own, placed by a transform; the ground is material 1. */ const random = mulberry32(11); const meshes: GpuDrivenMesh[] = []; const ROCKS = 2500; for (let i = 0; i < ROCKS; i += 1) { const shade = 0.4 + random() * 0.25; const rock = new MeshBuilder().addBlob( [0, 0.3, 0], (u, v) => 0.5 + hashToUnit(i * 977 + Math.floor(u * 7) * 31 + Math.floor(v * 5)) * 0.2, [shade, shade * 0.97, shade * 0.92], ); meshes.push(clustered(rock.build(), 0)); } meshes.push( clustered(new MeshBuilder().addBox([0, -0.1, 0], [80, 0.1, 80], [0.3, 0.34, 0.26]).build(), 1), ); const transforms = new Float32Array(meshes.length * 16); for (let i = 0; i < meshes.length; i += 1) { const s = i < ROCKS ? 0.4 + random() * 1.4 : 1; const x = i < ROCKS ? (random() - 0.5) * 150 : 0; const z = i < ROCKS ? (random() - 0.5) * 150 : 0; transforms.set([s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, x, 0, z, 1], i * 16); } const scene = streamingScene(meshes, transforms); const materials: GpuDrivenMaterial[] = [ { tint: [1, 1, 1], emissive: 0, roughness: 0.8 }, { tint: [1, 1, 1], emissive: 0, roughness: 0.95 }, ]; ``` `streamingScene(meshes, transforms)` packs a scene that is filled once: every mesh with its clusters, a material index each, and one transform each. A world that changes while it runs, chunks streaming in as a player walks or remeshed as they dig, builds a `StreamingScene` with a capacity of vertices, indices, clusters and meshes, then calls `add(mesh, transform, material)` and `remove(handle)` from the frame loop. `add` allocates only when a mesh larger than any before it arrives. The vertex buffer is bound as one storage binding, so a capacity has to fit the device's `maxStorageBufferBindingSize`: `vertices × VERTEX_FLOATS × 4` bytes. ## The pass ```ts /** The pipeline is a pass like any other: registered once, drawn where the frame says. */ const pass = new GpuDrivenPass(scene, materials); const handle = renderer.registerPass(pass); ``` `GpuDrivenPass` is a pass like any other: registered once, drawn where the frame calls `drawPass`. A third argument configures its own shadow map: `mapSize`, `maxDistance`, `maxSlope` and `taps`, as the forward path's shadow options are. ```ts /** What the pass needs of the camera and the light, refreshed in place every frame. */ const view: GpuDrivenView = { viewProj: camera.viewProjection, eye, lightDir: env.directionalDir, lightColour: env.directionalColor, ambient: env.ambient, ambientGround: env.ambientGround ?? env.ambient, lodThreshold: 1.5, fovY: (55 * Math.PI) / 180, }; ``` The view is the camera's view-projection and position, the light, and `lodThreshold` with the field of view the level-of-detail choice projects errors with. Pass `fog` from `atmosphereFog(env, eyeY, underwater)` to fog the pipeline exactly as the forward path fogs, and `emissiveGain` and `nightFactor` from the same environment so both pipelines glow alike. ```ts /* Before the frame opens: the pass records its culling and drawing against this view. */ pass.resize(renderer.sceneWidth, renderer.sceneHeight); pass.setView(view); renderer.beginFrame(CLEAR); renderer.bindMeshPass(camera, env); renderer.drawPass(handle); renderer.endFrame(); ``` `resize` and `setView` come before `beginFrame`, because that is when the pass records its culling. Size it from `renderer.sceneWidth` and `sceneHeight`, not the canvas: with DriftTR the scene is smaller than the canvas. ## With the forward path Both pipelines can draw in one frame: GPU-driven terrain with forward characters, particles and interface on it. `presentDepth: true` in the shadow options hands the frame the pass's depth as well as its colour, so a forward mesh can stand behind GPU-driven geometry; without it the two have no depth relationship. It costs one more texture read and a depth write over the pixels the pass covered. `pass.totalMs` is what the pipeline cost the device last frame, and `stageTime(stage)` each stage, where the device can time itself; both are `null` otherwise. --- # Particles Rendering. https://driftengine.dev/docs/rendering/particles Sparks, smoke and motes from a pool and a batch, deterministic emission, textured sprites and flipbooks, particles placed by your own plan, and birds. A particle effect is two things: a pool that simulates the particles, where each one is, how old and how big, and a batch that draws them with a particle material. The example's fire uses three pairs, one each for sparks, smoke and motes. (This chapter runs the `particles` example at https://driftengine.dev/docs/rendering/particles.) ## The pool ```ts /** Each pool is the simulation: where its particles are, how old, how big and what colour. */ const sparks = new ParticlePool({ capacity: 600, lifeSec: 1.4, sizeStart: 0.05, sizeEnd: 0.01, colorStart: [4, 2.2, 0.8], colorEnd: [1.4, 0.3, 0.05], gravity: 4, drag: 0.6, rise: 0, }); const smoke = new ParticlePool({ capacity: 300, lifeSec: 6, sizeStart: 0.5, sizeEnd: 2.4, colorStart: [0.18, 0.17, 0.17], colorEnd: [0.3, 0.3, 0.32], gravity: 0, drag: 0.4, rise: 0.7, alphaStart: 0.3, alphaEnd: 0, }); const motes = new ParticlePool({ capacity: 200, lifeSec: 8, sizeStart: 0.04, sizeEnd: 0.04, colorStart: [1.6, 1.4, 0.8], colorEnd: [0.6, 0.5, 0.3], gravity: 0, drag: 0.2, rise: 0.05, alphaStart: 1, alphaEnd: 0, }); ``` A `ParticlePool` holds up to `capacity` particles. Each lives `lifeSec` seconds and moves from its start size, colour and opacity to its end ones over that life. A size is a half-width, metres from the centre to an edge, so a particle of size 0.5 is a metre across. `gravity` pulls it down, `drag` slows it per second, and `rise` pushes it up steadily, which is what makes smoke behave like smoke. Leave `alphaStart` and `alphaEnd` out and a particle stays opaque and fades by colour, which suits additive sparks; give them, and it fades for real, which smoke needs. Colours are linear and may go past one: a spark at four times white is what bloom finds. ## Emitting ```ts simulate(dt) { tick += 1; time += dt; /* A few sparks every tick, a puff of smoke every other one, and a mote now and then. */ for (let i = 0; i < 4; i += 1) { const seed = tick * 8 + i; const a = hashToUnit(seed) * Math.PI * 2; const out = hashToUnit(seed + 1) * 1.2; sparks.emit( 0, 0.3, 0, Math.cos(a) * out, 2.5 + hashToUnit(seed + 2) * 3, Math.sin(a) * out, seed, ); } if (tick % 2 === 0) { const seed = tick; smoke.emit( (hashToUnit(seed) - 0.5) * 0.4, 0.6, (hashToUnit(seed + 5) - 0.5) * 0.4, 0.15, 0.6, 0, seed, ); } if (tick % 12 === 0) { const seed = tick; const a = hashToUnit(seed) * Math.PI * 2; const r = 1.5 + hashToUnit(seed + 3) * 3; motes.emit( Math.cos(a) * r, 0.3 + hashToUnit(seed + 4) * 2, Math.sin(a) * r, 0, 0.05, 0, seed, ); } sparks.update(dt); smoke.update(dt); motes.update(dt); }, ``` `emit(x, y, z, vx, vy, vz, seed, sizeScale, lifeScale)` adds a particle with a position and a velocity. The seed drives its variation, its spin and the noise its material animates by, in place of `Math.random`, so emitting from the fixed step with the tick as the seed makes the same fire every run, which a replay needs. When the pool is full, the oldest particle is reused. `update(dt)` advances every particle and rebuilds the data the batch draws. Call it from the simulation step, as here, or from the render step for an effect that is pure decoration. ## Drawing ```ts /** Each batch is how its pool is drawn: which material, how it blends, which way it faces. */ const sparkBatch = renderer.createParticles(600, { material: 'spark', blend: 'additive', stretchSec: 0.05, coreGain: 2, }); const smokeBatch = renderer.createParticles(300, { material: 'smoke', blend: 'alpha', erosion: 0.6, }); const moteBatch = renderer.createParticles(200, { material: 'mote', blend: 'additive' }); ``` `createParticles(capacity, options)` makes a batch, and its `material` names how a particle looks: - `'spark'`: a hot point stretched along its velocity by `stretchSec` seconds of travel, with `coreGain` saying how far past white its core may go. A spark is a streak, because it moved while the eye was looking. - `'smoke'`: a soft puff eroded by noise, `erosion` from 0 to 1. - `'mote'`: an unlit point exactly its own colour. It ignores fog unless `fog: true`. `blend` is `'additive'` for what emits light and `'alpha'` for what covers it. `facing` is `'camera'`, the default, for one quad facing the viewer, `'cross'` for two blades fixed in the world, or `'velocity'` for a quad facing the viewer with its length along the particle's travel. `cameraOffset` moves every particle that many metres toward the eye, so a spark born inside a body is drawn in front of it. Several batches of one material can share its compiled program with `reuse`, so four kinds of smoke cost one shader. ```ts /* After the opaque scene: what covers first, then what adds light. */ renderer.drawParticles(smokeBatch, smoke.particles, camera, env, time); renderer.drawParticles(sparkBatch, sparks.particles, camera, env, time); renderer.drawParticles(moteBatch, motes.particles, camera, env, time); ``` `drawParticles(batch, pool.particles, camera, env, time)` draws a pool after the opaque scene. Draw what covers before what adds light. Sparks and smoke are fogged with the rest of the world. ## Sprites ```ts /** * Smoke from a flipbook: an image of four by four cells, blended back to front, softened where it * meets the ground and faded as it reaches the eye. */ export function smokeSprites( renderer: RendererApi, flipbook: SurfaceTextureHandle, ): ParticleHandle { return renderer.createParticles(300, { material: 'sprite', blend: 'alpha', texture: flipbook, cells: [4, 4], blendCells: true, softDepth: 0.2, cameraFade: 1.5, sort: true, }); } /** After the pool's update: each particle's cell from its age, the sixteen cells over its life. */ export function stepFlipbook(particles: ParticleInstances): void { const frames = particles.frames; if (frames === undefined) return; for (let i = 0; i < particles.count; i += 1) frames[i] = (particles.ages[i] ?? 0) * 15.999; } ``` The `'sprite'` material draws an image, unlit, multiplied by each particle's colour and opacity. `texture` is a surface texture of your own, and `cells` divides it into a flipbook of columns and rows, counted across then down from the top-left; each particle's `frames` value names its cell, and with `blendCells` its fraction blends toward the next. A pool leaves `frames` at zero, so step it yourself after `update`, as above. `heights` gives a card a half-height of its own beside its size, for one that is not square. Three options keep a flat card from looking like one. `softDepth` fades a sprite over that many metres where it meets the opaque scene, instead of cutting a hard line through the floor; it reads the frame's depth, which needs `screenEffects`. `cameraFade` fades it out over that many metres in front of the eye, so a puff the camera walks through does not fill the screen. And `sort` draws a blended batch farthest first, the order an alpha blend assumes; additive light needs no order. ## Particles from your own plan ```ts /** * A ring of embers placed by a plan, not simulated: positions are a function of time, so a clip * exported frame by frame draws exactly what the preview drew. */ export function drawRing( renderer: RendererApi, batch: ParticleHandle, data: ParticleInstances, camera: Camera, env: Environment, time: number, ): void { const count = data.positions.length / 3; for (let i = 0; i < count; i += 1) { const a = (i / count) * Math.PI * 2 + time * 0.5; const at = i * 3; data.positions[at] = Math.cos(a) * 3; data.positions[at + 1] = 1 + Math.sin(time + i) * 0.2; data.positions[at + 2] = Math.sin(a) * 3; data.velocities[at] = -Math.sin(a); data.velocities[at + 1] = 0; data.velocities[at + 2] = Math.cos(a); data.colors[at] = 3; data.colors[at + 1] = 1.4; data.colors[at + 2] = 0.4; data.sizes[i] = 0.05; data.alphas[i] = 1; } data.count = count; renderer.drawParticles(batch, data, camera, env, time); } ``` A pool is a simulation, and some effects are not: a ring of embers orbiting a mage, streamers around a star, anything whose position is a function of time. Fill a `ParticleInstances` yourself, its positions, velocities, sizes, colours and opacities, set `count`, and draw it. Nothing integrates the velocity; it is only the direction a spark is stretched along. Because nothing is simulated, the same time draws the same frame however the frames were spaced, which is what an exported clip needs. ## Particles a compute shader writes ```ts /** `GPUBufferUsage.STORAGE | VERTEX`, as values: the globals exist only in a browser. */ const STORAGE_VERTEX = 0x0080 | 0x0020; /** A buffer a compute shader fills with `capacity` particles and a pool then draws. WebGPU only. */ export function particleBuffer(device: GPUDevice, capacity: number): DeviceParticles { const buffer = device.createBuffer({ size: capacity * DEVICE_PARTICLE_FLOATS * 4, usage: STORAGE_VERTEX, }); return { buffer, count: capacity }; } /** Each frame: step the simulation on the device, then draw what it wrote, where it lies. */ export function drawSimulated( renderer: RendererApi, simulate: ComputeHandle, batch: ParticleHandle, particles: DeviceParticles, camera: Camera, env: Environment, time: number, ): void { renderer.dispatchCompute(simulate); renderer.drawDeviceParticles(batch, particles, camera, env, time); } ``` On WebGPU a simulation can run entirely on the device: a compute shader of your own, registered with `registerCompute` (see [Custom passes and compute](https://driftengine.dev/docs/rendering/custom-passes)), writes its particles into a buffer of yours, and `drawDeviceParticles` draws a pool's material from that buffer where it lies, with nothing read back. Each particle is `DEVICE_PARTICLE_FLOATS` (16) floats: position, half-width, roll, colour, opacity, age, seed, velocity, a sprite's frame and its half-height, the streams of a `ParticleInstances` interleaved in that order. The buffer needs `VERTEX` usage beside `STORAGE`. A slot whose half-width is 0 draws nothing, so a fixed-size buffer can hold fewer live particles than it has room for. The particles are drawn as written and not sorted; an alpha-blended set that must be drawn far to near sorts itself. WebGL2 has no compute stage: there it says so once and draws nothing, so check `computeSupported` and fall back to a pool. ## Birds ```ts /** Birds circling a point, every one's path a function of its index and the clock. */ export function birds(renderer: RendererApi): (camera: Camera, time: number) => void { const flock = renderer.createFlock(40); const circling: FlockParams = { center: [0, 0, 0], radius: 30, height: 25, count: 40, speed: 9, scale: 0.4, }; const dark: Vec3 = [0.1, 0.1, 0.12]; return (camera, time) => renderer.drawFlock(flock, camera, time, circling, dark); } ``` `createFlock(count)` and `drawFlock(flock, camera, time, params, tint, windX, windZ)` draw birds circling a centre at a radius and height, flapping as they go. Each bird's path is a function of its index and the clock, so a flock costs no simulation. `scale` is half the wingspan in metres. Other effects with chapters of their own: plumes of fire and smoke in [Light in the air](https://driftengine.dev/docs/rendering/light-in-the-air), rain and lightning in [Fog and weather](https://driftengine.dev/docs/rendering/fog-and-weather). --- # Text and overlays Rendering. https://driftengine.dev/docs/rendering/text-and-overlays A built-in pixel font for heads-up displays, panels and keycaps, a portrait in a box of its own, and distance-field text in the world. The engine draws text two ways. A 5×7 pixel font is built into the code from bitmasks, so a heads-up display downloads nothing and carries nothing to license. Signed-distance-field text draws a font you supply, crisp at any size, in the world. Menus, buttons and layout are the job of the `@driftengine/ui2d` package, in the Input and interface section. (This chapter runs the `overlay-text` example at https://driftengine.dev/docs/rendering/text-and-overlays.) ## The pixel font ```ts /** One handle per message, laid out once and again only when its string changes. */ const title = renderer.createText(); const timer = renderer.createText(); const prompt = renderer.createText(); const keycap = renderer.createText(); renderer.setText(title, 'DRIFTENGINE'); renderer.setText(prompt, 'TO JUMP'); renderer.setText(timer, '0 S'); /** A solid plate of cells behind the key: SPACE is 29 cells wide, and two of margin all round. */ renderer.setPlate(keycap, 33, 11, -2); const keyLabel = renderer.createText(); renderer.setText(keyLabel, 'SPACE'); ``` `createText()` makes a handle for one message. `setText(handle, string)` lays it out, and does nothing when the string is the one already laid out, so calling it every frame with an unchanged string is free; the example rebuilds the timer's string only when the second changes. Make one handle per message slot and keep it. ```ts /** Styles are rebuilt only when the screen's size changes the cell size, never per frame. */ let cell = 0; let titleStyle: TextStyle = DEFAULT_TEXT_STYLE; let bodyStyle: TextStyle = DEFAULT_TEXT_STYLE; let plateStyle: TextStyle = DEFAULT_TEXT_STYLE; let keyStyle: TextStyle = DEFAULT_TEXT_STYLE; function restyle(size: number): void { cell = size; titleStyle = { ...DEFAULT_TEXT_STYLE, cellSize: size, color: srgbColor(1, 0.85, 0.35), glow: 1 }; bodyStyle = { ...DEFAULT_TEXT_STYLE, cellSize: size, color: srgbColor(0.8, 0.84, 0.92) }; plateStyle = { ...DEFAULT_TEXT_STYLE, cellSize: size, color: srgbColor(0.9, 0.9, 0.95) }; keyStyle = { ...plateStyle, color: srgbColor(0.08, 0.09, 0.12) }; } ``` A `TextStyle` sets `cellSize`, the pixels per cell of a glyph, the `color`, `glow` for text that reads as lit, and `alpha`. The rest animates text in: `reveal` from 0 to 1 runs the arrival, `spin` and `punch` tumble and pop each character as it lands, and `bob` keeps it moving gently while it idles. Build styles when the screen size changes, not every frame. ## Panels and text over the scene ```ts /* A backing panel first, then the glyphs over it, in CSS pixels from the top left. */ const left = Math.round(width * 0.06); const baseline = Math.round(height * 0.18); renderer.fillPanel( { left: left - cell * 3, top: baseline - cell * 10, width: cell * 72, height: cell * 22 }, PANEL, 0.8, ); renderer.drawText(title, width, height, left, baseline, titleStyle, seconds); renderer.drawText(timer, width, height, left, baseline + cell * 10, bodyStyle, seconds); ``` `drawText(handle, width, height, x, baseline, style, time)` draws in CSS pixels from the top left of the viewport you pass, with `baseline` measured down from the top. `fillPanel(rect, color, alpha)` fills a rectangle behind it. `textWidth(handle, cellSize)` measures a string for centring or right-aligning. ```ts /* A key drawn as a plate with its letters over it, then the words after it. */ const keyX = left; const keyY = Math.round(height * 0.86); renderer.drawText(keycap, width, height, keyX, keyY, plateStyle, seconds); renderer.drawText(keyLabel, width, height, keyX + cell * 2, keyY, keyStyle, seconds); renderer.drawText(prompt, width, height, keyX + cell * 36, keyY, bodyStyle, seconds); ``` `setPlate(handle, widthCells, heightCells, bottomCell)` turns a handle into a solid rectangle of cells, for a keycap or a backing plate; `bottomCell` is where it starts, in the same baseline-relative cells the glyphs use. A row of block glyphs would come out striped and sized in whole glyph widths. Draw the plate first and the word over it. Overlays may be drawn before `endFrame`, as here, or after it, over the presented frame, on both backends. Text and panels are encoded for the screen and never put through a tone curve or an exposure, so a colour picked by eye goes through `srgbColor` and comes out exactly as picked under any `outputTransform`. Under `hdrScene` an overlay drawn before `endFrame` is part of the picture the resolve tone maps; draw it after `endFrame` to keep it as picked. ## A portrait in a box ```ts /* A box in the corner with its own camera and its own backdrop, drawn into the same frame. */ const box = { left: width - 220, top: 24, width: 196, height: 196 }; const aspect = renderer.beginInset(box, INSET_CLEAR); gemNode.setRotationAxisAngle(0, 1, 0, seconds); gemNode.updateWorld(); portrait.updateMatrices(aspect); renderer.bindMeshPass(portrait, DAYLIGHT); renderer.drawMesh(gem, gemNode.worldMatrix); renderer.endInset(); ``` `beginInset(rect, clear)` draws into a rectangle of the canvas on its own terms: a character preview on a menu, an item in an inventory slot, a minimap. It takes the rectangle in CSS pixels, returns its aspect ratio for the camera that fills it, and clears only inside it, so the frame around survives. Bind a pass, draw, and `endInset()`. A `clear` of `null` clears only depth, for an object drawn into the live frame instead of onto a backdrop. ## A view model ```ts /** The world first, then the view model over it, through the same camera. */ export function drawWithViewModel( renderer: RendererApi, camera: Camera, env: Environment, world: () => void, weapon: MeshHandle, weaponModel: Float32Array, ): void { renderer.bindMeshPass(camera, env); world(); renderer.beginViewModel(); renderer.drawMesh(weapon, weaponModel); renderer.endViewModel(); } ``` `beginViewModel(share)` draws what follows in the nearest `share` of the depth range, 1% by default, until `endViewModel()`: a first person's arms and weapon land in front of anything past the near plane, so they never go into the wall they are pushed against. The world's depth is kept, so ambient occlusion, depth of field and fog still see the world behind the weapon. Draw the view model with the frame's camera, or bind one with its own field of view first. Its pixels take no motion of their own under temporal reconstruction, so draw a view model with multisampling, and not inside an inset, which has a depth of its own. `endFrame` closes one left open. ## Text in the world ```ts /** Load a font's metrics and atlas, which the engine never fetches itself, and lay a sign out. */ export async function shopSign(renderer: RendererApi, base: string): Promise { const font = parseSdfFont(await (await fetch(`${base}/metrics.json`)).json()); const image = await createImageBitmap(await (await fetch(`${base}/atlas.png`)).blob()); const atlas = renderer.createSurfaceTexture(image); const sign = renderer.createSdfText(); renderer.setSdfText(sign, font, atlas, 'OPEN LATE', { ...DEFAULT_SDF_TEXT_STYLE, size: 0.4, anchorX: 'center', }); return sign; } const NEON: Vec3 = [1, 0.4, 0.7]; /** Drawn inside the mesh pass, at a model matrix, like any mesh. */ export function drawSign(renderer: RendererApi, sign: SdfTextHandle, model: Float32Array): void { renderer.drawSdfText(sign, model, NEON, 1); } ``` Signed-distance-field text is opt-in, and the engine fetches nothing for it: you parse the font's metrics with `parseSdfFont` and upload its atlas with `createSurfaceTexture`, both from files you ship. `setSdfText(handle, font, atlas, string, style)` lays a string out, with a `size` in metres per em, horizontal and vertical anchors, letter spacing and line height. `drawSdfText(handle, model, color, opacity)` draws it inside the mesh pass at a model matrix, with the frame's camera, so a sign on a wall or a name over a character is part of the scene. It stays sharp close up, where the pixel font would show its cells. The engine repository's `npm run sdf-font` makes a font's atlas and metrics from a TTF or OTF file, and can bake pre-shaped runs of a script that joins or reorders its letters, since the engine itself does no shaping. Whoever runs it is responsible for that font's licence. --- # Picking Rendering. https://driftengine.dev/docs/rendering/picking What is under the pointer, from meshes registered for it, with the hit's point and distance, moving pickables, and a set of your own. Picking answers one question: what is under this pixel. The renderer tests a ray through the pixel against meshes registered for picking and returns the nearest hit. Everything around that question, hover, press, drag, the difference between a click and a drag, belongs to the game, which already has that logic for its controls. Hover over the example and click a shape. (This chapter runs the `picking` example at https://driftengine.dev/docs/rendering/picking.) ## Registering ```ts /** Each shape is drawn and registered for picking, with the same geometry and the same matrix. */ const shapeData = new MeshBuilder() .addBox([0, 0.4, 0], [0.4, 0.4, 0.4], [0.75, 0.75, 0.78]) .build(); const shape = renderer.createMesh(shapeData); const nodes: SceneNode[] = []; const handles: number[] = []; const lifted: boolean[] = []; for (let row = 0; row < 5; row += 1) for (let column = 0; column < 5; column += 1) { const node = new SceneNode(); node.setPosition((column - 2) * 2, 0, (row - 2) * 2); node.updateWorld(); nodes.push(node); handles.push(renderer.registerPickable(shapeData, node.worldMatrix)); lifted.push(false); } ``` `registerPickable(meshData, model)` adds a mesh's positions and indices at a model matrix and returns a handle. Register the same geometry you draw, with the same matrix, so what is picked is what is seen. Picking runs on the CPU against your data and never reads the GPU, so it answers the same on both backends and costs nothing on frames that do not ask. Each mesh's box in the world is computed when its matrix is set, so a ray rejects nearly everything with a box test and only the survivors pay for their triangles. ## Asking ```ts /** Where the pointer is, in the canvas's CSS box, and whether a click is waiting. */ let pointerX = -1; let pointerY = -1; let clicked = false; canvas.addEventListener('pointermove', (event) => { const box = canvas.getBoundingClientRect(); pointerX = event.clientX - box.left; pointerY = event.clientY - box.top; }); canvas.addEventListener('pointerleave', () => { pointerX = -1; }); canvas.addEventListener('click', () => { clicked = true; }); ``` Pointer positions are CSS pixels inside the canvas: `event.clientX` minus the canvas's left edge, with no device pixel ratio to think about. ```ts /* What is under the pointer: the nearest registered mesh along its ray, or nothing. */ const hit = pointerX < 0 ? null : renderer.pickAt(camera, pointerX, pointerY); const hovered = hit === null ? -1 : handles.indexOf(hit.handle); if (clicked && hovered >= 0) { lifted[hovered] = !lifted[hovered]; const node = nodes[hovered]; node.setPosition(node.position[0], lifted[hovered] ? 1 : 0, node.position[2]); node.updateWorld(); /* A pickable that moves is told where it went. */ renderer.updatePickable(handles[hovered], node.worldMatrix); } clicked = false; ``` `pickAt(camera, x, y)` returns the nearest hit or `null`. A hit says which `handle` it was, the `distance` along the ray, and the `point` in the world where the ray met it. The point is reused between queries, so copy it to keep it. A pick allocates nothing, so calling it on every pointer move is fine. **A pickable that moves is told where it went** with `updatePickable(handle, model)`, or it is picked where it used to be. `unregisterPickable(handle)` removes one. ## Rays of your own `camera.rayThrough(origin, direction, x, y, width, height)` writes the ray through a pixel into two arrays, for a game that wants to test it against something else: a ground plane, a physics world. For gameplay, such as what a gun hits or what a character can see, cast against the physics world's colliders instead; see the Simulation section. ## A second set The renderer's own set holds what the world draws. A `PickableSet` is the same machinery on its own, for things the world never draws as meshes, such as an editor's gizmo handles, or for a set that must be tested separately: `add(source, model)`, `update`, `remove`, `clear`, and `pick(origin, direction)` with a ray from `rayThrough`. --- # Custom passes and compute Rendering. https://driftengine.dev/docs/rendering/custom-passes Add a draw pass of your own, fill targets it owns before the frame opens, dispatch compute on WebGPU, and keep a pass right on both backends. The renderer's verbs cover what most games draw, and a pass of your own covers the rest: a shader written for one effect, a package's own renderer, a compute kernel that sorts, bins or simulates on the device. The engine's optional packages draw through the same door, so the Gaussian splats and the GPU-driven pipeline are passes registered exactly as yours would be. ## A pass ```ts /** A full-screen wash of colour over the frame, on WebGPU, as the smallest pass that draws. */ const WASH_WGSL = /* wgsl */ ` @vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f { let corner = vec2f(f32((i << 1u) & 2u), f32(i & 2u)); return vec4f(corner * 2.0 - 1.0, 0.0, 1.0); } @fragment fn fs() -> @location(0) vec4f { return vec4f(0.1, 0.0, 0.2, 0.15); } `; export function washPass(): PassDefinition { let pipeline: GPURenderPipeline | null = null; return { label: 'wash', init(device) { if (device.backend !== 'webgpu') return; const module = device.device.createShaderModule({ code: WASH_WGSL }); pipeline = device.device.createRenderPipeline({ layout: 'auto', vertex: { module, entryPoint: 'vs' }, fragment: { module, entryPoint: 'fs', targets: [ { format: device.format, blend: { color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha' }, alpha: SCENE_ALPHA_COVERS, }, }, ], }, depthStencil: { format: device.depthFormat, depthWriteEnabled: false, depthCompare: 'always', }, multisample: { count: device.samples }, }); }, draw(ctx) { if (ctx.backend !== 'webgpu' || pipeline === null) return; ctx.pass.setPipeline(pipeline); ctx.pass.draw(3); }, }; } ``` A `PassDefinition` has a `label` and up to four callbacks: - `init(device)` builds pipelines, buffers and textures, once, when the pass is registered. - `prepare(ctx)` fills a target the pass owns, each frame, before the frame's own target opens: a shadow map of its own, a blur pyramid, a picking buffer. - `draw(ctx)` draws into the frame, at the point the frame calls `drawPass`. - `dispose(device)` releases what `init` built. `reads` declares the frame attachments the pass samples, such as depth, so the frame keeps them for it. What a pass writes is wherever the frame is drawing; a pass cannot declare other writes into the frame, which is why `prepare` exists for targets it owns. The device and both contexts are tagged by backend, because a pass that draws on both has a different shader and a different buffer layout on each and branches either way. On WebGPU the device carries the frame's colour `format`, `depthFormat` and `samples`, which a pipeline cannot be built without, and whether the frame is reconstructed. On WebGL2 it carries the context. ```ts /** Registered once; drawn wherever the frame calls `drawPass`; let go when done. */ export function useWash(renderer: RendererApi): { draw(): void; release(): void } { const handle = renderer.registerPass(washPass()); return { draw: () => renderer.drawPass(handle), release: () => renderer.unregisterPass(handle), }; } ``` `registerPass(definition)` returns a handle, `drawPass(handle)` draws it inside the frame, and `unregisterPass(handle)` calls `dispose`. A handle kept after it is unregistered draws nothing; it never draws whatever took its slot. ## The rules a pass keeps - **It allocates nothing in `prepare` or `draw`.** They run every frame, and the engine's own rule about per-frame code binds them. - **It leaves the context as it found it.** On WebGL2: the program, the vertex array, blend and depth state and the viewport; `prepare` also leaves the default framebuffer bound. On WebGPU only the viewport and scissor carry over between draws. - **It corrects its projection.** A pass takes its camera from you, so it never sees the corrected matrix the renderer builds. Pre-multiply by `device.clipCorrection` if your WGSL was generated from GLSL with the engine's generator, and by `device.depthCorrection` if you wrote it by hand. The wrong one mirrors the world vertically, and mirrors the triangle winding with it, so it looks like a culling problem. - **It grades only when the frame does not.** `ctx.outputTransform` is 0 when the end of the frame applies the tone curve, and otherwise says which curve this pass must apply itself, with `ctx.outputExposure`. `OUTPUT_TRANSFORM_GLSL` is the engine's own curve, so a pass applies the same one. - **It jitters with a reconstructed frame.** With DriftTR on, a pass drawing the world applies the frame's jitter, `ctx.jitter`, with `jitterClip`, and writes its depth into the frame's attachment; see [DriftTR](https://driftengine.dev/docs/rendering/drifttr). - **It says what its blending does to the scene's alpha.** The scene's alpha holds how much of each pixel is still the opaque surface, and the composite darkens only that share with ambient occlusion, so a translucent draw is not darkened by a corner it hides. A pass drawing something blended over the world gives its alpha `SCENE_ALPHA_COVERS` (it hides what is behind by its alpha), `SCENE_ALPHA_TRANSMITS` (its alpha is what gets through) or `SCENE_ALPHA_KEEPS` (it adds light to the surface); on WebGL2, `blendCovering`, `blendTransmitting` or `blendKeeping` set the same thing beside the colour factors. An opaque draw writes 1. - **It sizes its targets from the scene.** `renderer.sceneWidth` and `sceneHeight` are what the frame is drawn at, which is smaller than the canvas under reconstruction. On WebGPU, `prepare` is also handed the frame's environment probe and, with DriftRay on, the world's composed distance field, one frame behind, for a pass that wants to light or trace its own work the way the frame does. ## Reading the frame A pass cannot sample the frame it is drawing into, so it reads copies, and declares which: - `reads: ['depthSnapshot']` hands it the frame's depth as it stands, one copy a frame, as `sceneDepth`: on WebGPU in the `PrepareContext`, a single-sample `r32float` texture to read with `textureLoad` or a non-filtering sampler, and on WebGL2 in the `PassContext`. It holds the depth buffer's own values, reversed as the buffer is: 1 at the near plane, 0 at the far one. - `reads: ['colorSnapshot']` hands it the frame's colour with everything drawn before it, copied afresh at each such pass's draw, as `sceneColor`: on WebGPU in the `PrepareContext`, at the scene's size and format, and on WebGL2 in the `PassContext`. A distortion samples the scene behind it with it; a full-screen pass drawn last reads the whole frame and writes over it, in scene light, before the tone curve: a radial blur, a flash, a filter over the finished picture. The views on WebGPU arrive in `prepare`, since a bind group is built before the frame's pass opens, and are filled at the draw. Both copies are `null` without `screenEffects`, which is what keeps a scene target to copy from. **Under DriftTR a pass that reads the colour draws after the upscale**, over the reconstructed picture and after every blended draw, whatever order it was asked in: otherwise it would read a frame without the blended draws and then be covered by them. It draws at the output's size and the reconstruction's format, which `ctx.format` names there, so it keeps a pipeline for that target. Its `sceneDepth` stays the render's opaque depth: coarser by the ratio above a ratio of 1, and a blended draw is in no depth either way. ## Compute ```ts /** A buffer of counters cleared on the device every frame, as the smallest compute definition. */ const CLEAR_WGSL = /* wgsl */ ` @group(0) @binding(0) var counts: array; @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3u) { if (id.x < arrayLength(&counts)) { counts[id.x] = 0u; } } `; /** `GPUBufferUsage.STORAGE`, spelled as its value: the global exists only in a browser. */ const STORAGE = 0x0080; export function clearCounters(size: number): ComputeDefinition { let pipeline: GPUComputePipeline | null = null; let group: GPUBindGroup | null = null; return { label: 'clear counters', init({ device }) { const buffer = device.createBuffer({ size: size * 4, usage: STORAGE }); pipeline = device.createComputePipeline({ layout: 'auto', compute: { module: device.createShaderModule({ code: CLEAR_WGSL }), entryPoint: 'main' }, }); group = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer } }], }); }, dispatch({ pass }) { if (pipeline === null || group === null) return; pass.setPipeline(pipeline); pass.setBindGroup(0, group); pass.dispatchWorkgroups(Math.ceil(size / 64)); }, }; } /** Only where the backend has compute at all; WebGL2 does not. */ export function startCounters(renderer: RendererApi): (() => void) | null { if (!renderer.computeSupported) return null; const handle = renderer.registerCompute(clearCounters(4096)); return () => renderer.dispatchCompute(handle); } ``` A `ComputeDefinition` is the same idea for the stage before drawing: `init` builds pipelines and buffers from the device, and `dispatch(ctx)` sets a pipeline and bind groups and calls `dispatchWorkgroups` on the compute pass the engine opened for it. The workgroup count is yours, since it comes from data the definition owns. `registerCompute(definition)` returns a handle, `dispatchCompute(handle)` runs it, and `unregisterCompute` releases it. Compute is WebGPU only: WebGL2 has no compute stage. `renderer.computeSupported` says which you have, and `registerCompute` refuses in words where it is false. A dispatch is submitted at once, so its result is visible to everything recorded after it, including a draw pass in the same frame. ## Testing a compute shader WGSL arithmetic can be wrong in ways no picture shows. The engine tests its own kernels by running them on a real device and reading the buffers back against a TypeScript reference, with `openGpuCompute` from `@driftengine/core/scripts/gpuCompute.mjs`. The same harness works for a game's own kernels; it serves its page from a loopback server, since `navigator.gpu` needs a secure context. --- # Terrain Worlds. https://driftengine.dev/docs/worlds/terrain A heightfield whose queries answer the ground that is drawn, a clipmap with matched seams, blended materials, colliders, and heights kept as textures. `@driftengine/terrain` is a heightfield and the geometry it draws, for 1.4 KB gzipped on top of core. It imports no renderer: a patch of terrain comes back as `MeshData`, which goes to `createMesh` like any other geometry and is drawn by the pass that already exists. The rule the package is built around is that every question about the ground answers the surface that is drawn. A query, the mesh, a collider and a script asking how steep a hillside is all read the same triangles, so a character stands on the ground you can see. The example is a river valley two kilometres across, flown over. Paint the levels to see the clipmap, and change how many cells a patch has and how many levels reach out. (This chapter runs the `terrain` example at https://driftengine.dev/docs/worlds/terrain.) ## A field ```ts /** Samples across each side, two metres apart: a field 2,048 metres square, centred on the origin. */ const SAMPLES = 1025; const SPACING = 2; const HALF = ((SAMPLES - 1) * SPACING) / 2; /** Smooth noise on a unit lattice, from a hash of each corner. */ function lattice(x: number, z: number): number { const ix = Math.floor(x); const iz = Math.floor(z); const fx = x - ix; const fz = z - iz; const sx = fx * fx * (3 - 2 * fx); const sz = fz * fz * (3 - 2 * fz); const a = hashToUnit(Math.imul(ix, 73856093) ^ Math.imul(iz, 19349663)); const b = hashToUnit(Math.imul(ix + 1, 73856093) ^ Math.imul(iz, 19349663)); const c = hashToUnit(Math.imul(ix, 73856093) ^ Math.imul(iz + 1, 19349663)); const d = hashToUnit(Math.imul(ix + 1, 73856093) ^ Math.imul(iz + 1, 19349663)); return (a + (b - a) * sx + (c - a) * sz + (a - b - c + d) * sx * sz) * 2 - 1; } /** Height in metres: a river winding along z, valley walls rising either side, hills over all. */ function valley(x: number, z: number): number { const river = Math.sin(z / 260) * 120 + Math.sin(z / 97) * 25; const fromRiver = Math.abs(x - river); const wall = Math.min(1, Math.max(0, (fromRiver - 30) / 700)); const rise = 230 * wall * wall * (3 - 2 * wall); let hills = 0; let amplitude = 1; let frequency = 1 / 220; for (let octave = 0; octave < 4; octave += 1) { hills += lattice(x * frequency, z * frequency) * amplitude; amplitude *= 0.5; frequency *= 2.1; } const bed = 5 * Math.max(0, 1 - fromRiver / 22); return rise + hills * (4 + rise * 0.35) - bed + 3; } const heights = new Float32Array(SAMPLES * SAMPLES); for (let row = 0; row < SAMPLES; row += 1) for (let column = 0; column < SAMPLES; column += 1) heights[row * SAMPLES + column] = valley(column * SPACING - HALF, row * SPACING - HALF); const terrain = new Terrain({ width: SAMPLES, depth: SAMPLES, spacingM: SPACING, heights, origin: [-HALF, 0, -HALF], }); ``` `new Terrain(options)` takes: - `width` and `depth`, the samples along x and z, at least two each. - `spacingM`, the metres between samples, the same both ways. - `heights`, `width * depth` heights in metres, row-major with x running fastest. - `origin`, the world position of sample `(0, 0)`. Its y is added to every height. The field reaches `extentX` and `extentZ` metres, one cell fewer than it has samples. The heights are copied, so a caller may reuse its array. ```ts /** A gentle slope 64 metres square, rising toward +x, with sample (0, 0) at the origin. */ const SIDE = 65; const heights = new Float32Array(SIDE * SIDE); for (let row = 0; row < SIDE; row += 1) for (let column = 0; column < SIDE; column += 1) heights[row * SIDE + column] = column * 0.1 + Math.sin(row * 0.3) * 0.5; export const field = new Terrain({ width: SIDE, depth: SIDE, spacingM: 1, heights }); /** How high the ground is, and which way it faces, at a place on it. */ export const groundY = field.heightAt(10.5, 20.25); export const up = field.normalAt(10.5, 20.25, new Float32Array(3)); ``` `heightAt(x, z)` is the height of the drawn surface at a world position. A cell is drawn as two triangles, and the query reads the triangle under the point. Interpolating the four corners bilinearly would describe a different surface, one that floats over half of every cell and sinks into the other half. Outside the field the query answers the nearest edge. `normalAt(x, z, out)` is a central difference over the samples, so it is continuous across every cell and every patch boundary. It is what the mesh carries as its vertex normals; a face normal would jump at every edge, and two patches would shade differently along the edge they share. To find the plane a wheel rests on, take three `heightAt` samples. ## Patches and levels of detail `heightfieldPatch(terrain, options)` builds one square of the field as `MeshData`: - `x` and `z`, the grid index of the patch's first sample. - `cells`, how many field cells it spans. - `step`, how many field cells one drawn cell spans: 1 is full detail, 4 a quarter. It must divide `cells`. - `neighbours`, the step of each neighbour that is coarser than this patch, as `minusX`, `plusX`, `minusZ` and `plusZ`. - `color` and `emissive` for one colour over the whole patch, or `materials` for several blended across the field. ```ts /** A full-detail patch whose +x neighbour is drawn at a quarter of the detail. */ export const fine = heightfieldPatch(field, { x: 0, z: 0, cells: 32, step: 1, neighbours: { plusX: 4 }, }); export const coarse = heightfieldPatch(field, { x: 32, z: 0, cells: 32, step: 4 }); ``` Where a fine patch meets a coarse one, the fine edge has vertices the coarse edge does not, and they sit on the field while the coarse edge cuts a straight chord beneath them. The gap between the two is a crack through to the sky. Naming the coarser neighbour moves the fine edge's extra vertices onto that chord, so the two edges are one polyline and there is nothing to fill. Only the coarser side is named, because the finer patch is the one that moves; a neighbour at the same step or a finer one changes nothing, so pass what you know. Matching has a cost, stated so it is not discovered later: along a matched edge the drawn surface is the coarse chord, so `heightAt` and the picture differ there by up to the sag of one coarse cell. That is the error the coarse patch carries over its whole area anyway, arriving one cell early. ## The clipmap ```ts /** The ground the camera is over, as one mesh rebuilt only when a level's block moves. */ let groundMesh: MeshHandle | null = null; let shown: ClipmapFrame | null = null; let shownPatchX = Number.NaN; let shownPatchZ = Number.NaN; /** One selected patch, painted by its level or by the ground's materials. */ function patchFor(options: HeightfieldPatchOptions, level: number): HeightfieldPatchOptions { return paint === 'levels' ? { ...options, color: LEVEL_COLOURS[level] ?? [1, 1, 1] } : { ...options, materials }; } function chooseGround(cameraX: number, cameraZ: number): void { /* A block snaps to whole patches, so nothing can move until the camera crosses one. */ const patchX = Math.floor(cameraX / (cells * SPACING)); const patchZ = Math.floor(cameraZ / (cells * SPACING)); if (!stale && patchX === shownPatchX && patchZ === shownPatchZ) return; shownPatchX = patchX; shownPatchZ = patchZ; const frame = clipmapFrame(terrain, cameraX, cameraZ, { levels, patchCells: cells }); const moved = shown === null || frame.origins.some((origin, i) => origin !== shown?.origins[i]); if (!stale && !moved) return; shown = frame; stale = false; const patches = selectClipmap(frame).map((patch) => heightfieldPatch(terrain, patchFor(clipmapPatchOptions(patch), patch.level)), ); const next = renderer.createMesh(concatMeshes(patches)); if (groundMesh !== null) renderer.disposeMesh(groundMesh); groundMesh = next; } ``` A clipmap draws the field as rings of patches whose step doubles outward, so the ground under the camera is drawn at full detail and the horizon at a fraction of it, and the vertex count stays the same however large the world is. - `clipmapFrame(terrain, cameraX, cameraZ, options)` snaps each level's block to the camera once for a frame. The options are `levels` (4 by default), `patchCells`, the drawn cells along a patch's edge (8), and `patchesAcross`, the patches along a block's edge (8, and a multiple of four). - `selectClipmap(frame)` lists every patch to draw, each with its level, position, `cells`, `step` and `neighbours`. - `clipmapPatchOptions(patch)` turns one into the options `heightfieldPatch` takes, with nothing added or renamed. The outermost block spans `patchesAcross × patchCells × 2^(levels − 1)` field cells: 512 with the defaults, which is a kilometre across at two metres a cell. That is what the switches change. Two failures decide the design. A field cell drawn by two patches is z-fighting on the ground, and one drawn by none is a hole. Each level's block snaps to an even patch index, which makes a finer block's edge fall on a coarser patch boundary, so a coarse patch is either covered by the level inside it or not at all, and is culled when it is covered. The finer block is therefore not always centred in the coarser one, and that is harmless. The tests count every cell of the footprint at thirty-three camera positions across a coarse patch and find each one drawn exactly once. The clipmap builds no geometry and the blocks only move when the camera crosses a patch, which is why the example compares the frame's `origins` with the last one before rebuilding anything. ### The selection, one patch at a time `clipmapPatchAt(frame, index, out)` decides one patch by its index and writes it into `out`, which `emptyClipmapPatch()` makes once so a loop allocates nothing. It returns whether that patch is drawn. `clipmapPatchCount(frame)` is how many indices there are, and `clipmapLevelAt(frame, cellX, cellZ)` says which level draws a field cell, or `-1`. The decision reads the frame and the index and nothing else. A `ClipmapFrame` is an `Int32Array` of origins and four numbers, which a uniform block can hold, so the selection is the body of a compute shader: it is written to move into a compute pass beside the [GPU-driven](https://driftengine.dev/docs/rendering/gpu-driven) cluster cut without being rewritten. Today it runs on the CPU, and the test that asks for the patches in a scrambled order is what keeps it free of any loop-carried state. ## Materials across the field ```ts /** Grass, rock and snow, weighted across the field by what the script says each place is. */ const WEIGHTS_ACROSS = 513; const GRASS: Vec3 = [0.25, 0.38, 0.16]; const ROCK: Vec3 = [0.4, 0.38, 0.35]; const SNOW: Vec3 = [0.86, 0.88, 0.92]; function paintGround(): TerrainMaterials { const rockiness = exported>(ground, 'rockiness'); const snowiness = exported>(ground, 'snowiness'); const weights = new Float32Array(WEIGHTS_ACROSS * WEIGHTS_ACROSS * 3); const step = (2 * HALF) / (WEIGHTS_ACROSS - 1); for (let row = 0; row < WEIGHTS_ACROSS; row += 1) { for (let column = 0; column < WEIGHTS_ACROSS; column += 1) { const x = column * step - HALF; const z = row * step - HALF; const rock = rockiness(terrain, x, z); const snow = snowiness(terrain, x, z); const at = (row * WEIGHTS_ACROSS + column) * 3; weights[at] = Math.max(0, 1 - rock - snow); weights[at + 1] = rock; weights[at + 2] = snow; } } return new TerrainMaterials({ materials: [{ color: GRASS }, { color: ROCK, specular: 0.15 }, { color: SNOW, specular: 0.4 }], width: WEIGHTS_ACROSS, depth: WEIGHTS_ACROSS, weights, }); } ``` `new TerrainMaterials({ materials, width, depth, weights })` blends several materials across the field. Each material has a `color`, and optionally `emissive` and `specular`. The weight map is `width * depth * materials.length` numbers, row-major with the material running fastest, at any resolution: the example paints a 2,048-metre field from a 513-square map. The blend is baked into vertex colour when the patch is built, so it costs nothing per frame and binds no texture. The price is that it is only as sharp as the mesh: a boundary inside a cell is a gradient across that cell, and a coarse patch blends as coarsely as it is drawn. Draw a patch at full detail where a line must be sharp. Weights are read bilinearly, unlike heights. A weight decides a vertex colour and is not drawn as triangles, so reading it as triangles would only put a crease along every cell diagonal. Weights are normalised as they are read, and a place where every weight is zero takes the first material, so an unpainted corner of a map is never black. `terrainMaterialWeights(map, u, v, out)` returns the normalised weights at a point given in the field's own `0..1` extent. ## From DriftScript `drift/terrain` gives a script the same answers: | Capability | Answers | | ------------------------------- | ----------------------------------------- | | `heightAt(terrain, x, z)` | How high the drawn ground is, in metres. | | `normalX`, `normalY`, `normalZ` | Which way it faces, one component a call. | | `slopeAt(terrain, x, z)` | How steep it is, in radians from flat. | | `covers(terrain, x, z)` | Whether a place is over the field at all. | | `extentX(terrain)`, `extentZ` | How far the field reaches, in metres. | Every one is a read of static data and deterministic, so a `@deterministic` system may ask where the ground is. The module needs no host service: the field reaches a script as a `Terrain` argument, the way a navigation graph does. The example's rules are a DriftScript module. Rock, snow and trees each ask the slope and the height: ```drs // How much of the ground at a place is bare rock, 0 to 1: none below a slope of 0.45 radians // (about 26 degrees), all of it from 0.7. fn rockiness(ground: Terrain, x: f32, z: f32) -> f32 { return math.clamp((terrain.slopeAt(ground, x, z) - 0.45) / 0.25, 0, 1) } // How much is snow: it lies above 140 metres, fully by 170, and slides off the steepest faces. fn snowiness(ground: Terrain, x: f32, z: f32) -> f32 { let high = math.clamp((terrain.heightAt(ground, x, z) - 140) / 30, 0, 1) return high * (1 - rockiness(ground, x, z) * 0.8) } // Whether a tree can grow here: on gentle ground, above the river and below the tree line. fn grows(ground: Terrain, x: f32, z: f32) -> bool { let height = terrain.heightAt(ground, x, z) return terrain.slopeAt(ground, x, z) < 0.35 && height > 6 && height < 115 } ``` and the camera holds its height above the ground ahead of it as well as beneath it: ```drs // One frame of flight round the valley. The camera holds its height above the ground ahead of it as // well as the ground beneath, so it climbs before a ridge arrives instead of on it. fn glide(flight: mut Flight, ground: Terrain, dt: f32) { flight.angle = flight.angle + dt * 0.045 let radius = 300 flight.x = math.cos(flight.angle) * radius flight.z = math.sin(flight.angle) * radius let aheadX = math.cos(flight.angle + 0.25) * radius let aheadZ = math.sin(flight.angle + 0.25) * radius let floor = math.max(terrain.heightAt(ground, flight.x, flight.z), terrain.heightAt(ground, aheadX, aheadZ)) let wanted = floor + 45 // Ease toward it, so the flight rises and settles instead of following every bump. flight.y = flight.y + (wanted - flight.y) * math.clamp(dt * 0.6, 0, 1) // Look further along the loop, at the ground there. flight.lookX = math.cos(flight.angle + 0.6) * radius flight.lookZ = math.sin(flight.angle + 0.6) * radius flight.lookY = terrain.heightAt(ground, flight.lookX, flight.lookZ) } ``` The page hosts the module and calls those rules, and when the file changes under `npm run examples` it repaints the ground and replants the forest with the new rules while the flight carries on: ```ts /** The valley's rules, hosted. The flight is a record the page holds, so an edit keeps it flying. */ const ground = hostScript(groundScript); interface Flight { angle: number; x: number; y: number; z: number; lookX: number; lookY: number; lookZ: number; } const flight = exported<() => Flight>(ground, 'createFlight')(); type Rule = (field: Terrain, x: number, z: number) => T; type Glide = (flight: Flight, field: Terrain, dt: number) => void; ``` ## Colliding with it ```ts /** The field as a collider: one static body holding the heights, and a ball dropped onto it. */ export const world = new PhysicsWorld(); world.addBody({ type: BODY_STATIC, shape: heightfieldShape(field), friction: 0.8 }); export const ball = world.addBody({ type: BODY_DYNAMIC, shape: sphereShape(0.5), x: 20, y: field.heightAt(20, 20) + 3, z: 20, }); /** Or the patch that is drawn, chords and all, so a coarse patch collides as coarse as it looks. */ export const drawnWorld = new PhysicsWorld(); drawnWorld.addBody({ type: BODY_STATIC, shape: meshShape(coarse.positions, coarse.indices) }); ``` A `Terrain` is a `Heightfield` to `@driftengine/physics`, with the same names and meanings, so `heightfieldShape(terrain)` makes a collider straight from it. That collider holds the heights it was handed and finds the cell under a body from its x and z, with no vertex buffer and no tree; at a 129-square field a mesh collider's positions and indices alone are more than five times the bytes of the heights. Contacts against it are the same as against the triangles, and a test walks a box across both and compares every normal, count and separation. `meshShape(patch.positions, patch.indices)` takes the arrays a patch hands back, so the geometry you draw is the geometry you collide with. Use it when the collider must be the patch as drawn: a coarse patch then collides as coarsely as it looks. Use the heightfield when the field is the truth and patches are only how it is drawn, which is the usual case for a large world. The world those colliders live in, its bodies and its step, is [Rigid bodies](https://driftengine.dev/docs/simulation/rigid-bodies). ## Heights kept as a texture ```ts /** The heights as a texture layer, and the terrain everything should read, built from it. */ const layer = encodeTerrainHeights(field); export const stored = terrainFromHeightLayer(layer); /** How far a decoded height may sit from the source: half a 16-bit step of the field's range. */ export const tolerance = terrainHeightTolerance(layer); ``` `encodeTerrainHeights(terrain)` stores a field as a `DTEX` layer from `@driftengine/texture`: a decode program over a 16-bit latent image (`TERRAIN_HEIGHT_LEVELS`, 65,536 levels) and the field's own range in metres, its spacing and its origin. Terrain then has the texture format's residency, streaming and determinism without an image path of its own. The range is the field's own because a shallow valley quantised against a whole world's range would be drawn as a staircase. Build the terrain everything reads with `terrainFromHeightLayer(layer)`. It decodes the samples and builds a `Terrain` from the decoded numbers, so the query, the mesh and the collider all read one set of heights. A renderer reading the layer while collision reads the source heights would disagree by the format's tolerance everywhere, which shows up as a character floating a fraction of a millimetre above every surface. `terrainHeightTolerance(layer)` is that tolerance: half a quantisation step plus one float32 step of the range. `decodeTerrainHeights(layer, out)` decodes into an array of your own. ```ts /** Four materials per sample, summing to one: grass that turns to rock up the slope. */ const weights = new Float32Array(SIDE * SIDE * TERRAIN_SPLAT_CHANNELS); for (let at = 0; at < SIDE * SIDE; at += 1) { const rock = (at % SIDE) / (SIDE - 1); weights[at * TERRAIN_SPLAT_CHANNELS] = 1 - rock; weights[at * TERRAIN_SPLAT_CHANNELS + 1] = rock; } const splat = encodeTerrainSplat(SIDE, SIDE, weights); /** The four weights halfway across, renormalised so they sum to one again. */ export const blend = new Float32Array(TERRAIN_SPLAT_CHANNELS); decodeTerrainSplat(splat, 0.5, 0.5, blend); ``` `encodeTerrainSplat(width, depth, weights)` stores four material weights a sample (`TERRAIN_SPLAT_CHANNELS`) at eight bits each (`TERRAIN_SPLAT_LEVELS`). It refuses weights that do not sum to one, because a map nobody filled in would otherwise ship as one material everywhere. `decodeTerrainSplat(layer, u, v, out)` samples them and renormalises, since four weights rounded to eight bits sum to anywhere from 0.994 to 1.006, and a shader that trusts the sum shades a hillside slightly wrong. None of this is imported unless named, so a game that never stores its terrain as a texture pays nothing for `@driftengine/texture`. --- # Large worlds Worlds. https://driftengine.dev/docs/worlds/large-worlds The cell grid a large world streams in, streaming by where the camera will be, and freezing cells so streaming never changes what the simulation computes. [Coordinates](https://driftengine.dev/docs/concepts/coordinates) explains the rule a large world rests on: the simulation keeps absolute positions in double precision and never rebases, and rendering subtracts an origin that moves a whole cell at a time. This chapter is the rest of it. The world is a sparse grid of cells, and a cell is the unit that streams in, streams out and freezes. The example is a town three thousand kilometres from the origin, where a 32-bit float counts in quarters of a metre. The camera circles through it, cells arrive as it approaches, and people walk about wherever the simulation reaches. Each cell takes a second and a half to arrive, standing in for a slow network: switch prediction off and the town builds itself in front of the camera. Paint the cells to see which are simulating and which are frozen. (This chapter runs the `streaming` example at https://driftengine.dev/docs/worlds/large-worlds.) ## The cell grid A cell is addressed by three whole grid coordinates, packed into one number: - `cellCoord(value, size)` is the grid coordinate a world coordinate falls in. It is `Math.floor`, so a position on a boundary belongs to exactly one cell, and negative coordinates work. - `cellIdFrom(cx, cy, cz)` packs three coordinates into one identifier, and `cellIdFor(x, y, z, size)` does it from a world position. - `cellCoordsOf(id, out)` unpacks one into an `Int32Array`, and `cellBounds(id, size, out)` writes a cell's minimum corner and size into a `Float64Array`. The packing holds ±65,536 cells an axis: ±16,777 km at 256-metre cells, ±4,194 km at 64. A coordinate outside that throws a `RangeError` and never wraps, because a wrapped identifier belongs to a different, real cell, and two distant places would silently share one. `cellCoordInRange(c)` asks first. `cellsInRadius(x, y, z, radius, size, out)` lists every cell within a radius of a point. It is conservative: it lists every cell that the cube round the sphere reaches, because a cell too many is a wasted load and a cell too few is a hole. `cellsInFrustum(grid, viewProjection, out)` lists the cells a view looks into, in coordinate order. The view-projection is in absolute world units and should be built in double precision past 2²⁴, where a single float no longer places a plane to the metre. `createCellGrid(size, maxCells)` makes the grid it walks; a view that would walk more than `maxCells` (65,536 by default) throws, and so does a view with no far plane, since a view that reaches infinity bounds no cells. ## Streaming cells ```ts /** How long a cell takes to arrive, in seconds of wall clock: a stand-in for a slow network. */ const ARRIVAL_SECONDS = 1.5; interface Resident { mesh: MeshHandle; /** The cell's minimum corner, absolute, for drawing it relative to the render origin. */ x: number; z: number; } const resident = new Map(); const arriving = new Map(); const coords = new Int32Array(3); /** * Where a cell's contents live. Only the layer of cells at ground level holds a town; the layers * above and below hold nothing, so they count as loaded at once. */ const store: CellStore = { loaded(id) { cellCoordsOf(id, coords); return coords[1] !== 0 || resident.has(id); }, load(id) { if (!arriving.has(id)) arriving.set(id, performance.now() + ARRIVAL_SECONDS * 1000); }, unload(id) { /* Only a frozen cell may be unloaded: freezing first is a no-op for one that already is. */ if (byCell.has(id)) freezeCell(world, frozen, id); const cell = resident.get(id); if (cell !== undefined) renderer.disposeMesh(cell.mesh); resident.delete(id); arriving.delete(id); }, }; /** The stream: cells within 110 metres are wanted, and dropped after two seconds unwanted. */ const stream = createCellStream({ store, size: CELL, radius: 110, hysteresis: 120 }); const predictor = cellPredictor(stream); ``` A `CellStore` is whatever holds a cell's contents: it answers `loaded(id)`, and is told `load(id, priority)` and `unload(id)`. A lower priority is sooner. The store decides what a load is. The example builds a few boxes from the cell's coordinates after a delay; a game fetches a region of a `.drft` file. `createCellStream(options)` takes the store and: - `size`, the cell's edge in world units. - `radius`, how far around a view cells are wanted. - `hysteresis`, how many pumps a cell may go unwanted before it is dropped. A camera that turns round does not reload what it just left, and a walk back and forth across a boundary does not reload a cell every few frames. - `origin`, the render origin the views are relative to, which `setCellStreamOrigin` moves. - `projection`, the lens the views are drawn through. With it the stream also wants the cells each view looks into, out to its far plane, nearest first; without it, only those within `radius`. - `maxCells`, the most cells one view's query may walk. ```ts /* The render origin follows the camera a whole cell at a time, and the stream is told it. */ pathAt(time, eye); renderOrigin(eye[0] as number, eye[1] as number, eye[2] as number, CELL, origin); setCellStreamOrigin(stream, origin[0] as number, origin[1] as number, origin[2] as number); predictedTime = time; runPrediction(handle, predictor, predict ? 120 : 1, predict ? 1 / 60 : 0, 32); pumpCellStream(stream, eye[0] as number, eye[1] as number, eye[2] as number); ``` Each frame, `pumpCellStream(stream, x, y, z)` marks the cells around the camera as wanted now and unloads those that have gone unwanted longer than the hysteresis. It returns how many it dropped. Marking the present is what keeps a camera that stands still from unloading the ground it stands on. ### By where the camera will be `cellPredictor(stream)` turns a stream into a predictor, which `runPrediction` from `@driftengine/texture` drives: it saves the simulation, runs it forward, asks what each predicted view needs, requests what is missing and puts the simulation back exactly as it was. ```ts /** * What prediction runs forward. The view here depends only on the camera's path, so the handle * saves, advances and restores the clock alone; a game whose camera follows a simulated player * advances its real step. */ let predictedTime = 0; let savedTime = 0; const lens = new Camera(); const at = new Float64Array(3); const ahead = new Float64Array(3); const local = new Float32Array(3); const handle: SimulationHandle = { save: () => { savedTime = predictedTime; }, restore: () => { predictedTime = savedTime; }, advance: (dt) => { predictedTime += dt; }, viewAt(out) { aimAt(lens, predictedTime); lens.updateMatrices(renderer.cssWidth / Math.max(1, renderer.cssHeight)); out.set(lens.view); }, }; /** Put a camera on the path at a time, in render space, looking three seconds ahead. */ function aimAt(view: Camera, when: number): void { pathAt(when, at); pathAt(when + 3, ahead); toRenderSpace(at[0] as number, at[1] as number, at[2] as number, stream.origin, local); view.position[0] = local[0] as number; view.position[1] = local[1] as number; view.position[2] = local[2] as number; toRenderSpace(ahead[0] as number, 0, ahead[2] as number, stream.origin, local); view.lookAt(local[0] as number, local[1] as number, local[2] as number); } ``` `runPrediction(simulation, predictor, frames, dt, budget)` takes a `SimulationHandle` with four methods: `save`, `restore`, `advance(dt)`, which must be the step the simulation really runs, and `viewAt(out)`, which writes the current view matrix. It requests at most `budget` cells across all the predicted frames, nearer frames first, so a distant frame cannot starve a near one. A misprediction costs a wasted fetch, and the cell arrives as late as it would have without prediction. The views a renderer takes are single precision and in render space, so the stream is told the render origin and adds it back in double precision before anything is put in a cell. `cameraPositionFrom(view, out)` recovers a camera's position from a view matrix, rotation and all. [Texture tiles](https://driftengine.dev/docs/worlds/texture-streaming) stream by the same prediction. ## Freezing A cell outside the simulated radius freezes: everything in it stops simulating, and its state is captured exactly. Freezing is a simulation decision and unloading is a memory decision. A frozen cell does not simulate whether or not its contents are loaded, and only a frozen cell may be unloaded, so streaming changes where the bytes live and never what the simulation computes. If unloading caused freezing, the simulation would depend on how much memory a machine had, and one player's computer would diverge from everyone else's. ```ts /** The walkers, hosted. Each is a record the page holds, so an edited script keeps them all. */ const walkers = hostScript(walkerScript); interface Walker { x: number; z: number; heading: number; untilTurn: number; seed: number; turns: number; } const createWalker = exported<() => Walker>(walkers, 'createWalker'); type Step = (walker: Walker, dt: number, cellSize: number) => void; const people: Walker[] = []; const homes: number[] = []; const walking: boolean[] = []; const byCell = new Map(); /** Four people to a cell, placed from the cell's identifier when the cell first comes near. */ function populate(id: number): void { const living: number[] = []; for (let i = 0; i < 4; i += 1) { const walker = createWalker(); walker.seed = (id + i * 977) >>> 0; walker.x = 6 + hashToUnit(walker.seed) * (CELL - 12); walker.z = 6 + hashToUnit(walker.seed + 1) * (CELL - 12); living.push(people.length); people.push(walker); homes.push(id); walking.push(true); } byCell.set(id, living); } /** What freezing needs of the world: who lives in a cell, and their state as numbers. */ const world: FreezableWorld = { entitiesIn: (cell) => byCell.get(cell) ?? [], readState(entity, out) { const w = people[entity] as Walker; out[0] = w.x; out[1] = w.z; out[2] = w.heading; out[3] = w.untilTurn; out[4] = w.turns; return 5; }, writeState(entity, values) { const w = people[entity] as Walker; w.x = values[0] as number; w.z = values[1] as number; w.heading = values[2] as number; w.untilTurn = values[3] as number; w.turns = values[4] as number; }, simulating: (entity) => walking[entity] === true, setSimulating(entity, on) { walking[entity] = on; }, }; const frozen = createFrozenCells(); ``` Freezing needs five things of a world, given as a `FreezableWorld`: the entities whose home is a cell, `readState` and `writeState` to copy an entity's state out as numbers and back, and `simulating` and `setSimulating`. Core has no entity store of its own, so a game passes whichever it keeps. ```ts /** * People live in every cell within 240 metres of the camera, and walk only within 40; the rest are * frozen. A cell is peopled frozen, so it is the simulated radius alone that sets anyone walking. * Both are conservative: a cell any part of the radius's square reaches is in it. */ const PEOPLED_M = 240; const SIMULATED_M = 40; let time = 0; const eye = new Float64Array(3); const near: number[] = []; const nearSet = new Set(); function simulate(dt: number): void { time += dt; pathAt(time, eye); cellsInRadius(eye[0] as number, 0, eye[2] as number, PEOPLED_M, CELL, near); for (const id of near) { cellCoordsOf(id, coords); if (coords[1] !== 0 || byCell.has(id)) continue; populate(id); freezeCell(world, frozen, id); } cellsInRadius(eye[0] as number, 0, eye[2] as number, SIMULATED_M, CELL, near); nearSet.clear(); for (const id of near) { cellCoordsOf(id, coords); if (coords[1] === 0) nearSet.add(id); } /* Freezing is decided here, by the simulation's own camera, and never by what is loaded. */ for (const id of nearSet) thawCell(world, frozen, id); for (const id of byCell.keys()) { if (!nearSet.has(id) && !isCellFrozen(frozen, id)) freezeCell(world, frozen, id); } const step = exported(walkers, 'step'); for (let i = 0; i < people.length; i += 1) { if (walking[i] === true) step(people[i] as Walker, dt, CELL); } } ``` - `createFrozenCells()` holds what has been frozen. - `freezeCell(world, frozen, cell)` stops a cell's entities simulating and captures their state, in ascending entity order so the capture is deterministic. It returns `false` if the cell was already frozen. - `thawCell(world, frozen, cell)` puts every entity back exactly as it was frozen and lets it simulate again. Never where it would have got to: a thaw that extrapolated would make an unloaded region quietly diverge from a loaded one. - `isCellFrozen` and `frozenEntities` answer what is frozen. - `frozenFingerprintContribution(frozen, cell)` is a digest of a frozen cell's state, taken once when it froze. Feed it into the world's fingerprint beside the live entities, so a streamed run and one that kept every cell loaded agree at every frame, and not only once everything has thawed. What freezing costs is a decision a game has to know about: an entity in a frozen cell does not walk anywhere, does not age and does not finish what it was doing. The engine's own gate walks a world at six magnitudes, from the origin to the far end of the packing, and asserts that the streamed walk fingerprints identically to one holding every cell; it also asserts that freezing by residency diverges, so the gate cannot pass by accident. ## Behaviour in a cell, in DriftScript The walkers are DriftScript records, and their positions are metres from the corner of their own cell: ```drs fn step(walker: mut Walker, dt: f32, cellSize: f32) { walker.untilTurn = walker.untilTurn - dt if walker.untilTurn <= 0 { walker.turns = walker.turns + 1 let draw = walker.seed * 7919 + walker.turns walker.heading = random.range(draw, 0, 6.2831855) walker.untilTurn = random.range(draw + 1, 1.5, 4) } // A brisk walk, kept two metres inside the cell's edge. let pace = 1.4 walker.x = math.clamp(walker.x + math.cos(walker.heading) * pace * dt, 2, cellSize - 2) walker.z = math.clamp(walker.z + math.sin(walker.heading) * pace * dt, 2, cellSize - 2) } ``` A script's numbers are 32-bit, so a script never holds an absolute coordinate in a large world: it works in a cell's frame and the page adds the cell's corner in double precision when it draws. The next turn comes from the walker's seed and how many turns it has made, so a walker that froze and thawed turns exactly as one that never stopped. Save the file under `npm run examples` and every walking figure takes the new rules on its next step. --- # Hierarchical detail Worlds. https://driftengine.dev/docs/worlds/hierarchical-detail Drawing each region of a world at the level its distance deserves, crossfading between levels, and baking proxies and impostors offline. A distant block of a city does not need its window fins, and a city drawn whole at its finest detail is more than a million triangles. Hierarchical detail draws each region of a world at the coarsest level that still looks right from where the camera is, and fades from one level to the next so nothing pops. The example is a city of 144 blocks flown over from street level to above the roofs. Paint the levels to watch them change as the camera climbs, loosen the tolerance to bring coarse levels closer, and switch the selection off to see what drawing every block at its finest costs. (This chapter runs the `hlod` example at https://driftengine.dev/docs/worlds/hierarchical-detail.) ## Levels and their errors ```ts /** * Sixteen buildings on a block of 100 metres, at three levels. The coarser two wear the facade's * average shade, so dropping the fins does not read as the city brightening. */ function block(ox: number, oz: number, random: () => number): MeshData[] { const fine = new MeshBuilder(); const plainer = new MeshBuilder(); const boxes = new MeshBuilder(); for (let lot = 0; lot < 16; lot += 1) { const cx = ox + 20 + (lot % 4) * 20; const cz = oz + 20 + Math.floor(lot / 4) * 20; const h = 12 + random() * 60; const grey = 0.45 + random() * 0.35; const wall: Vec3 = [grey, grey * 0.96, grey * 0.9]; const fin: Vec3 = [grey * 0.6, grey * 0.6, grey * 0.62]; const average: Vec3 = [wall[0] * 0.9, wall[1] * 0.9, wall[2] * 0.9]; fine.addBox([cx, h / 2, cz], [7, h / 2, 7], wall); fine.addBox([cx, h + 4, cz], [4.5, 4, 4.5], wall); for (let y = 4; y < h; y += 4) fine.addBox([cx, y, cz], [7.3, 0.15, 7.3], fin); for (let i = 0; i < 7; i += 1) { const along = -6 + i * 2; fine.addBox([cx + along, h / 2, cz - 7.2], [0.2, h / 2, 0.25], fin); fine.addBox([cx + along, h / 2, cz + 7.2], [0.2, h / 2, 0.25], fin); fine.addBox([cx - 7.2, h / 2, cz + along], [0.25, h / 2, 0.2], fin); fine.addBox([cx + 7.2, h / 2, cz + along], [0.25, h / 2, 0.2], fin); } plainer.addBox([cx, h / 2, cz], [7, h / 2, 7], average); plainer.addBox([cx, h + 4, cz], [4.5, 4, 4.5], average); boxes.addBox([cx, h / 2, cz], [7, h / 2, 7], average); } return [fine.build(), plainer.build(), boxes.build()]; } /** What each level claims: the fins stand half a metre out, the setbacks eight metres up. */ const ERRORS = [0, 0.5, 8]; ``` A region is a box and one or more levels, finest first. Each level states its geometric error: how far, in metres, its surface may stand from the real one. The example's middle level drops the fins, which stand half a metre proud of the walls, so it claims 0.5; the coarsest drops the setbacks on the roofs, which are eight metres tall, so it claims 8. A level is good enough once its error projects to fewer than `pixelTolerance` pixels on screen, so the distance at which it takes over is `error × projectionScale / pixelTolerance`. The file carries errors, and the distances follow from the screen: a distance would be a decision about one screen, and an error is a fact about the geometry. The coarser levels here wear the average shade of the finer one's facade. A level that drops dark detail and keeps the bright wall colour makes the city look as though it brightens as it recedes. ## Choosing a level for every region ```ts /** Twelve blocks by twelve, each a region: a box, its levels' meshes and their errors. */ const GRID = 12; const SIZE = 100; interface Region { levels: MeshHandle[]; triangles: number[]; } const regions: Region[] = []; const hlod = new HlodSet({ capacity: GRID * GRID, fadeSec: 0.4 }); const draws = createHlodDraws(GRID * GRID); const random = mulberry32(17); for (let id = 0; id < GRID * GRID; id += 1) { const ox = (id % GRID) * SIZE; const oz = Math.floor(id / GRID) * SIZE; const meshes = block(ox, oz, random); regions.push({ levels: meshes.map((mesh) => renderer.createMesh(mesh)), triangles: meshes.map((mesh) => mesh.indices.length / 3), }); hlod.add(id, [ox, 0, oz, ox + SIZE, 90, oz + SIZE], ERRORS); } ``` `new HlodSet(options)` holds the regions: - `capacity`, the most regions it holds at once. - `maxLevels`, the most levels a region may carry, 4 by default. - `pixelTolerance`, the pixels of error a level may show, 1.5 by default. - `hysteresis`, the band around each switch as a fraction of its distance, 0.15 by default. A region coarsens only once the camera is that much past the switch and refines only once it is that much inside, so a camera standing on a threshold, or wobbling across it, keeps the level it has. - `fadeSec`, how long a crossfade takes, 0.4 seconds by default. 0 switches at once. - `farDistance`, beyond which a region is drawn at no level at all. Unbounded by default. `add(id, box, errors)` adds a region: its box as minimum then maximum corner, and an error per level that never shrinks from finer to coarser. A region arrives at no level and fades into the first one chosen. `remove(id)` takes one out, `has(id)` and `levelOf(id)` ask about one, and `size` is how many there are. `HLOD_NONE` is the level of a region drawn at none of its own. ```ts /* Each block hides what is behind it, up to its lowest roofs. */ for (let id = 0; id < GRID * GRID; id += 1) { const ox = (id % GRID) * SIZE; const oz = Math.floor(id / GRID) * SIZE; renderer.addOccluder([ox + 13, 0, oz + 13], [ox + 87, 12, oz + 87], IDENTITY); } renderer.drawMesh(ground, IDENTITY); /* The switch distance is error · scale / tolerance, so a looser tolerance is a smaller scale. */ const scale = (projectionScaleOf(camera.fovYDeg, stage.canvas.height) * 1.5) / tolerance; const count = selecting ? hlod.select(eye, scale, frustum, renderer, dt, draws) : 0; shown.fill(0); let triangles = 0; const drawRegion = (id: number, level: number, dither: number): void => { const region = regions[id]; const mesh = region?.levels[level]; if (region === undefined || mesh === undefined) return; if (dither !== 0) renderer.setDitherFade(dither); renderer.drawMesh(mesh, IDENTITY, undefined, paint === 'levels' ? LEVEL_TINTS[level] : null); if (dither !== 0) renderer.setDitherFade(0); triangles += region.triangles[level] ?? 0; if (dither >= 0) shown[level] = (shown[level] ?? 0) + 1; }; if (selecting) { for (let i = 0; i < count; i += 1) drawRegion(draws.region[i] ?? 0, draws.level[i] ?? 0, draws.dither[i] ?? 0); } else { for (let id = 0; id < GRID * GRID; id += 1) drawRegion(id, 0, 0); } ``` `select(eye, projectionScale, frustum, occluder, dtSec, out)` decides every region's level for this view and writes what to draw into an `HlodDraws` from `createHlodDraws(capacity)`, returning how many draws there are. `projectionScaleOf(fovYDeg, heightPx)` is the pixels a metre spans at a metre's distance. Distance is measured to the region's box, so the region under the camera is always at its finest. A region outside the frustum, or hidden behind the occluders declared so far this frame when the renderer is passed as `occluder`, is skipped. Each draw carries a region, a level and a dither. A settled region is one draw with a dither of 0. A region changing level is two: the level arriving at `+t` and the one leaving at `-t`, and `setDitherFade` with those two amounts keeps complementary cells of a screen-door pattern, so the pair covers every pixel exactly once. Reset it to 0 after the draw. `t` runs over `fadeSec` of the `dtSec` you pass, so a held clock never finishes a fade, and a capture that holds the clock wants `fadeSec: 0`. A region is one decision, so a long region seen end-on is drawn all the way along at the level its nearest corner asks for. Smaller regions are the lever. ## Baking the levels Coarse levels can be authored, as the example's are, or baked. `@driftengine/assets` bakes two kinds offline, where nothing runs per frame. ### Proxies ```ts /** A yard of two hundred crates, and the one mesh that stands in for it from a distance. */ const random = mulberry32(3); const yard = new MeshBuilder(); for (let i = 0; i < 200; i += 1) { const x = random() * 40; const z = random() * 40; const s = 0.4 + random() * 0.6; yard.addBox([x, s, z], [s, s, s], [0.5, 0.4, 0.3]); } const crates = yard.build(); /** Level 1: a 16-cell outline. `null` when the outline would not be under half the crates' cost. */ export const yardProxy = buildProxy([{ id: 0, meshes: [crates] }], 1); ``` `buildProxy(cells, level)` merges a group of cells into one mesh by outlining the space they occupy on a grid: `proxyResolution(level)` cells along the longest axis, 32 at level 0 (`PROXY_BASE_CELLS`) and halving with each level down to 4 (`PROXY_MIN_CELLS`). Each `ProxyCell` is a cell's identifier from the [cell grid](https://driftengine.dev/docs/worlds/large-worlds) and its meshes. A proxy is a budget, so it can be refused. An outline's triangle count grows with the group's surface area, not with the triangles it replaces, so `buildProxy` returns `null` for a group whose outline would not be under half its cost, as well as for an empty group and one that does not span a cell of the grid. The yard of crates above outlines into 1,152 triangles against its 2,400. A block of plain towers is nearly all surface and outlines into more triangles than the towers, which is why the example's coarse levels are simpler versions of its own buildings. ### Impostors ```ts /** A tree baked as eight by eight pictures, one for each direction it may be seen from. */ const tree = new MeshBuilder() .addCylinder([0, 1.5, 0], 0.2, 1.5, 'y', [0.35, 0.25, 0.18]) .addSphere([0, 4, 0], 1.8, [0.2, 0.42, 0.18]) .build(); export const treePictures = buildImpostor(tree, 8); /** What the tree looks like from the east, at the middle of its picture: RGBA. */ export const fromTheEast = new Float32Array(4); sampleImpostor(treePictures, [1, 0, 0], 0.5, 0.5, fromTheEast); ``` `buildImpostor(mesh, directions)` renders a mesh from `directions × directions` directions, laid out octahedrally, into one RGBA atlas of `IMPOSTOR_TILE`-texel tiles. The `Impostor` carries the atlas, its size, the direction count and the `frame`, the sphere the views were framed on, which is what places the sprite it is drawn on. `frameOf(meshes)` computes that sphere, and `octahedralDirection` and `octahedralCoord` convert between a direction and its place in the atlas. The edges are the hard part. Colour is pushed outward past the silhouette and every tile carries a gutter of `IMPOSTOR_GUTTER` texels repeating its edge, so a filtered sample at the silhouette or at a tile's border never blends in the clear colour or the next direction's picture: a distant tree does not glow at its seams. `sampleImpostor(impostor, direction, u, v, out)` samples it as a shader would, blending the four tiles around a direction. There is no parallax correction, so between two baked directions a shape with depth ghosts slightly: measured on a tree at eight directions a side, the silhouette agrees exactly on a baked direction and to 0.91 between two. More directions cost their square. `rasteriseView` is the single-view renderer the bake uses. The engine bakes impostors and does not yet draw them view-dependently, which needs a sprite pipeline. A card impostor, one picture on a quad, is an ordinary level of a region. ## Regions in a container ```ts /** One block as a region in a container: its levels name the meshes they draw, finest first. */ const fine = new MeshBuilder().addBox([50, 30, 50], [7, 30, 7], [0.6, 0.6, 0.6]).build(); const coarse = new MeshBuilder().addBox([50, 30, 50], [7.3, 30, 7.3], [0.55, 0.55, 0.55]).build(); export const city = writeDrft({ head: { name: 'city' }, meshes: [fine, coarse], regions: [ { id: 0, bounds: [0, 0, 0, 100, 60, 100], levels: [ { error: 0, meshes: [0] }, { error: 0.5, meshes: [1] }, ], instances: [], occluders: new Float32Array([43, 0, 43, 57, 60, 57]), collision: null, }, ], }); ``` A `.drft` file carries regions in its `REGN` chunk: each region's id, box, levels as lists of mesh ordinals with their errors, its props as instanced groups drawn at its finest level, its occluder boxes, and its collision triangles. A region is written ahead of the meshes it introduces, so a loader knows what a mesh belongs to as it arrives. ```ts /** Stream the container; each region is handed over ahead of the meshes it draws. */ export async function openCity(renderer: RendererApi, url: string): Promise { const loader = new DrftLoader(renderer); await loader.load(url, { fit: 'none' }); return loader; } /** Once a frame: upload what has arrived, and admit each region whose meshes are all up. */ export function admitRegions(loader: DrftLoader, hlod: HlodSet, dtSec: number): void { loader.update(dtSec); for (const region of loader.regions.values()) { if (region.pending !== 0 || hlod.has(region.id)) continue; hlod.add( region.id, region.bounds, region.levels.map((level) => level.error), ); } } ``` `DrftLoader.regions` hands the regions over by id, kept apart and never merged into the rest of the model. Each `LoadedRegion` has its placed `bounds`, its `levels`, each with the `parts` to draw, its props as instanced `batches`, its `occluders` ready for `addOccluder`, and `pending`, the meshes and props still to arrive. Admit a region to the `HlodSet` once `pending` is 0. Measured on the engine's own test city, 1.2 kilometres across and seen from above, hierarchical detail takes the frame from 1.1 million triangles to 60 thousand and from 0.92 to 0.13 milliseconds of GPU time. --- # Worlds from a kit Worlds. https://driftengine.dev/docs/worlds/worlds-from-a-kit A world built from a few pieces placed many times, carried as its placements in a .drft, expanded by arithmetic, and paged in region by region. A city of boxes, columns and cornices is a few thousand distinct shapes placed hundreds of thousands of times, each at its own size and in its own paint. Merged into vertices it is most of a gigabyte; as placements of its pieces it is a few tens of megabytes. A `.drft` can carry a mesh either way, and a mesh carried as placements is expanded into ordinary geometry where it is needed. The example is a street built from three pieces, a box, a column and a sphere. Its figures say what the street weighs as placements and as vertices. Lengthen the street, or paint each copy by the piece it is, and save a change to the rules in `street.drs` to have the street built again. (This chapter runs the `kit` example at https://driftengine.dev/docs/worlds/worlds-from-a-kit.) ## Pieces, surfaces and copies ```ts /** The kit: three unit pieces. Their own colours are ignored; a copy's surface paints it. */ const WHITE: Vec3 = [1, 1, 1]; const PIECES: MeshData[] = [ new MeshBuilder().addBox([0, 0, 0], [0.5, 0.5, 0.5], WHITE).build(), new MeshBuilder().addCylinder([0, 0, 0], 0.5, 0.5, 'y', WHITE, 0, 12).build(), new MeshBuilder().addSphere([0, 0, 0], 0.5, WHITE, 0, 16, 8).build(), ]; const BOX = 0; const COLUMN = 1; const SPHERE = 2; /** The surfaces a copy can wear: four wall paints, glass, stone, copper and the road. */ const PAINTS: [Vec3, number][] = [ [[0.78, 0.66, 0.52], 0], [[0.7, 0.52, 0.42], 0], [[0.82, 0.78, 0.68], 0], [[0.58, 0.6, 0.62], 0], [[0.12, 0.15, 0.2], 0.7], [[0.86, 0.84, 0.8], 0.1], [[0.36, 0.6, 0.5], 0.4], [[0.22, 0.22, 0.24], 0], /* And one per piece, for painting the street by which piece each copy is. */ [[1, 0.5, 0.25], 0], [[1, 0.85, 0.3], 0], [[0.35, 0.6, 1], 0], ]; const GLASS = 4; const STONE = 5; const COPPER = 6; const ROAD = 7; const BY_PIECE = 8; const surfaces = new Float32Array(PAINTS.length * SURFACE_FLOATS); PAINTS.forEach(([colour, specular], i) => { surfaces.set(colour, i * SURFACE_FLOATS + SURFACE.color); surfaces[i * SURFACE_FLOATS + SURFACE.specular] = specular; }); ``` A piece is an ordinary mesh, usually of unit size. A piece is shape only: its colours, emissive and other per-vertex constants are ignored, and the copy's surface supplies them. A piece carries positions and normals, texture coordinates and tangents where the result is textured, and its own sway `channel` where the result sways, so a tree's sway rises from its root however it is placed. A surface is `SURFACE_FLOATS` (12) numbers, laid out as `SURFACE` names them: `color` at 0, `emissive` at 3, `specular` at 4, `emissiveColor` at 5, `roughness` at 8, `grain` at 9, `relief` at 10 and the texture-array `layer` at 11. Only the values the assembly's attributes ask for are read. ```ts /** Copies collected for one street, before they become an assembly. */ const pieces: number[] = []; const surfaceOf: number[] = []; const transforms: number[] = []; let paintByPiece = flag('paint', 'surfaces') === 'pieces'; /** One copy: a piece, a surface, and a box it fills, from its centre and its size on each axis. */ function place(piece: number, surface: number, centre: Vec3, size: Vec3): void { pieces.push(piece); surfaceOf.push(paintByPiece ? BY_PIECE + piece : surface); /* Three columns of the linear part, then the translation: a scale and a move. */ transforms.push(size[0], 0, 0, 0, size[1], 0, 0, 0, size[2], centre[0], centre[1], centre[2]); } /** Lots down both sides of the street, each a building the rules describe. */ function buildStreet(lots: number): DrftAssembly { pieces.length = 0; surfaceOf.length = 0; transforms.length = 0; const storeys = rule('storeys'); const bays = rule('bays'); const arcaded = rule('arcaded'); const domed = rule('domed'); const paint = rule('paint'); const along = [0, 0]; for (let lot = 0; lot < lots; lot += 1) { const side = lot % 2 === 0 ? -1 : 1; const width = bays(lot) * 3.2 + 1.6; const height = (storeys(lot) + 1) * 3.4; const z = (along[lot % 2] ?? 0) + width / 2; along[lot % 2] = z + width / 2 + 0.6; const front = side * 7; const middle = side * 13; const wall = paint(lot); place(BOX, wall, [middle, height / 2, z], [12, height, width]); place(BOX, STONE, [middle, height + 0.25, z], [12.6, 0.5, width + 0.3]); for (let floor = 1; floor <= storeys(lot); floor += 1) { for (let bay = 0; bay < bays(lot); bay += 1) { const across = z - width / 2 + 2.4 + bay * 3.2; place(BOX, GLASS, [front - side * 0.05, floor * 3.4 + 1.7, across], [0.2, 1.8, 1.4]); } } if (arcaded(lot)) { for (let column = 0; column <= bays(lot); column += 1) { const across = z - width / 2 + 0.8 + column * 3.2; place(COLUMN, STONE, [front - side * 1.6, 1.7, across], [0.5, 3.4, 0.5]); } place(BOX, STONE, [front - side * 1.2, 3.6, z], [2.8, 0.4, width]); } if (domed(lot)) place(SPHERE, COPPER, [middle, height + 0.5, z], [7, 7, 7]); } const length = Math.max(along[0] ?? 0, along[1] ?? 0); place(BOX, ROAD, [0, -0.1, length / 2], [60, 0.2, length + 40]); const copies = pieces.length; /* A stretch of one along each piece axis and no offset: untextured, so it changes nothing. */ const uv = new Float32Array(copies * COPY_UV_FLOATS); for (let c = 0; c < copies; c += 1) uv.set([1, 1, 1, 1, 1, 1, 0, 0], c * COPY_UV_FLOATS); return { attributes: 0, surfaces, pieces: Uint32Array.from(pieces), surfaceOf: Uint32Array.from(surfaceOf), transforms: Float32Array.from(transforms), uv, }; } ``` A `DrftAssembly` is the mesh described as copies: - `attributes`, the optional arrays the expanded mesh carries, as a `MESH`'s attribute bits (`ATTR_SPECULAR`, `ATTR_UVS`, `ATTR_TANGENT`, `ATTR_LAYERS`, `ATTR_CHANNEL` and the rest). `ASSEMBLY_ATTRIBUTES` is every bit an assembly may carry; skinning is not among them. - `surfaces`, the surface table. - `pieces` and `surfaceOf`, one piece and one surface a copy. - `transforms`, `COPY_MATRIX_FLOATS` (12) a copy: the three columns of the linear part, then the translation. - `uv`, `COPY_UV_FLOATS` (8) a copy: how far a texture coordinate stretches along each of the piece's three axes for u, the same for v, and an offset. One along every axis and no offset leave a piece's coordinates as they are. ## Expanding a copy ```ts /** The street as a mesh, built again whenever the rules, the length or the paint change. */ let mesh: MeshHandle | null = null; const readout = createReadout(renderer, 2); let lots = Number(flag('lots', '128')); function rebuild(): void { const assembly = buildStreet(lots); const expanded = expandAssembly(assembly, (ordinal) => PIECES[ordinal] as MeshData); const next = renderer.createMesh(expanded); if (mesh !== null) renderer.disposeMesh(mesh); mesh = next; const copies = assembly.pieces.length; /* What the file would carry: a surface table, then 88 bytes a copy. */ const placed = 12 + surfaces.byteLength + copies * (8 + (COPY_MATRIX_FLOATS + COPY_UV_FLOATS) * 4); const vertices = expanded.positions.byteLength + expanded.normals.byteLength + expanded.colors.byteLength + expanded.emissive.byteLength + (expanded.specular?.byteLength ?? 0) + expanded.indices.byteLength; readout.set(0, `${copies} COPIES OF ${PIECES.length} PIECES`); readout.set( 1, `PLACEMENTS ${(placed / 1e6).toFixed(2)} MB EXPANDED ${(vertices / 1e6).toFixed(2)} MB`, ); } ``` `expandAssembly(assembly, piece)` builds the `MeshData` the assembly describes, given a function that finds a piece by its mesh ordinal. Each copy's positions go through its matrix and its normals through the matrix's inverse transpose, so a slope stretched along one axis stays perpendicular to its surface. A copy whose matrix mirrors, with a negative determinant, has its triangles wound back and its tangents' handedness flipped, so its faces still face outward and a mirrored texture still lights the right way up. `assemblyBounds(assembly, piece, out)` gives the box the expanded mesh will fill without expanding it. A texture coordinate is stretched along the piece's own tangent, so one unit box can serve every box in a city: a copy 13 metres by 4 with stretches of its size over the texture's tile size repeats its facade in metres on every face. A stretch that varies across one face, as it does along a cone's side, comes out as the stretch at each vertex's own tangent. The rules for each building are a DriftScript module, which the page calls once a lot: ```drs // Floors above the ground, from two to seven. fn storeys(lot: u32) -> u32 { return 2 + random.index(lot, 6) } // Windows across the front, from three to five. fn bays(lot: u32) -> u32 { return 3 + random.index(lot + 101, 3) } // Two buildings in five stand on an arcade of columns. fn arcaded(lot: u32) -> bool { return random.unit(lot + 7) < 0.4 } // One in seven carries a dome. fn domed(lot: u32) -> bool { return random.unit(lot + 13) < 0.15 } // Which of the four wall paints a building wears. fn paint(lot: u32) -> u32 { return random.index(lot + 29, 4) } ``` ## In a container ```ts /** Two pieces, and a tower made of four copies of them: a body, a roof and two columns. */ const box = new MeshBuilder().addBox([0, 0, 0], [0.5, 0.5, 0.5], [1, 1, 1]).build(); const column = new MeshBuilder().addCylinder([0, 0, 0], 0.5, 0.5, 'y', [1, 1, 1]).build(); const surfaces = new Float32Array(2 * SURFACE_FLOATS); surfaces.set([0.8, 0.7, 0.6], SURFACE.color); surfaces.set([0.9, 0.9, 0.88], SURFACE_FLOATS + SURFACE.color); const UNSTRETCHED = [1, 1, 1, 1, 1, 1, 0, 0]; export const tower: DrftAssembly = { attributes: 0, surfaces, /* By mesh ordinal in the file: 0 is the box and 1 the column. */ pieces: Uint32Array.of(0, 0, 1, 1), surfaceOf: Uint32Array.of(0, 1, 1, 1), /* Per copy, the three columns of a scale and then where it stands. */ transforms: Float32Array.of( ...[10, 0, 0, 0, 30, 0, 0, 0, 10, 0, 15, 0], ...[11, 0, 0, 0, 1, 0, 0, 0, 11, 0, 30.5, 0], ...[0.6, 0, 0, 0, 4, 0, 0, 0, 0.6, -3, 2, 6], ...[0.6, 0, 0, 0, 4, 0, 0, 0, 0.6, 3, 2, 6], ), /* No texture to stretch: a stretch of one along every piece axis, and no offset, a copy. */ uv: Float32Array.of(...UNSTRETCHED, ...UNSTRETCHED, ...UNSTRETCHED, ...UNSTRETCHED), }; /** The mesh it describes, as a `MESH` would have carried it. */ export const expanded = expandAssembly(tower, (ordinal) => (ordinal === 0 ? box : column)); ``` ```ts /** The kit names the pieces; the assembly stands in a mesh slot like any other mesh. */ const block = new MeshBuilder().addBox([0, 15.5, 0], [5.5, 15.5, 5.5], [0.75, 0.68, 0.6]).build(); export const district = writeDrft({ head: { name: 'district' }, meshes: [box, column, tower, block], kit: [0, 1], regions: [ { id: 0, bounds: [-6, 0, -6, 6, 31, 7], levels: [ { error: 0, meshes: [2] }, { error: 1, meshes: [3] }, ], instances: [], occluders: new Float32Array(0), collision: null, }, ], texturesFirst: true, }); ``` `writeDrft` takes assemblies in `meshes`, where each stands in a mesh slot and counts as one in every ordinal, so materials and regions name it like any other mesh. `kit` lists the ordinals of the meshes that are pieces. Two chunks carry them: - `KITS` names the pieces and is written ahead of the geometry. A piece is drawn only inside the meshes assembled from it; without the list, a streaming reader would draw every piece at the origin. - `MSHC` carries an assembly: its attribute bits, its surface table, and 88 bytes a copy. Both are required, so a reader older than format 1.23 refuses such a file and names them. A piece travels with the first region that copies it, among that region's meshes and ahead of its assemblies, so the first regions a walker reaches arrive without the rest of the kit. `texturesFirst: true` writes the pictures ahead of all geometry, for a world whose materials must be ready before its first region; its first mesh then arrives later by the size of the pictures. Measured on a two-kilometre city of 18.7 million triangles in 579,164 copies of 7,308 pieces: with its coarse levels, collision, lights, scene and pictures the file is 123 MB, and the 14 regions within 150 metres of its spawn point are whole after the first 7.1 MB. `buildKit`, `readKit`, `buildAssembly`, `readAssembly`, `checkAssembly`, `checkCopies` and `isAssembly` are the chunk-level reader and writer `writeDrft` and `readDrft` use, for a tool that writes the chunks itself. ## Paging the finest level ```ts /** * Page a region's finest level in while the selection draws it, and out once the eye has left. * Until it is resident, the region is drawn at its next level. */ const paged = new Map(); export function pageFinest(loader: DrftLoader, hlod: HlodSet): void { for (const region of loader.regions.values()) { if (region.levels[0]?.paged !== true) continue; const wanted = hlod.levelOf(region.id) === 0; if (paged.get(region.id) === wanted) continue; paged.set(region.id, wanted); loader.pageRegion(region.id, 0, wanted); } } /** The level to draw for a region the selection put at `level`. */ export function drawnLevel(loader: DrftLoader, id: number, level: number): number { const region = loader.regions.get(id); if (level === 0 && region?.levels[0]?.resident === false) return 1; return level; } ``` `DrftLoader` keeps a region's level that arrived as assemblies small, as the copies the file carried, and marks it `paged`. `pageRegion(id, level, resident)` brings it up, expanding and uploading each mesh on the loader's clocked queue over the next `update`s and turning `resident` true when the last is up, or frees its meshes and keeps the copies. A level that is not paged ignores it. The game decides from what it will draw: page in the levels [`HlodSet`](https://driftengine.dev/docs/worlds/hierarchical-detail) is choosing, draw a coarser one until the fine one is resident, and page out what the eye has left. A reader of its own built on `streamDrft` is told the kit's pieces by `onKit` when `KITS` lands, each piece by `onPiece`, and each assembly by `onAssembly` with a lookup for its pieces, all of which have arrived by then. Without `onAssembly`, the stream expands an assembly itself and hands the result to `onMesh`. Two more options split a file between the loader and the game: - `onImage(name, image)` takes each picture as it decodes and the loader uploads none, for a game that packs every picture into a texture array of its own. Materials that name an image then draw untextured, which is the game's to answer. - `onMesh(mesh, ordinal)` is offered each mesh no region holds; return `true` to take it, and it is neither uploaded as a part nor merged. For meshes a game draws its own way, such as a crowd it instances and moves every frame. A taken mesh leaves its upload budget and fade to the game. --- # Procedural solids Worlds. https://driftengine.dev/docs/worlds/procedural-solids Closed solids built in code, from boxes and lathes to sweeps, combined by booleans, smoothed, painted and handed to the renderer as meshes. A baker that builds a city from templates, or a game that generates its own buildings, needs shapes it can combine: a wall with windows cut out of it, a tower with a doorway carved into its foot. The solids in core are closed surfaces with outward normals, and the booleans between them keep them closed. The example is a gatehouse built entirely in code. Change how many windows the wall has and how they are cut, and switch the round solids between faceted and smooth. (This chapter runs the `solids` example at https://driftengine.dev/docs/worlds/procedural-solids.) ## Shape before paint A `Solid` is shape alone: `positions`, `normals`, `uvs` and counter-clockwise `indices`. It has no colour, emissive or roughness yet, because booleans, smoothing and transforms are defined on shape, and carrying a dozen per-vertex channels through a boolean would mean deciding how each one interpolates across a cut. A finished solid is painted once with `solidToMesh(solid, colour, emissive)`, which returns the `MeshData` that `createMesh` takes. Solids are built at load or bake time, never per frame, so every function here allocates its result. Every primitive is closed except `solidQuad`, and the engine's tests check each one with the divergence theorem: its volume, measured from its surface, is the volume of the shape it claims to be. ## The primitives All of them are centred on the origin unless stated, take full extents and not half, give texture coordinates from 0 to 1 across each face or around and along a round one, and wind counter-clockwise seen from outside. | Solid | Shape | | -------------------------------------------------------- | --------------------------------------------------------------------------------------- | | `solidBox(x, y, z)` | A box, four vertices a face | | `solidRoundedBox(x, y, z, radius, segments)` | A box with every edge rounded | | `solidQuad(x, y)` | A single-sided plane in XY facing +Z, the one open solid | | `solidPrism(x, y, z, right)` | A triangular section in XY extruded along Z; `right` puts a right angle at its left end | | `solidExtrude(profile, height, centre)` | A polygon in XZ, convex or not, extruded up Y | | `solidSweep(profile, path, capEnds, up)` | A section swept along a polyline | | `solidCylinder(radius, length, segments, smooth)` | Along Y, capped | | `solidCone(radius, length, segments, smooth)` | Base at −length/2, apex at +length/2 | | `solidFrustum(bottom, top, length, segments, smooth)` | A cone with its top cut off | | `solidTube(radius, thickness, length, segments, smooth)` | A hollow cylinder along Y; four segments make a square frame | | `solidSphere(radius, segments, smooth)` | `segments` around, half as many from pole to pole | | `solidHemisphere(radius, segments, smooth)` | A dome toward +Y on a flat base at the origin | | `solidCapsule(radius, length, segments, smooth)` | A cylinder with hemispherical ends, along Y | | `solidTorus(major, minor, segments, sides, smooth)` | Around +Y | | `solidLathe(profile, segments, smooth)` | A profile of radius and height pairs, bottom to top, turned around +Y | | `solidIcosphere(radius, level, smooth)` | A subdivided icosahedron | `smooth` shares vertices around a round solid and gives it radial normals; without it each face has its own. A polygon handed to `solidExtrude` or `solidSweep` may be wound either way and may be concave: caps are ear-clipped. A sweep's frame at each point of the path keeps the section's x to the right and its y up, `up` being +Y unless stated. Its corners are not mitred, so a path that turns sharply wants more points. ```ts /** A plinth: an eight-pointed star in plan, extruded up 0.6 metres. */ const star: number[] = []; for (let i = 0; i < 16; i += 1) { const a = (i / 16) * Math.PI * 2; const r = i % 2 === 0 ? 6 : 4.6; star.push(Math.cos(a) * r, Math.sin(a) * r); } const plinth = solidExtrude(star, 0.6); /** A pavilion on it: a ring of wall, a dome, and a torus where the two meet. */ const drum = transformSolid(solidTube(4, 0.4, 3, 32), at(0, 2.1, 0)); const dome = transformSolid(solidHemisphere(4.1, 32), at(0, 3.6, 0)); const band = transformSolid(solidTorus(4.15, 0.22, 48, 10), at(0, 3.6, 0)); const pavilion = transformSolid(mergeSolids([plinth, drum, band]), at(-17, 0, 2)); const roof = transformSolid(dome, at(-17, 0, 2)); /** An urn turned on a lathe from a profile of radius and height pairs, bottom to top. */ const urn = transformSolid( solidLathe([0.5, 0, 0.7, 0.2, 0.9, 0.9, 0.6, 1.5, 0.45, 1.8, 0.65, 2.1], 24), at(-9, 0, 6), ); /** A rail swept along a curve in front of the wall: a small square section, both ends capped. */ const path: number[] = []; for (let i = 0; i <= 24; i += 1) { const x = -12 + i; path.push(x, 1 + Math.sin(i * 0.25) * 0.15, 4 + Math.cos(i * 0.2) * 0.8); } const rail = solidSweep([-0.08, -0.08, 0.08, -0.08, 0.08, 0.08, -0.08, 0.08], path, true); ``` `transformSolid(solid, model)` moves a solid by a column-major matrix. Normals go through the inverse transpose, so a unit cylinder scaled into a post is still lit as round, and a mirroring matrix reverses the winding so the result is not inside out. `mergeSolids(solids)` joins several into one without combining their volumes, `emptySolid()` is a solid with nothing in it, and `solidVolume(solid)` measures one. ## Booleans ```ts /** A round tower with a doorway carved into its foot: a capsule taken out of a cylinder. */ const shaft = transformSolid(solidCylinder(3, 14, 32), at(16, 7, 0)); const arch = transformSolid(solidCapsule(1.1, 1.8, 24), at(16, 1.4, 3)); const tower = mergeSolids([ solidSubtract(shaft, arch), transformSolid(solidCone(3.6, 4.5, 32), at(16, 16.25, 0)), ]); ``` `solidUnion(a, b)`, `solidSubtract(a, b)` and `solidIntersect(a, b)` combine any two closed solids by binary space partitioning, the method made well known by Evan Wallace's csg.js. Positions, normals and texture coordinates are interpolated wherever a plane splits a face, so a cut face keeps the texture of the face it was cut from. Only what the other operand reaches is split: a face clear of the other solid's bounds passes through whole. That keeps the end faces of a wall cut five times at two triangles each instead of eight, and took a cut city wall from 4.5 million triangles to 0.75 million. A face the other operand does reach is split along every plane of it that crosses the face, and nothing is merged again afterwards, so a heavily cut solid still grows. The pieces meet with T-junctions: closed as a surface, with an exact volume, but not edge for edge. Weld after a bake if that matters. ### Boxes on the axes ```ts /** The windows, as the script lays them out, cut out of a wall 24 metres long and 10.5 high. */ const layout = hostScript(wallScript); type Rule = (value: number) => T; function openings(count: number): [number, number, number, number, number, number][] { const perRow = exported>(layout, 'perRow')(count); const height = exported>(layout, 'windowHeight'); const width = exported>(layout, 'windowWidth'); const boxes: [number, number, number, number, number, number][] = []; let y = 1; for (let i = 0; i < count; i += 1) { const row = Math.floor(i / perRow); const column = i % perRow; if (column === 0 && row > 0) y += height(row - 1) + 0.5; const x = -12 + (24 / perRow) * (column + 0.5); const w = width(row) / 2; boxes.push([x - w, y, -1, x + w, y + height(row), 1]); } return boxes; } /** Boxes on the three axes: exact over the grid of their coordinates, faces merged. */ function cutByGrid(holes: [number, number, number, number, number, number][]): Solid { const operations: BoxOperation[] = [{ box: [-12, 0, -0.3, 12, 10.5, 0.3], op: 'union' }]; for (const box of holes) operations.push({ box, op: 'subtract' }); return solidBoxBoolean(operations); } /** The general boolean: any closed solid from any other, one subtraction at a time. */ function cutByBsp(holes: [number, number, number, number, number, number][]): Solid { let wall = transformSolid(solidBox(24, 10.5, 0.6), at(0, 5.25, 0)); for (const [x0, y0, z0, x1, y1, z1] of holes) { const hole = solidBox(x1 - x0, y1 - y0, z1 - z0); wall = solidSubtract( wall, transformSolid(hole, at((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2)), ); } return wall; } ``` Boxes that share the three axes need none of that. `solidBoxBoolean(operations)` applies a list of `BoxOperation`s, each a box as `[x0, y0, z0, x1, y1, z1]` and an `op` of `'union'`, `'subtract'` or `'intersect'`, from nothing, left to right. It splits space into the grid of every coordinate the boxes have, decides each cell by applying the operations to its centre, and builds the surface between cells that differ, merged into the largest rectangles that fit. The result is exact, and as few faces as it has: a wall with twenty openings is a few hundred triangles where the general boolean once made 325,187. The grid costs a byte a cell, so `boxBooleanCells(operations)` says how many it would allocate before a call with hundreds of boxes. The example's wall can be cut either way; the figures report the triangles and the time each took, and the volume, which agrees. How many windows a row holds and how big each row's are is a DriftScript module, so editing it under `npm run examples` cuts the wall again: ```drs // Openings across one row: all of them while there are few, ten at most. fn perRow(openings: u32) -> u32 { if openings < 10 { return openings } return 10 } // Tall windows at the bottom, squarer toward the top. fn windowHeight(row: u32) -> f32 { return math.max(2.2 - 0.3 * f32.nearest(row), 1.0) } fn windowWidth(row: u32) -> f32 { return math.min(1.0 + 0.1 * f32.nearest(row), 1.4) } ``` ## Smoothing and painting ```ts /** Every solid painted once and handed to the renderer; built again when a switch changes. */ function build(): void { for (const mesh of meshes) renderer.disposeMesh(mesh); meshes.length = 0; const holes = openings(count); const started = performance.now(); const wall = method === 'grid' ? cutByGrid(holes) : cutByBsp(holes); const took = performance.now() - started; const shade = (solid: Solid): Solid => (smooth ? smoothSolidNormals(solid, 40) : solid); const paint = (solid: Solid, colour: Vec3): void => { meshes.push(renderer.createMesh(solidToMesh(shade(solid), colour))); }; paint(wall, STONE); paint(tower, [0.66, 0.4, 0.32]); paint(pavilion, [0.86, 0.82, 0.74]); paint(roof, [0.32, 0.58, 0.5]); paint(urn, [0.5, 0.3, 0.2]); paint(rail, [0.2, 0.2, 0.24]); readout.set(0, `WALL ${wall.indices.length / 3} TRIANGLES IN ${took.toFixed(1)} MS`); readout.set(1, `VOLUME ${solidVolume(wall).toFixed(2)} CUBIC METRES`); } ``` `smoothSolidNormals(solid, creaseDeg)` averages each vertex's normal over the faces that meet at its position within the crease angle of its own, so a cylinder's side goes round while its rim stays sharp. The average is weighted by the angle each face makes at the vertex, not by its area, so it does not lean toward whichever side a quad happened to be split on. It changes normals only: the vertices, indices and texture coordinates are as they were. For a single object of a few parts, [`MeshBuilder`](https://driftengine.dev/docs/rendering/meshes) is shorter. Solids are for shapes that need cutting, joining or generating. --- # Gaussian splats Worlds. https://driftengine.dev/docs/worlds/splats Captured places drawn as hundreds of thousands of soft ellipsoids, composed into a scene of meshes, sorted off the frame and streamed in blocks. A splat capture is a photographed place drawn as several hundred thousand oriented, soft-edged ellipsoids. `@driftengine/splats` reads the files capture tools write, sorts the splats off the frame, and draws them as a pass that composes into a scene of ordinary meshes, so a lamp post you model stands among splats someone photographed. It costs 17.2 KB gzipped on top of core. The example is a rock garden synthesised from about sixty-six thousand flat splats, so the page needs no download, with a post of ordinary geometry standing in it. Switch the sort off to see what drawing in file order looks like, and the pool's view-dependent colour to see it flatten. (This chapter runs the `splats` example at https://driftengine.dev/docs/worlds/splats.) ## A capture ```ts /** * Splats gathered for one capture: where, how big along each axis, which way, what colour. A colour * is a display value, as a capture trained on photographs stores it, and the pass decodes it. */ const positions: number[] = []; const scales: number[] = []; const rotations: number[] = []; const colors: number[] = []; const opacities: number[] = []; const shine: number[] = []; /** The quaternion, xyzw, that turns +z onto a unit normal: a flat splat lies along the surface. */ function facing(nx: number, ny: number, nz: number): [number, number, number, number] { const w = 1 + nz; if (w < 1e-6) return [1, 0, 0, 0]; const length = Math.hypot(-ny, nx, 0, w); return [-ny / length, nx / length, 0, w / length]; } /** One flat splat on a surface: wide along it, thin across it. */ function lay(at: Vec3, normal: Vec3, size: number, colour: Vec3, opacity: number, sheen = 0): void { positions.push(...at); scales.push(size, size, size * 0.12); rotations.push(...facing(normal[0], normal[1], normal[2])); colors.push(...colour); opacities.push(opacity); shine.push(sheen); } /** A rock: points spread evenly over a lumpy ellipsoid, stone below and moss where it faces up. */ function rock(cx: number, cz: number, rx: number, ry: number, rz: number, seed: number): void { const count = Math.round(6000 * rx * rz); for (let i = 0; i < count; i += 1) { const y = 1 - (2 * (i + 0.5)) / count; const ring = Math.sqrt(1 - y * y); const a = i * 2.399963; const nx = Math.cos(a) * ring; const nz = Math.sin(a) * ring; const lump = 1 + (hashToUnit(seed + Math.floor(a * 3) * 17 + Math.floor(y * 6)) - 0.5) * 0.18; if (y < -0.2) continue; const grey = 0.63 + hashToUnit(seed * 7 + i) * 0.1; const moss = Math.max(0, y - 0.55) * 2.2 * hashToUnit(seed * 13 + i); const colour: Vec3 = [grey - moss * 0.15, grey + moss * 0.12, grey - moss * 0.17]; lay([cx + nx * rx * lump, y * ry * lump, cz + nz * rz * lump], [nx, y, nz], 0.07, colour, 0.9); } } /** The ground: a disc of soil and grass, and a pool in it whose colour changes with the view. */ for (let i = 0; i < 52000; i += 1) { const r = Math.sqrt((i + 0.5) / 52000) * 9; const a = i * 2.399963; const x = Math.cos(a) * r; const z = Math.sin(a) * r; const pool = Math.hypot(x - 2.2, z + 1.2) < 1.8; const tone = hashToUnit(i * 3); const colour: Vec3 = pool ? [0.25, 0.38 + tone * 0.04, 0.44] : [0.44 + tone * 0.09, 0.48 + tone * 0.17, 0.31 + tone * 0.07]; lay( [x, pool ? -0.05 : tone * 0.04, z], [0, 1, 0], 0.075, colour, pool ? 0.85 : 0.95, pool ? 1 : 0, ); } rock(-2.2, -1.5, 1.4, 1.1, 1.2, 11); rock(-0.4, 1.6, 0.9, 0.7, 0.8, 23); rock(-3.6, 1.8, 0.7, 1.3, 0.6, 37); rock(3.4, 2.4, 1, 0.6, 1.1, 41); ``` Each splat is a Gaussian: a position, a standard deviation along each of its own three axes, a rotation, a colour and an opacity. A `SplatSource` holds them as flat arrays: three numbers a splat for `positions` and `scales`, four for `rotations` in **xyzw** order, three for `colors` from 0 to 1, and one for `opacities`, already through the logistic. A colour is a display value, as a capture trained on photographs stores it, and the pass decodes it after the view-dependent band, so a capture draws as it does in the tool that made it. Both common file formats store rotations as wxyz, and the readers turn them round. ```ts /** * The same splats packed twice: once with flat colour, and once with the first band of * view-dependent colour on the pool, nine coefficients a splat, interleaved by basis function. */ const count = opacities.length; const source = { count, positions: new Float32Array(positions), scales: new Float32Array(scales), rotations: new Float32Array(rotations), colors: new Float32Array(colors), opacities: new Float32Array(opacities), }; const sh1 = new Float32Array(count * 9); for (let i = 0; i < count; i += 1) { const sheen = shine[i] ?? 0; /* Brighter and bluer seen from one side of the pool, darker from the other. */ sh1[i * 9 + 6] = 0.25 * sheen; sh1[i * 9 + 7] = 0.35 * sheen; sh1[i * 9 + 8] = 0.45 * sheen; } const flat = packSplats(source); const glossy = packSplats({ ...source, sh1 }); ``` `packSplats(source)` packs a source into `SplatData`, the record the GPU reads and the `SPLT` chunk of a `.drft` carries: eight 32-bit words a splat (`SPLAT_WORDS`), as two texels. The first holds the position and the colour; the second, the splat's covariance in half precision, computed once from its scales and rotation since it cannot change. A sort reads the positions, so they stay full precision. The splats of a capture cannot move: that is a scene the format does not express. ### Colour that changes with the view A capture from a training run stores colour as a spherical-harmonic expansion: a constant term for the colour from every angle, and bands above it for how that colour changes as you move past. The first band is read and the rest are not. `sh1` takes nine numbers a splat (`SPLAT_SH1_COEFFICIENTS`), interleaved by basis function and then by channel, and packs them into one extra texel a splat (`SPLAT_WORDS_SH1`, twelve words). That is a decision with numbers behind it. The first band is 288 bytes a splat a frame against 192, which at a mobile budget of 400,000 splats is 115 MB a frame against 77; the second and third bands would be 192 MB and 307 MB, on a phone already moving about 389 MB a frame for everything else. The broad directional lobe that lets glass and a wet floor read as themselves ships; the sharp specular bands do not. A capture without harmonics pays nothing. ## From files ```ts /** A capture from a file: a `.ply` from training, a `.splat`, or a `.sog` bundle of WebP images. */ export async function readCapture(url: string): Promise { const bytes = await (await fetch(url)).arrayBuffer(); if (url.endsWith('.ply')) return readSplatPly(bytes); if (url.endsWith('.splat')) return readSplat(bytes); return readSplatSog(await unbundleSog(bytes), browserWebpDecoder()); } ``` - `readSplatPly(buffer)` reads the `.ply` a training run writes, including its first harmonic band. - `readSplat(buffer)` reads a `.splat`, a whole number of `SPLAT_RECORD_BYTES` records. - `.sog` is a ZIP of lossless WebP images and a manifest. `unbundleSog(bundle)` unpacks it to files, `readSplatSog(files, decode)` decodes them, and `browserWebpDecoder()` is the decoder a browser provides; Node has none, so a tool passes its own. A capture already unbundled into a directory, a `meta.json` beside its images, starts at `readSplatSog`. `readSogMeta` and `readSogSource` are the two halves, for checking what was decoded before it was packed. `SOG_VERSION` is the manifest version the reader accepts. ## Composing into the scene ```ts /** Each packing as a pass registered with the renderer, and the version of the order it holds. */ interface Batch { readonly pass: SplatPass; readonly handle: PassHandle; uploaded: number; } function batch(data: SplatData, label: string): Batch { const pass = createSplatPass(data, label); return { pass, handle: renderer.registerPass(pass), uploaded: -1 }; } const batches = { flat: batch(flat, 'garden.flat'), glossy: batch(glossy, 'garden.glossy') }; /** One sorter serves both, since their splats stand in the same places. It sorts in a worker. */ const sorter = new SplatSorter({ splats: flat }); /** File order, for the switch that turns the sort off. */ const unsorted = Uint32Array.from({ length: count }, (_, i) => i); const local = createSplatViewLocal(); const IDENTITY = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); ``` `createSplatPass(data, label)` makes a pass, and `renderer.registerPass(pass)` hands it to the renderer, which calls its `init` and returns the handle `drawPass` takes. Splats reach the frame through the renderer's pass seam, not a verb of its own, which is why they are a package. ```ts const shown = viewDependent ? batches.glossy : batches.flat; /* The view first, because it decides whether the capture is in frame at all. */ shown.pass.setView({ view: camera.view, projection: camera.projection, widthPx: stage.canvas.width, heightPx: stage.canvas.height, }); if (!sorting) { if (shown.uploaded !== -2) shown.pass.setOrder(unsorted, count); shown.uploaded = -2; } else if (shown.pass.visible) { /* The camera in the capture's own space; the sorter asks for a new order when it has moved. */ resolveSplatView(camera.view, IDENTITY, local); sorter.frame(local); const order = sorter.order; if (order !== null && sorter.version !== shown.uploaded) { shown.pass.setOrder(order, sorter.drawCount); shown.uploaded = sorter.version; } } renderer.beginFrame(SKY); renderer.bindMeshPass(camera, env); renderer.drawMesh(post, IDENTITY); /* After the meshes, so the post hides the splats behind it and not those in front. */ renderer.drawPass(shown.handle); ``` Each frame: 1. `pass.setView({ view, projection, widthPx, heightPx })` with the camera's matrices and the canvas size in pixels. It decides whether the capture is in frame at all, as `pass.visible`. 2. When it is visible, `resolveSplatView(camera.view, model, local)` puts the camera into the capture's own space, in a `SplatViewLocal` from `createSplatViewLocal()`, and the sorter's `frame(local)` asks for a new order if the view has moved enough. 3. When a new order has landed, which `sorter.version` says, `pass.setOrder(order, count)` uploads it. Four bytes a splat, so it is uploaded when it changes and not every frame. 4. `renderer.drawPass(handle)` after the meshes, so geometry in front of the splats hides them and geometry behind does not. Splats test depth and never write it: a Gaussian has no surface to hide anything with. Until it has an order, a pass draws nothing, since a capture composited in the wrong order is wrong at every edge. `pass.setModel(matrix)` places a capture in the world; a sorter sorts in the capture's own space, so one transform on the camera replaces a million on the splats. `splatBoundsVisible` is the frustum test `setView` uses. Two captures are two passes and two orders, with no order between them: each is drawn whole, one after the other. Where they occupy different volumes, a statue and the room around it, nothing shows. Where they interpenetrate, the seam is a plane at which one starts winning every blend. ### The sort, off the frame Splats are transparent and draw back to front, and the order changes whenever the camera moves. Sorting hundreds of thousands inside a frame is what makes a naive renderer stall, so a `SplatSorter` sorts in a worker and the pass draws whatever order it last received. A fast camera move draws a slightly stale order for a frame or two, which reads as a soft settle and never as a stall. `new SplatSorter({ splats })` builds its worker from a `Blob`, falling back to the main thread where a worker cannot be made. `sort` replaces it with any `SplatSortFn`: one is handed a `SplatSortRequest` and a `SplatSortScratch` it reuses, and answers a `SplatSortResult`. `sortSplatsByDepth` is the sort itself, a counting sort over a sixteen-bit depth key (`SPLAT_SORT_BUCKETS`, with `SPLAT_SIZE_BUCKETS` for ranking by size under a budget), and `sortOnMainThread` and `createDefaultSplatSort` are the two ready-made functions. `sorter.sorting` says whether a sort is in flight. ## A budget for weaker GPUs ```ts /** At most as many splats as this GPU family is known to hold, the largest on screen kept. */ export function budgetedSorter(renderer: RendererApi, splats: SplatData): SplatSorter { return new SplatSorter({ splats, budget: defaultSplatBudget(renderer.rendererName) }); } ``` `budget` caps how many splats a sorter hands the pass, keeping those largest on screen, and with a budget the sorter also re-sorts only when the camera has moved a tenth of the capture's size, which `moveFraction` overrides. `defaultSplatBudget(rendererName)` answers 400,000 (`SPLAT_BUDGET_DEFAULT`), or 120,000 (`SPLAT_BUDGET_WEAK`) on a GPU family measured to struggle. Too low a budget draws a sparser cloud and nothing worse; a game holding a measurement of its own should pass that. ## Streaming a capture ```ts /** * A capture that fills as its blocks arrive. The first block names the final count, so the * capture and its pass are sized once, and every block after is a sub-upload. */ export function streamCapture( renderer: RendererApi, onReady: (pass: SplatPass, sorter: SplatSorter) => void, ): DrftStream { let capture: SplatCapture | null = null; let pass: SplatPass | null = null; return new DrftStream({ onSplats: (block: DrftSplatBlock) => { if (capture === null) { const filling = new SplatCapture({ total: block.totalCount, boundsMin: block.boundsMin, boundsMax: block.boundsMax, sphericalHarmonics: block.sphericalHarmonics, wordsPerSplat: block.wordsPerSplat, }); capture = filling; pass = createSplatPass(filling.data, 'streamed'); renderer.registerPass(pass); /* The sorter orders what has arrived, and nothing of the zeroed tail still to come. */ onReady(pass, new SplatSorter({ splats: filling.data, ready: () => filling.ready })); } const landed = capture.append(block.records, block.count); pass?.uploadSplats(landed.from, landed.count); }, }); } ``` A `.drft` carries a capture in up to sixteen `SPLT` blocks, coarse-ordered so the first block draws the whole place thinly and the rest fill it in. Measured on a 332 KB capture: the first block is 662 splats in 24 KB, and it draws the whole room, not a corner of it. A `SplatCapture` is allocated at the final count the first block names and filled as blocks arrive: `append(records, count)` says where a block landed, and `pass.uploadSplats(from, count)` sends just those rows. The sorter is told `ready: () => capture.ready`, so it orders what has arrived and never the zeroed tail still to come. `splatsFromRecords` assembles a capture from a file that was read whole. --- # DriftTexture Worlds. https://driftengine.dev/docs/worlds/drifttexture Textures as small programs over a latent image, decoded per pixel on the GPU and on the CPU alike, animated by the simulation's clock and carried in .drft. A DriftTexture is a material's maps as a small program over a latent image, not as pictures. The program is a few four-word instructions: sample the latent, run a small network over it, add noise, mix by time, remap a channel's convention. It runs per shaded pixel on the GPU and, word for word, in `decodeCpu` on the CPU, which is the reference the device is checked against. `@driftengine/texture` is the format, the reference interpreter and the residency that streams it, for 2,304 bytes gzipped and no renderer. The device interpreter lives in core's [GPU-driven pipeline](https://driftengine.dev/docs/rendering/gpu-driven), so DriftTexture materials draw on WebGPU. The example is four materials: bricks and a metal chequer encoded from channels written in code, a marble that is noise and a colour, and a panel whose glow the simulation's clock animates. Hold the clock and the panel stops while the camera carries on. (This chapter runs the `drifttexture` example at https://driftengine.dev/docs/worlds/drifttexture.) ## Why a program **One object a material, not one a channel.** A material's albedo, roughness and normal are three descriptions of the same scratches and wear. Encoding them apart pays for that structure three times; encoding them together fits one latent every channel decodes from. **Time is an argument.** The decoder takes `t` from its caller, which is the simulation's clock, so an animated texture replays byte for byte. The engine's tests assert it three ways: a run sampling an animated texture every tick fingerprints identically to a run sampling nothing, the same simulation run twice at different wall-clock times fingerprints identically, and a decoder reading a wall clock instead is shown to diverge, so the first two cannot pass by accident. **The decoder is data, not shader permutations.** A program is four words a node in a buffer, walked by one shader. A new operation is one more case in one switch, and a thousand materials are a thousand programs and still one pipeline. **Conventions are declared, so nothing downstream guesses.** A channel says it is an sRGB albedo, a Y-down tangent-space normal or a gloss, and comes back linear, Y-up and as roughness. The sRGB curve is the exact one: the midpoint linearises to 0.2140, not the 0.2176 of the 2.2 approximation. ## The program ```ts /** A marble: five octaves of noise, with a warm white laid over it at half strength. */ const marbleGraph = createDecodeGraph(3); addDecodeNode(marbleGraph, DECODE_OP.PROCEDURAL_FBM, 7, 5, 0); addDecodeNode(marbleGraph, DECODE_OP.CONSTANT, 0, 0, 1); addDecodeNode(marbleGraph, DECODE_OP.COMPOSITE, 1, 0, 2); marbleGraph.result = 2; marbleGraph.addressMode = ADDRESS_MODE.CENTRE_WRAP; const marbleConstants = Float32Array.of(0.95, 0.9, 0.82, 0.55); /** A glow that sweeps from amber to blue once a second of the time it is given. */ const glowGraph = createDecodeGraph(3); addDecodeNode(glowGraph, DECODE_OP.CONSTANT, 0, 0, 0); addDecodeNode(glowGraph, DECODE_OP.CONSTANT, 1, 0, 1); addDecodeNode(glowGraph, DECODE_OP.LATENT_LERP, 0, 1, 2); glowGraph.result = 2; const glowConstants = Float32Array.of(1, 0.55, 0.15, 1, 0.2, 0.45, 1, 1); /** A graph and its constants, as the device's program: no latent and no network to carry. */ const procedural = (graph: DecodeGraph, constants: Float32Array): GpuDrivenProgram => ({ graph, latents: [], networks: [], constants, }); ``` `createDecodeGraph(capacity)` makes an empty program and `addDecodeNode(graph, op, a, b, out)` appends an instruction writing register `out`, of which there are `MAX_REGISTERS` (16), each four components. `result` names the register holding the finished value, and `addressMode` says where coordinates land, as one of `ADDRESS_MODE`: - `ADDRESS_MODE.LATTICE_CLAMP` and `ADDRESS_MODE.LATTICE_WRAP` put `u = 0` on the first texel's centre, which a heightfield sampled at its own vertices wants. - `ADDRESS_MODE.CENTRE_CLAMP` and `ADDRESS_MODE.CENTRE_WRAP` put it on the first texel's edge, as every GPU sampler does, which a surface tiled across a mesh wants. The instructions: | Operation | `a` | `b` | Writes | | -------------------------- | ------------------ | --------------------- | --------------------------------------------------- | | `DECODE_OP.SAMPLE_LATENT` | a latent slot | | The latent at (u, v) | | `DECODE_OP.EVAL_NETWORK` | the input register | a network slot | The network's outputs | | `DECODE_OP.SAMPLE_BLOCK` | a block slot | | Raw bytes at (u, v): an ordinary picture | | `DECODE_OP.PROCEDURAL_FBM` | a seed | octaves | Fractal noise, in all three colour lanes | | `DECODE_OP.FLIPBOOK_INDEX` | frames | frames per second | The frame the time lands on, looping | | `DECODE_OP.LATENT_LERP` | a register | a register | The two mixed by the fractional part of the time | | `DECODE_OP.REMAP_CHANNEL` | a register | a packed channel spec | That register with one channel's convention applied | | `DECODE_OP.COMPOSITE` | a register | a register | `a` over `b`, by `a`'s alpha | | `DECODE_OP.CONSTANT` | a constant slot | | Four numbers from the program's constants | `validateDecodeGraph(graph)` returns `null` for a program an interpreter can run and a message for one it cannot: an unknown operation, a register out of range, a register read before anything wrote it, a result nothing writes. `graphRegisterCount`, `nodeOp`, `nodeA`, `nodeB` and `nodeOut` read a program back, and `encodeDecodeGraph` and `decodeDecodeGraph` turn one into words and back. ### On the CPU ```ts /** * Noise read as gloss, which the remap hands back as roughness: a channel says what convention it * was authored in, and comes back in the one the renderer uses. */ const graph = createDecodeGraph(2); addDecodeNode(graph, DECODE_OP.PROCEDURAL_FBM, 3, 4, 0); const gloss = (REMAP_SEMANTICS.indexOf('gloss-linear') << 4) | 0; addDecodeNode(graph, DECODE_OP.REMAP_CHANNEL, 0, gloss, 1); graph.result = 1; graph.addressMode = ADDRESS_MODE.CENTRE_WRAP; /** `null` for a graph an interpreter can run; otherwise what is wrong with it. */ export const problem = validateDecodeGraph(graph); /** The roughness at one point, at simulation time zero. Registers are reused between calls. */ const registers = createDecodeRegisters(); export const roughness = new Float32Array(4); decodeCpu(graph, { latents: [], blocks: [], networks: [] }, 0.25, 0.75, 0, roughness, registers); ``` `decodeCpu(graph, resources, u, v, t, out, registers, lod)` runs a program at one point and writes the four-component result. `resources` holds the `latents`, `blocks`, `networks` and `constants` the program's slots name; `registers` comes from `createDecodeRegisters()` and is reused so a decode allocates nothing. `lod` picks a mip level, so the GPU's trilinear sample has a reference at every level. A channel spec for `DECODE_OP.REMAP_CHANNEL` packs a semantic's index in `REMAP_SEMANTICS` above its component: `(index << 4) | component`. The semantics are `CHANNEL_SEMANTICS`: `albedo-srgb`, `albedo-linear`, `normal-tangent-yup`, `normal-tangent-ydown`, `roughness-linear`, `gloss-linear`, `metallic-linear`, `occlusion-linear`, `height-linear`, `emissive-srgb` and `mask-linear`. `semanticIndex` and `semanticAt` convert, `isColour` and `needsVarianceMips` say which need a transfer curve or a normal-preserving mip, and `srgbToLinear`, `linearToSrgb` and `normaliseSample` are the conversions themselves. ### On the GPU ```ts /** Material 0 is the ground; the rest wear DriftTexture programs. A cube's faces span 0 to 1, so a scale of three tiles the bricks three times across each face. */ const materials: GpuDrivenMaterial[] = [ { tint: [0.4, 0.42, 0.38], emissive: 0, roughness: 0.9 }, { tint: [1, 1, 1], emissive: 0, roughness: 0.85, textures: { baseColour: programFromEncoded(bricks.baseColour), normal: programFromEncoded(bricks.normal), uScale: 3, vScale: 3, }, }, { tint: [1, 1, 1], emissive: 0, roughness: 1, textures: { baseColour: programFromEncoded(chequer.baseColour), orm: programFromEncoded(chequer.orm), uScale: 1, vScale: 1, }, }, { tint: [1, 1, 1], emissive: 0, roughness: 0.3, textures: { baseColour: procedural(marbleGraph, marbleConstants), uScale: 1, vScale: 1 }, }, { tint: [0.8, 0.8, 0.8], emissive: 1.2, roughness: 0.5, textures: { emissive: procedural(glowGraph, glowConstants) }, }, ]; ``` A [GPU-driven](https://driftengine.dev/docs/rendering/gpu-driven) material takes `textures`: a `GpuDrivenProgram` for any of `baseColour`, `normal`, `orm` (occlusion, roughness and metallic in R, G and B) and `emissive`, with `uScale` and `vScale` to tile them and the strengths `SurfaceMaterial` has. A program is a graph and its resources in bytes: `latents`, `blocks`, `networks` and `constants`. `programFromEncoded(encoded)` builds one from an encoded material, and `packDecodeTables` is what the pass flattens every material's programs into. A material with no programs draws exactly as it did without them. ```ts /* The decode reads this, never a clock of its own, so a held or replayed time decodes alike. */ view.time = decodeTime; decodeCpu(glowGraph, glowResources, 0.5, 0.5, decodeTime, sampled, registers); ``` The pass reads the time an animated program samples from its view's `time`, in seconds of the simulation's clock, never from a clock of its own. ## Encoding a material ```ts /** Channels written in code, 64 texels square, then encoded jointly into one latent. */ const SIZE = 64; function channel( semantic: ChannelInput['spec']['semantic'], component: number, value: (x: number, y: number) => number, ): ChannelInput { const data = new Float32Array(SIZE * SIZE); for (let y = 0; y < SIZE; y += 1) for (let x = 0; x < SIZE; x += 1) data[y * SIZE + x] = value(x, y); return { spec: { semantic, component }, data }; } /** Tiling, full resolution, addressed at texel centres: what a surface texture wants. */ const encode = (channels: readonly ChannelInput[]): EncodedMaterial => encodeMaterial(channels, SIZE, SIZE, { quality: 1, addressMode: ADDRESS_MODE.CENTRE_WRAP }); /** Courses of bricks: their colour, and a normal that turns at the mortar. */ const mortar = (x: number, y: number): boolean => y % 16 < 2 || (x + ((y >> 4) & 1) * 16) % 32 < 2; const bevel = (offset: number): number => (offset === 2 ? 0.55 : offset === 31 ? -0.55 : 0); const nx = (x: number, y: number): number => bevel((x + ((y >> 4) & 1) * 16) % 32); const ny = (_x: number, y: number): number => bevel(y % 16 === 2 ? 2 : y % 16 === 15 ? 31 : 0); const bricks = { baseColour: encode([ channel('albedo-linear', 0, (x, y) => (mortar(x, y) ? 0.7 : 0.55)), channel('albedo-linear', 1, (x, y) => (mortar(x, y) ? 0.68 : 0.22)), channel('albedo-linear', 2, (x, y) => (mortar(x, y) ? 0.64 : 0.15)), ]), normal: encode([ channel('normal-tangent-yup', 0, (x, y) => nx(x, y) * 0.5 + 0.5), channel('normal-tangent-yup', 1, (x, y) => ny(x, y) * 0.5 + 0.5), channel( 'normal-tangent-yup', 2, (x, y) => Math.sqrt(Math.max(0, 1 - nx(x, y) ** 2 - ny(x, y) ** 2)) * 0.5 + 0.5, ), ]), }; /** A chequer of polished metal and rough stone: colour, and occlusion, roughness and metal. */ const tone = (x: number, y: number): number => ((x >> 3) + (y >> 3)) & 1; const chequer = { baseColour: encode([ channel('albedo-linear', 0, (x, y) => (tone(x, y) ? 0.85 : 0.25)), channel('albedo-linear', 1, (x, y) => (tone(x, y) ? 0.8 : 0.3)), channel('albedo-linear', 2, (x, y) => (tone(x, y) ? 0.7 : 0.35)), ]), orm: encode([ channel('occlusion-linear', 0, (x, y) => (x % 8 === 0 || y % 8 === 0 ? 0.45 : 1)), channel('roughness-linear', 1, (x, y) => (tone(x, y) ? 0.25 : 0.85)), channel('metallic-linear', 2, (x, y) => (tone(x, y) ? 0.6 : 0)), ]), }; ``` `encodeMaterial(channels, width, height, options)` in `@driftengine/assets` fits one latent for a set of channels, each a `ChannelInput`: a `ChannelSpec` of semantic and component, and its values. `quality` from 0 to 1 sets the latent's resolution, an eighth of the source up to all of it, and `addressMode` how it tiles. The result, an `EncodedMaterial`, carries the latent and its mips, a small network and the two-node program that samples one and evaluates the other. The fit is a principal-component basis over the channel vectors: exact, deterministic and cheap. Channels that move together share a component, and a component is kept only where it explains enough of the channels to be worth its bytes, at most three. A sandstone whose three colour channels rise and fall together encodes into a single component. Normal maps get rougher toward their small mips instead of sparkling: the encoder writes the disagreement between four averaged normals into roughness, which is why both live in one object (`reduceNormalMip`, `toksvigRoughness`). A network is evaluated by `evalNetwork`, and by `evalNetworkHalf` at the half precision a device runs, with `halfPrecisionErrorBound` saying how far the two may differ. `@driftengine/texture` also exports the tensor operations its networks are built from, for a caller with a network of its own. `latentImageOf(encoded)` gives the latent as the CPU decoder reads it. ## In a `.drft` ```ts /** Three channels of a sandstone written in code, encoded jointly, and carried as a `DTEX`. */ const SIZE = 32; const band = (y: number): number => 0.5 + 0.5 * Math.sin(y * 0.6); const sandstone: ChannelInput[] = [0.78, 0.6, 0.42].map((base, component) => ({ spec: { semantic: 'albedo-linear', component }, data: Float32Array.from({ length: SIZE * SIZE }, (_, i) => Math.min(1, base * (0.8 + 0.3 * band(Math.floor(i / SIZE)))), ), })); const encoded = encodeMaterial(sandstone, SIZE, SIZE, { quality: 0.5, addressMode: ADDRESS_MODE.CENTRE_WRAP, }); export const file = writeDrft({ head: { name: 'sandstone' }, meshes: [new MeshBuilder().addBox([0, 1, 0], [1, 1, 1], [1, 1, 1]).build()], materials: [STONE], /* Paired to its MATL entry by index, so a file may carry programs for some materials only. */ dtex: [ { material: 0, texture: dtexFromEncoded( encoded, sandstone.map((c) => c.spec), ), }, ], }); /** Read back: the chunk is data, and decoding it is the texture package's job. */ export const carried = readDrft(file).dtex; /** The same latent as the decoder's input, for checking a bake against its source. */ export const latent = latentImageOf(encoded); ``` `dtexFromEncoded(encoded, channels, tileSize)` turns an encoded material into a `DtexMaterial`, and `writeDrft` carries each in a `DTEX` chunk paired to a `MATL` entry by the index it names, so a file may carry programs for some materials and plain maps for the rest. The chunk holds the latent, what each channel is, the program, the network's shape and weights, and a tile table. The tile table is the streaming unit. With a `tileSize`, the latent is stored tile by tile and each tile carries a 64-bit content hash, so two identical tiles anywhere in a bake share one payload and a tile resident for one material is resident for every material sharing it. `tileGridFromDtex` and `dtexTileBytes` read the table back for streaming. The chunk validates containment, not meaning: a tile whose bytes run past the payload and a result register no node writes are refused, since either would hand a reader arbitrary memory or an uninitialised value. Whether a program runs is `validateDecodeGraph`'s question. The chunk is additive, so an older reader skips it by its length and loses only a material it could not have decoded. `DTEX_REGISTERS`, `DTEX_ADDRESS_MODES` and `DTEX_MAX_TILES` are its limits. ## Texture arrays and materials WebGPU has no bindless textures, so a thousand materials as six thousand textures is out of reach. DriftTexture materials bind as slices of a few arrays: `createMaterialArray` holds them, `assignLayer` gives a latent its layer, sharing one between identical content, and `layerOf` and `arrayDescriptor` describe the result. `hashTile`, `createTileIndex`, `internTile` and `tileSlotCount` are the content addressing underneath. --- # Texture streaming Worlds. https://driftengine.dev/docs/worlds/texture-streaming Deciding which tiles of a texture are resident by running the simulation ahead to see where the camera will be, and giving up on tiles that will not come. A world's textures do not fit in memory at once, so tiles of them are fetched as they are needed and dropped when they are not. A streamer that waits until a frame has sampled a missing tile asks for it two or three frames late, and the tile pops in. DriftEngine can run its simulation forward and put it back exactly, which it already does for networking, so residency is decided by where the camera **will** be: the simulation is saved, advanced a few deterministic steps without rendering, asked which tiles those views would sample, and restored. `@driftengine/texture` holds the residency: a table of what is resident, a queue of what is wanted, a cache of pages and a streamer of fetches, all on the CPU. It decides what is in memory and when; moving a page to wherever a renderer samples it is the caller's. [Large worlds](https://driftengine.dev/docs/worlds/large-worlds) streams cells of a world through the same prediction. ## Where tiles come from A tile is addressed by a content hash, so a tile two materials share is one address and one fetch. `latentTileGrid(image, tileSize, addressMode)` cuts a latent and its mips into hashed tiles, level by level, which is what a baker has; `tileGridFromDtex(material)` reads the same grid from a [`DTEX`](https://driftengine.dev/docs/worlds/drifttexture) chunk's tile table, which is what a game loading a file has, and `dtexTileBytes(material, tx, ty)` gives one tile's bytes. The two hash different things, decoded texels against stored bytes, so a game keeps to one of them. ```ts /** * Where tiles come from: here, the tile tables of a file already read, by content hash. A game * streaming over a network answers the same question with a range request. */ export function sourceOf(materials: readonly DtexMaterial[]): TileSource { const bytes = new Map(); for (const material of materials) { const grid = tileGridFromDtex(material); if (grid === null) continue; const across = Math.ceil(grid.width / grid.tileSize); grid.levels[0]?.forEach((hash, at) => { const tile = dtexTileBytes(material, at % across, Math.floor(at / across)); if (tile !== null) bytes.set(hash, tile); }); } return { fetch: (hash) => Promise.resolve(bytes.get(hash) ?? null) }; } ``` A `TileSource` is one method, `fetch(hash)`, returning a promise of the tile's bytes or `null` where the source does not have it. What sits behind it, a file already read, a range request or a cache, is the caller's. ## The residency ```ts /** What is resident, the pages holding it, what is wanted next, and the fetches in flight. */ const TILE_BYTES = 4096; const table = createResidencyTable(4096); const cache = createPageCache(256, TILE_BYTES); const queue = createPrefetchQueue(2048); export function residency(source: TileSource): ReturnType { return createStreamer(source, table, cache, { maxInFlight: 64 }); } ``` - `createResidencyTable(capacity)` records each tile as `TILE_ABSENT`, `TILE_REQUESTED` or `TILE_RESIDENT`. `tileState`, `markRequested`, `markResident`, `evict`, `slotFor` and `residentCount` read and change it, `touchTile` stamps a tile as used this frame, and `leastRecentlyUsed` lists resident tiles oldest first, never one touched since the frame began. - `createPageCache(pages, pageBytes, options)` holds the bytes. A page acquired this frame is never evicted: a cache with nothing else to give refuses with `-1` from `acquirePage`, because a frame drawn against bytes being overwritten is a corruption, not a stall. `pageSlot`, `pageDecoded`, `releasePage` and `occupiedPages` read it, and `takeEvicted` drains what it gave up. - `createPrefetchQueue(capacity)` holds what is wanted by priority, lower first. `enqueue` adds or raises a tile, `queueSize` says how many wait, and `takeBatch(queue, isResident, bytesBudget, tileBytes, out)` takes the most urgent that fit a byte budget, checking residency at the moment of taking, since a tile asked for frames ago may have arrived. - `createStreamer(source, table, cache, { maxInFlight })` sends fetches. `pumpStreamer(streamer, batch, count)` starts them and returns at once, never awaiting, and skips anything resident, in flight or known missing, so calling it every frame with the same batch is correct. `streamerInFlight` counts what is outstanding. ## A frame ```ts /** What a predicted view would sample, and how to ask for what is missing. */ export function predictorFor(scene: InstanceTileInfo, projection: Float32Array): Predictor { return { needs: (view, out, budget) => tilesForView(view, projection, scene, out, budget), resident: (hash) => tileState(table, hash) === TILE_RESIDENT, request: (hash, priority) => enqueue(queue, hash, priority), }; } const batch: string[] = []; /** * One frame: protect what this frame samples, look six steps ahead, send the most urgent fetches * a 256 KB budget allows, and mark what is drawn as in use. */ export function streamFrame( streamer: ReturnType, simulation: SimulationHandle, predictor: Predictor, sampled: readonly string[], ): void { beginCacheFrame(cache); runPrediction(simulation, predictor, 6, 1 / 60, 512); const taken = takeBatch( queue, (hash) => tileState(table, hash) === TILE_RESIDENT, 256 * 1024, TILE_BYTES, batch, ); pumpStreamer(streamer, batch, taken); for (const hash of sampled) { if (tileState(table, hash) !== TILE_RESIDENT) continue; acquirePage(cache, hash); touchTile(table, hash); } } ``` Each frame: 1. `beginCacheFrame(cache)`, so everything acquired from here on is protected. 2. `runPrediction(simulation, predictor, frames, dt, budget)` runs the simulation ahead, as [Large worlds](https://driftengine.dev/docs/worlds/large-worlds) describes for cells, and requests what each predicted view needs, nearer frames first and at most `budget` tiles in all. 3. `takeBatch` and `pumpStreamer` send the most urgent fetches. 4. For every tile the frame samples, `acquirePage` and `touchTile`, so it is in use and recent. `tilesForView(view, projection, scene, out, budget)` is what a predicted view needs: for each instance whose bounding sphere is in view, the mip level its nearest point asks for, the finer level too within an eighth of a level of a boundary (`LEVEL_MARGIN`), and every coarser level a sampler falls back to, over the span of texture coordinates it shows. The answer is ordered by the screen each tile covers, so at any budget it is a prefix of the answer with none. `InstanceTileInfo` describes the scene it reads: each instance's bounding sphere, its texture coordinate span, how many metres one unit of texture coordinate covers on it, which material it wears, each material's tile grids, and the size of the target in pixels, since the level a sampler picks is texels a pixel. `predictViews` is the save, advance and restore underneath, for a caller that wants the views themselves. ### What it buys The engine's own gate flies a scripted path down a corridor of real latents: 452 tiles through a 256-page cache, never more than 102 sampled in a frame. Predicting, 296 samples are late; reacting, 1,294 are. The 296 are exactly the three frames before the first fetch could possibly have landed. When prediction is wrong it costs a wasted fetch and a tile as late as it would have been without it. A camera reversing every three frames is the case prediction cannot help, and on that flight it is 102 late samples predicted against 755 reacting; the picture converges once the camera settles. ## Giving up A fetch that resolves with nothing, a tile the container lacks, a name from a stale index, a refused range, would leave the tile requested and its in-flight slot taken for ever, and a handful of those stop streaming with no error anywhere. So the streamer remembers a missing tile as missing and does not ask again, treats a rejected fetch the same way, refuses bytes larger than a page instead of truncating them, and drops a fetch that lands after its tile was evicted, counting those in `oversize` and `stale`. A fetch that lands with no page free is counted in `deferred`, and the tile stays absent to be asked for again. `forgetMissing(streamer, hash)` and `clearMissing(streamer)` ask again, for a game that has mounted a different container. ## When the decode happens ```ts /** A cache that decodes each tile once, as it becomes resident, to be sampled as a plain texture. */ export function decodingCache(decode: PageDecode): ReturnType { return createPageCache(256, TILE_BYTES, { mode: 'on-residency', decode }); } /** Back to decoding per sample, at run time. Every page decoded under the old rule is invalidated. */ export function decodePerSample(): void { setDecodeMode(cache, 'per-sample'); } ``` A DriftTexture is decoded per sample by default. If that proves too slow for some material, the cache can decode each tile once, when it becomes resident, and the renderer samples it as an ordinary texture after: `mode: 'on-residency'` with a `PageDecode` function, and `ensurePageDecoded(cache, hash)` to run it. That keeps the compression, the joint channels and the streaming, and loses procedural and per-sample variation for the materials it is used on. `setDecodeMode` switches at run time and invalidates every page decoded under the old rule, since the two modes hold different bytes; `decodeMode` says which is in force. `progressiveOrder(tileCount, out)` gives an order to send a material's tiles in, every tile once, and `usableAt` says which level the bytes received so far support, rising and never going back, so a loader shows something at once and refines it. --- # Writable textures Worlds. https://driftengine.dev/docs/worlds/writable-textures Marks written into a texture at run time, allocated only where they land, recorded beside the input so a replay or a rollback draws the same wall. A scorch mark, a footprint in snow or paint on a wall is a texture changed while the game runs. Changed the usual way, the marks are not part of the simulation and nothing records them: a replay of the session shows clean walls, and a rollback leaves marks from frames that never happened. DriftEngine writes marks into a sparse overlay and records every write in a journal beside the input, so replaying the journal burns the same wall and rolling back rebuilds the wall as it was. The example is a wall a turret scorches three times a second, where and how large decided by a DriftScript module from nothing but the tick. Run the clock backwards and the marks disappear newest first; run it forwards again and the same marks come back in the same places. (This chapter runs the `scorch` example at https://driftengine.dev/docs/worlds/writable-textures.) ## The overlay ```ts /** The wall's texture, 256 texels square, as eight by eight tiles of 32 the overlay allocates. */ const RESOLUTION = 256; const overlay = createOverlay(32, { tilesAcross: 8 }); const journal = createOverlayJournal(); /** One shot: a soot halo and a darker core, each written into the three colour channels. */ function scorch(tick: number, u: number, v: number, radius: number): void { const marks: [number, number][] = [ [radius, 0.22], [radius * 0.5, 0.06], ]; for (const [r, shade] of marks) { for (let channel = 0; channel < 3; channel += 1) { writeOverlay(overlay, u, v, r, channel, shade); recordOverlayWrite(journal, tick, u, v, r, channel, shade); } } } ``` `createOverlay(tileSize, { tilesAcross, addressMode })` covers the unit square of a texture's coordinates with `tilesAcross` tiles a side of `tileSize` texels each. Only tiles a write touches are allocated, so a mark on one wall does not allocate a layer for the building: `overlayTileCount` and `overlayTiles` say which exist. The address mode is the base texture's, `ADDRESS_CLAMP` or `ADDRESS_WRAP`, so a mark near the edge of a wrapping texture lands on the far side where the base repeats. `writeOverlay(overlay, u, v, radius, channel, value)` writes `value` into one channel of every texel within `radius` of `(u, v)`, a disc, with the radius in texture coordinates. A texel carries `OVERLAY_CHANNELS` (4) channels, and the overlay remembers which channels of which texels were written, so a scorch that darkens the colour leaves a channel it did not touch to the base. ## Drawing it ```ts /** The wall as the base with every written channel of every written texel laid over it. */ const pixels = new ImageData(RESOLUTION, RESOLUTION); const sampled = new Float32Array(OVERLAY_CHANNELS); function paint(): ImageData { for (let y = 0; y < RESOLUTION; y += 1) { for (let x = 0; x < RESOLUTION; x += 1) { const u = (x + 0.5) / RESOLUTION; const v = (y + 0.5) / RESOLUTION; const at = (y * RESOLUTION + x) * OVERLAY_CHANNELS; const mask = writtenMaskAt(overlay, u, v); if (mask !== 0) sampleOverlay(overlay, u, v, sampled); for (let c = 0; c < OVERLAY_CHANNELS; c += 1) { const value = (mask & (1 << c)) !== 0 ? (sampled[c] ?? 0) : (base[at + c] ?? 0); /* sRGB for the canvas, from the linear values the wall is authored in. */ pixels.data[at + c] = c === 3 ? 255 : Math.round(Math.pow(value, 1 / 2.2) * 255); } } } return pixels; } ``` `writtenMaskAt(overlay, u, v)` says which channels of a texel are written, a bit each, and `sampleOverlay(overlay, u, v, out)` reads them, returning `false` where nothing is. The base shows through everywhere else. `compositeOverlay(out, base, overlay, written)` does the same for whole arrays of texels, such as one tile against the base's matching tile. The example composites onto an image and replaces its surface texture with `updateSurfaceTexture`, which re-uploads it and is done only on a frame where something was written. ## The journal `createOverlayJournal()` holds the writes, and `recordOverlayWrite(journal, frame, u, v, radius, channel, value)` adds one at the frame it happened on, beside the input that caused it. `journalLength` counts them. ```ts /** The simulation's tick, which the switch runs forwards or backwards. */ let tick = 0; let backwards = flag('clock', 'forwards') === 'backwards'; let dirty = true; controls([ { key: 'clock', label: 'clock', value: backwards ? 'backwards' : 'forwards', options: ['forwards', 'backwards'].map((c) => ({ text: c, value: c })), change: (value) => { backwards = value === 'backwards'; /* Going forwards from here: what the journal holds past now never happened. */ if (!backwards) truncateJournalFrom(journal, tick + 1); }, }, ]); function step(): void { if (backwards) { if (tick === 0) return; tick -= 1; /* A write cannot be undone, so the wall is rebuilt from the journal up to the earlier tick. */ rewindOverlay(overlay, journal, tick); dirty = true; return; } tick += 1; if (!exported>(turret, 'fires')(tick)) return; scorch( tick, exported>(turret, 'aimU')(tick), exported>(turret, 'aimV')(tick), exported>(turret, 'size')(tick), ); dirty = true; } ``` - `applyOverlayJournal(overlay, journal, upToFrame)` replays every write up to a frame onto what the overlay already holds, which is how a live session catches up frame by frame. - `rewindOverlay(overlay, journal, upToFrame)` puts the overlay back as it was at a frame: it clears it and replays. A write cannot be undone, since two marks on one texel leave no record of what was underneath, so a rollback rebuilds. - `truncateJournalFrom(journal, frame)` drops the writes from a frame on. Call it when the simulation resumes from an earlier frame: the frames it re-simulates record their writes again, and a journal that still held the old ones would draw both what happened and what was undone. - `clearOverlay` empties an overlay, and `emptyLike(overlay)` makes an empty one of the same shape, which is what a replay starts from. A journal travels as bytes: `encodeOverlayJournal` writes `JOURNAL_ENTRY_BYTES` (24) an entry after a `JOURNAL_MAGIC` and `JOURNAL_VERSION` header, and `decodeOverlayJournal` returns `null` for bytes that are not one, never half a journal, since a replay against half a log diverges partway for no visible reason. ## Behaviour that replays The turret's rules are a DriftScript module, and every answer is a function of the tick alone: ```drs // A shot every third of a second, at sixty ticks a second. fn fires(tick: u32) -> bool { return tick % 20 == 0 } // Where it lands, as a fraction of the wall across and up. fn aimU(tick: u32) -> f32 { return random.range(tick, 0.08, 0.92) } fn aimV(tick: u32) -> f32 { return random.range(tick + 1, 0.1, 0.9) } // How wide the scorch is, as a fraction of the wall. fn size(tick: u32) -> f32 { return random.range(tick + 2, 0.02, 0.05) } ``` `drift/random` draws from a seed and nothing else, so re-simulating the same ticks fires the same shots, which is what makes the journal and the simulation agree after the clock has run backwards. Edit a rule under `npm run examples` and the shots from then on follow it; the marks already made stay as they were made. ```ts /** The turret's rules, hosted. They read nothing but the tick. */ const turret = hostScript(turretScript); type ByTick = (tick: number) => T; if (import.meta.hot) { import.meta.hot.accept('./turret.drs', (next) => { if (next !== undefined) patchModule(turret, next as Record, {}); }); } ``` --- # DriftCapture Worlds. https://driftengine.dev/docs/worlds/driftcapture A video of a place turned into a surface, a collider, materials and proposed entities on the player's own device, and each stage's measured limits. `@driftengine/capture` turns a video of a place into a scene: a surface, a collider a character can stand on, the surface's colours separated from the light they were filmed under, and the scene cut into regions proposed as entities. It runs on the player's own device, in a browser or on the native host, and never fetches: the models' weights are files a game ships. It costs 72,615 bytes gzipped, and nothing in core imports it. Each stage states its maturity, measured on real handheld clips, and this chapter repeats those statements: DriftCapture reconstructs what a clip saw from where the clip saw it, and nothing more. The example runs the geometry stages on a clip it synthesises: a ring of frames ray cast from a room of four boxes, each with its true depth, so the page needs no model and no download. The surface it fuses is proposed as floor and scenery, and balls drop onto it as a collider. Use fewer frames to see the holes where nothing looked. (This chapter runs the `capture` example at https://driftengine.dev/docs/worlds/driftcapture.) ## Stage one: a surface ### Frames ```ts /** Six frames of a clip, spaced by equal motion, decoded to pixels. */ export async function framesOf(clip: Blob): Promise { const source = await browserFrameSource(clip); const kept = await selectFrames(source, { budget: 6 }); const frames: RawFrame[] = []; for (const index of kept) { const probe = await source.frameAt(index, new Uint8Array(0)); const pixels = new Uint8Array(probe.width * probe.height * 4); const size = await source.frameAt(index, pixels); frames.push({ pixels, width: size.width, height: size.height }); } return frames; } ``` A `FrameSource` is the host's own decoder, one frame at a time: `browserFrameSource(clip)` puts a browser's video element behind one, and the native host puts ffmpeg behind another. `eachFrame(source, visit)` walks a clip, and `selectFrames(source, { budget, every })` chooses the frames a capture keeps, spaced by equal motion. Choosing by motion decodes the whole clip, which through a browser's seek took 445 seconds for 1,401 frames; `every` takes every nth frame instead, under the same budget, for a caller that knows its clip. ### Depth and cameras ```ts /** A converted model file's weights, by tensor name, as a definition reads them. */ export function weightsOf(file: ArrayBuffer): WeightSource { const stored = readDrft(file).graphs[0]; if (stored === undefined) throw new Error('the model file holds no graph'); const tensors = graphFromStored(stored).tensors; return { get: (name) => tensors.get(name), names: () => tensors.keys() }; } /** Each graph run on the device, its runner built once a size and reused. */ export function onDevice(device: GPUDevice, half: boolean): GraphRun { const runners = new Map>>(); return async (graph, inputs) => { let runner = runners.get(graph); if (runner === undefined) { runner = await createGraphRunner({ device, half }, graphForDevice(graph)); runners.set(graph, runner); } return runner.run(inputs); }; } /** Depth, a confidence and a camera for every frame, from Depth Anything 3 Small. */ export function estimate( frames: RawFrame[], weights: WeightSource, run: GraphRun, ): Promise { return createDepthEstimator(DEPTH_ANYTHING_3.small, weights, run).estimate(frames); } ``` `createDepthEstimator(config, weights, run)` runs Depth Anything 3 over the frames together and answers a depth, a confidence and a camera for each: `DEPTH_ANYTHING_3.small` and `.base` are the two accepted sizes. `depthAnything2` with `DEPTH_ANYTHING_2_SMALL` is a lighter fallback, relative depth from one view at a time. A `GraphRun` runs a model's graph wherever the caller likes: on the device through core's `createGraphRunner`, or on the CPU as the reference. The models are written as definitions, functions of a model's weights that the texture package's `graphFromWeights` builds into a graph the engine's one neural runtime runs. Each is held by its tests to numbers the upstream project's own code wrote for a miniature of it, within a few parts in a million, and `miniatureCheckpoint` and its siblings are those miniatures, for checking a port of your own. **No weights ship with the engine.** A converter pins each accepted model to a commit and a SHA-256, and a game ships the converted file with the model's licence and attribution. Without a model, `estimatePoses(frames, options, out)` places the cameras the classical way: features tracked between frames (`detectFeatures`, `describeFeatures`, `matchFeatures`), a two-view start (`relativePose`, `triangulate`), every frame placed by what it sees, and a bundle adjustment. Each pose carries a confidence and reports `parallax: false` where the clip only turned, and the scale is metric only when a length is given. The decompositions underneath, `svd3`, `svdN`, `symmetricEigen`, `cholesky`, `levenbergMarquardt` and `schurSolve`, are exported, in double precision. ### Fusing the views ```ts /** The room the clip is of: a floor, a table, two crates stacked, and a cabinet. */ const ROOM: TestScene = { boxes: [ { min: [-1.6, 0, -0.8], max: [-0.4, 0.8, 0.4], seed: 1 }, { min: [0.3, 0, -1.2], max: [1.5, 0.5, 0.2], seed: 2 }, { min: [0.5, 0.5, -0.9], max: [1.1, 1.1, -0.3], seed: 5 }, { min: [-0.5, 0, 0.9], max: [0.5, 1.4, 1.5], seed: 7 }, ], planes: [{ normal: [0, 1, 0], offset: 0, seed: 3 }], }; /** Frames from a ring of positions round the room, each with the depth along the camera's axis. */ const WIDTH = 96; const HEIGHT = 72; function clip(frames: number): SurfaceView[] { const views: SurfaceView[] = []; for (let i = 0; i < frames; i += 1) { const angle = (i / frames) * Math.PI * 2; const eye: [number, number, number] = [Math.cos(angle) * 4.5, 2.2, Math.sin(angle) * 4.5]; const view = { width: WIDTH, height: HEIGHT, intrinsics: [80, 80, WIDTH / 2, HEIGHT / 2] as [number, number, number, number], worldToCamera: lookAt(eye, [0, 0.4, 0]), }; const pixels = new Uint8Array(WIDTH * HEIGHT * 4); const depth = new Float32Array(WIDTH * HEIGHT); renderTestScene(ROOM, view, pixels, depth); views.push({ depth, coverage: depth.map((d) => (d > 0 ? 1 : 0)), camera: view }); } return views; } ``` ```ts /** Every frame fused into one volume, its surface marched out, and brought to a budget. */ function surfaceOf(views: readonly SurfaceView[], budget: number): MeshData { const volume = createVolume([72, 30, 72], [-2.5, -0.3, -2.5], 0.07); fuseDepth(views, volume); const marched = marchVolume(volume); return budget > 0 ? decimate(marched, budget) : marched; } ``` `createVolume(dims, origin, spacing)` is a grid of samples over a box of the world, and `fuseDepth(views, volume)` writes every view's depth into it as a truncated signed distance, weighted by how squarely each view saw the surface. Space in front of a surface is carved out, space behind it is left alone, and a surface one view saw is kept at the weight one view is worth. Fusing twice with two halves of the views is fusing once with all of them, so a clip can be fused as it arrives. A `SurfaceView` is a depth along the camera's axis, a coverage from 0 to 1 and the camera; from a model, the confidence stands in for coverage: ```ts /** The estimate as views the fusion reads: the model's confidence stands in for coverage. */ export function surfaceOf(estimate: DepthEstimate, volumeSide: number): MeshData { const views: SurfaceView[] = estimate.views.map((view) => ({ depth: view.depth, coverage: view.confidence, camera: { width: estimate.width, height: estimate.height, intrinsics: [ view.intrinsics[0] ?? 0, view.intrinsics[4] ?? 0, view.intrinsics[2] ?? 0, view.intrinsics[5] ?? 0, ], worldToCamera: Float64Array.from(view.worldToCamera), }, })); /* A box round the room; a clip has no scale of its own until a length in it is known. */ const spacing = volumeSide / 96; const half = volumeSide / 2; const volume = createVolume([96, 96, 96], [-half, -half, -half], spacing); fuseDepth(views, volume); const marched = marchVolume(volume); return decimate(marched, Math.max(512, Math.floor(marched.indices.length / 6))); } ``` `marchVolume(volume)` extracts the surface as a mesh, by tetrahedra so it is closed by construction and faces outward. Where the clip never looked it is left open: a cap there would be a surface nobody measured. `decimate(mesh, budget)` brings it to a triangle budget by quadric-error collapse: a wall flattens, a corner keeps its detail, the border of an open capture is held, and a collapse that would turn a face inside out is refused. **Maturity.** Measured on an RX 9070 XT, six frames of a 1,401-frame 1080p handheld clip took 7.2 seconds in a browser and 9.05 on the native host, of which 3.6 and 5.5 were loading the weights, and a room came back as 33,060 triangles. Six frames is the ceiling on that device: ten are refused. The metric scale is not verified, since no capture measured contained an object of known size, so the metres are the model's claim. ### As Gaussians `optimiseGaussians(targets, poses, options)` fits the frames and their cameras into Gaussians, answered as the [splats](https://driftengine.dev/docs/worlds/splats) package's own `SplatSource`, with the first band of view-dependent colour on request. It descends a reference rasteriser, `rasteriseGaussians`, the same projection the splat shader performs with every analytic gradient checked against a central difference, and is judged by `structuralSimilarity`. `renderDepth` reads a cloud's depth back with the coverage beside it, and `splatColour`, `sh1Basis` and `SH_C1` shade a band exactly as the shader does. ## Stage two: a collider ```ts /** The same surface as a static body, and balls dropped onto it. */ let world = new PhysicsWorld(); const BALLS = 24; let balls: number[] = []; function collide(mesh: MeshData): void { world = new PhysicsWorld(); const { positions, indices } = collisionMesh(mesh); world.addBody({ type: BODY_STATIC, shape: meshShape(positions, indices), friction: 0.6 }); balls = Array.from({ length: BALLS }, (_, i) => world.addBody({ type: BODY_DYNAMIC, shape: sphereShape(0.12), x: (hashToUnit(i * 7) - 0.5) * 3, y: 2 + i * 0.25, z: (hashToUnit(i * 7 + 1) - 0.5) * 3, restitution: 0.4, }), ); } ``` `collisionMesh(mesh)` cleans a captured surface for collision, taking out triangles with no area and the vertices nothing uses after, and answers the positions and indices `meshShape` takes. `propHulls(mesh, options)` turns a prop into convex hulls instead, inside the container's own caps, since a room is one mesh body and a prop is something that can be thrown. **Maturity.** A collider holds where the capture has a surface, and a capture does not have one everywhere. A character controller dropped from a metre above a three-by-three grid of a real reconstruction landed on it three times of nine and fell through six, which is the reconstruction being patchy: a controller started inside the geometry is pushed out, not trapped. ## Stage three: materials `delight(views, mesh, options, out)` separates what a surface reflects from the light it was filmed under: what stays the same across views is the material, what moves is the light, and an intensity change the colour does not follow is a shadow. Every vertex carries a confidence. `renderLit` and `nearestHit` are the lit fixture it is measured against. **Maturity.** It recovers colour and says how much it trusts it, and on ordinary footage that is not much: a mean confidence of 0.276 on a wooden table and 0.249 on a room, a grey object on a grey floor having no chromaticity to tell shading from paint. It cannot remove a cast shadow, since a shadowed point is shadowed from every camera. It is the most expensive stage by thirty times, 44 seconds over 16,670 triangles, and colour is per vertex, so its detail is the mesh's. ## Stage four: entities ```ts /** Paint each triangle by the surface it belongs to, or by what the capture proposes it is. */ const WALKABLE: Vec3 = [0.35, 0.75, 0.4]; const SCENERY: Vec3 = [0.62, 0.6, 0.56]; function painted(mesh: MeshData, paint: string): MeshData { const regions = segmentGeometry(mesh, { creaseDegrees: 15 }); const proposals = proposeEntities(regions); const colourOf = new Map(); regions.forEach((region, index) => { const proposal = proposals[index]; const colour: Vec3 = paint === 'regions' ? [ 0.3 + hashToUnit(index * 3) * 0.6, 0.3 + hashToUnit(index * 3 + 1) * 0.6, 0.3 + hashToUnit(index * 3 + 2) * 0.6, ] : paint === 'proposals' && proposal?.walkable === true ? WALKABLE : SCENERY; for (const triangle of region.triangles) colourOf.set(triangle, colour); }); /* Three vertices a triangle, so neighbouring surfaces do not blend at their edges. */ const count = mesh.indices.length / 3; const positions = new Float32Array(count * 9); const normals = new Float32Array(count * 9); const colors = new Float32Array(count * 9); for (let t = 0; t < count; t += 1) { const colour = paint === 'clay' ? SCENERY : (colourOf.get(t) ?? SCENERY); for (let k = 0; k < 3; k += 1) { const from = (mesh.indices[t * 3 + k] ?? 0) * 3; const to = (t * 3 + k) * 3; positions.set(mesh.positions.subarray(from, from + 3), to); normals.set(mesh.normals.subarray(from, from + 3), to); colors.set(colour, to); } } return { positions, normals, colors, emissive: new Float32Array(count * 3), indices: Uint32Array.from({ length: count * 3 }, (_, i) => i), }; } ``` `segmentGeometry(mesh, { creaseDegrees, minimumArea })` cuts the mesh into regions with no model at all: runs of triangles that share an edge and whose normals agree within the crease angle, largest first. A floor, its walls and a table top are findable without knowing what any of them is. `planeOf` and `regionOf` read a region's plane and extent. `proposeEntities(regions)` makes each region a proposal, and the word matters: **a region nobody labelled becomes scenery**, drawn and solid and doing nothing (`SCENERY_COMPONENTS`). The largest surface a character could stand on gets a navigation surface (`WALKABLE_COMPONENTS`), and a named region small enough to move is offered as movable (`MOVABLE_COMPONENTS`). A segmentation model names regions where one is loaded. MobileSAM, SAM 2.1 with a tracker across frames, and OWLv2's text-prompted detector are definitions like the depth models. `liftMasks(views, mesh, labels)` votes a segmenter's masks onto the mesh across every view that saw a triangle, leaving a triangle no view claimed unassigned, `promptGrid` seeds the lattice of points it is prompted on, and `labelMasks` puts a detector's names to the masks by how far each box and mask agree; a mask that agrees with nothing stays unnamed, and unnamed is scenery. **Maturity.** It proposes and does not decide. Every region arrives undecided, a person accepts or rejects each in the editor, and the file records decisions, not guesses. A real room gave eight proposals and a tabletop one. ## One file `captureFile(scene)` writes every stage as one `.drft`: the mesh, its materials and decode program, the cloud, a prop's hulls, the way across the scene and the proposals. The proposals travel under a component this package declares, `PROPOSAL_COMPONENT`, so a capture proposes in its own words and an editor decides what a scene ends up holding. `proposalScene` builds that scene and `readProposals` reads it back. --- # Rigid bodies Simulation. https://driftengine.dev/docs/simulation/rigid-bodies A deterministic physics world of boxes, spheres, capsules, cylinders, hulls and meshes, with soft contacts, sleeping islands and a fingerprint. `@driftengine/physics` is a rigid-body world stepped on the fixed clock. It imports no other engine package, so a deterministic simulation runs with no renderer in its module graph: in Node, in a worker, or on a server holding the authoritative copy of a game. Core re-exports every name in it, so reaching for physics through the core barrel works as well. It costs 47.0 KB gzipped on its own. The example is a wall of crates, a ramp with wheels, a capsule, a ball and a rock rolling down it, and a cannon firing at the wall. The cannon is a DriftScript module. The readout's fingerprint is the whole world as one number. (This chapter runs the `physics` example at https://driftengine.dev/docs/simulation/rigid-bodies.) ## A world ```ts /** The ground, a ramp, a wall of crates and things to roll down the ramp. */ let world = new PhysicsWorld(); let ball = 0; function build(friction: FrictionModel, substeps: number): void { world = new PhysicsWorld({ frictionModel: friction, substeps }); drawnAs.length = 0; world.addBody({ type: BODY_STATIC, shape: boxShape(30, 0.5, 30), y: -0.5, friction: 0.8 }); /* A ramp turned twenty degrees about z, falling toward the wall. */ const half = (20 * Math.PI) / 360; world.addBody({ type: BODY_STATIC, shape: boxShape(5, 0.25, 2.5), x: 9, y: 1.6, qz: Math.sin(half), qw: Math.cos(half), }); const body = (desc: Parameters[0], drawn: MeshHandle): number => { const index = world.addBody(desc); drawnAs[index] = drawn; return index; }; /* The wall: six crates along the bottom, one fewer each row up. */ for (let row = 0; row < 6; row += 1) { for (let i = 0; i < 6 - row; i += 1) { body( { type: BODY_DYNAMIC, shape: boxShape(0.5, 0.5, 0.5), x: 0, y: 0.5 + row, z: i - (5 - row) / 2, friction: 0.6, density: 120, }, CRATE, ); } } /* Down the ramp: wheels standing on their rims, capsules lying across it, balls and a rock. */ const quarter = Math.SQRT1_2; for (let i = 0; i < 3; i += 1) { body( { type: BODY_DYNAMIC, shape: cylinderShape(0.6, 0.2), x: 12, y: 4.2, z: i * 1.4 - 1.4, qx: quarter, qw: quarter, }, WHEEL, ); } body( { type: BODY_DYNAMIC, shape: capsuleShape(0.3, 0.4), x: 11, y: 4.2, z: 2, qx: quarter, qw: quarter, }, PILL, ); body( { type: BODY_DYNAMIC, shape: sphereShape(0.45), x: 13, y: 5, z: 0.6, restitution: 0.3 }, BALL, ); body({ type: BODY_DYNAMIC, shape: hullShape(ROCK_POINTS), x: 10.5, y: 4.4, z: -2 }, ROCK); /* The cannon's ball, parked out of the way until the script fires it. */ ball = body( { type: BODY_DYNAMIC, shape: sphereShape(0.35), x: -14, y: 0.35, z: 0, density: 7800 }, SHOT, ); } ``` `new PhysicsWorld(options)` takes its quality and feel dials once: - `substeps`, integrate-and-solve passes a tick, and `iterations` a substep. Constraints are soft, each a stiffness in hertz with a damping ratio, so raising `substeps` buys accuracy and changes no behaviour: a stack rests at the same height and a ball bounces as high. - `gravityX`, `gravityY` and `gravityZ`; `linearDamping` and `angularDamping`. - `contactHertz` and `contactDamping`, and `jointHertz` and `jointDamping`, stiffer, since a joint is a structural relationship. - `speculativeMargin`, how far apart two shapes may be and still get a constraint. - `allowSleep`, on by default. - `frictionModel`, `'box'` by default or `'elliptical'`. Box friction clamps each tangent axis on its own, so a slide along the diagonal between them meets up to `√2` times the grip it meets along an axis: measured, 0.737 metres of travel against 1.064 from the same 4 m/s. Elliptical couples them, and the distance is 1.06 metres whatever the heading, which is what friction physically is. It is not the default because every stacking result moves under it, and a stored replay or a golden fingerprint is something a game keeps. - `workers` and `pool`, for solving islands on other threads; see below. `world.step(dt)` advances one fixed tick, always with the same `dt`. Contact events are drained after the tick, so nothing samples a substep's state. ## Bodies `addBody(desc)` returns the body's index. A `BodyDesc` names: - `type`: `BODY_STATIC`, never moving; `BODY_DYNAMIC`, moved by forces and contacts; `BODY_KINEMATIC`, never pushed and never integrated: you move it with `setPosition` each tick, and `setVelocity` tells contacts how fast it is moving. - `shape`, one convex shape, or `shapes`, up to `MAX_BODY_PARTS` (32) of them as one body. - `density`, 1,000 kilograms a cubic metre unless stated, which is water. The example's crates are 120 and its cannon ball 3,000. - `x`, `y` and `z`, and a rotation as the quaternion `qx`, `qy`, `qz` and `qw`. - `friction` and `restitution`. - `layer` and `mask`, 32 bits each: two bodies collide only when each one's mask admits the other's layer (`layersInteract`). `ignorePair(a, b)` excludes one pair whatever their layers say, and `allowPair` undoes it. - `sensor`, for a body that reports overlap and is never pushed out of it. State lives in `world.bodies`, a `BodySet` of parallel arrays: `posX`, `posY`, `posZ`, the rotation `rotX`, `rotY`, `rotZ`, `rotW`, the velocities `velX`, `velY`, `velZ` and `angX`, `angY`, `angZ`, and `count`. Position and rotation are what a frame draws: ```ts /** A body's model matrix, from its position and the quaternion the world integrates. */ const model = new Float32Array(16); function placed(body: number): Float32Array { const b = world.bodies; const x = b.rotX[body] ?? 0; const y = b.rotY[body] ?? 0; const z = b.rotZ[body] ?? 0; const w = b.rotW[body] ?? 1; model[0] = 1 - 2 * (y * y + z * z); model[1] = 2 * (x * y + z * w); model[2] = 2 * (x * z - y * w); model[4] = 2 * (x * y - z * w); model[5] = 1 - 2 * (x * x + z * z); model[6] = 2 * (y * z + x * w); model[8] = 2 * (x * z + y * w); model[9] = 2 * (y * z - x * w); model[10] = 1 - 2 * (x * x + y * y); model[12] = b.posX[body] ?? 0; model[13] = b.posY[body] ?? 0; model[14] = b.posZ[body] ?? 0; model[15] = 1; return model; } ``` `applyImpulse`, `applyForce`, `setVelocity` and `setPosition` move a body from outside, waking its island; `bodyMass` reads its mass, and `sleeping(body)` whether it has settled. `removeBody(index)` fills the hole with the last body and returns that body's old index, or −1, so a game keeping body indices follows the one it is told about. ## Shapes A `ConvexShape` is a point cloud and two kinds of rounding, with its separating features listed once when it is built: - `boxShape(hx, hy, hz)`, by half extents: eight corners. - `sphereShape(radius)`: one point and a radius. - `capsuleShape(radius, halfHeight)`: two points along y and a radius. - `cylinderShape(radius, halfHeight)`, standing along y: two points and a side radius that grows the shape by a disc, so the caps are flat and the rim is sharp. A wheel is a cylinder turned a quarter turn. A 32-sided prism wheel bobs 16 mm rolling at 6 m/s; a cylinder bobs under 2 mm. - `hullShape(points, radius)`, the convex hull of up to 64 points, from the few points that define a shape, never a render mesh. `shapeBounds` measures one, `shapeMassProperties` and `combineMassProperties` give mass, centre and inertia for a density. A concave thing that moves is several hulls. `decomposeConvex(positions, indices, options)` cuts a mesh into `parts`, each a hull's `points`, its `volume` and how full it is, with `resolution`, `maxHulls` and `concavity` as its dials; it runs offline. Static concave geometry is a mesh: `meshShape(positions, indices)` on a static body, where every triangle goes through the same narrow phase, contacts are one-sided, rays are two-sided, and interior edges are filtered so a box sliding across two coplanar triangles does not catch on their seam. Measured, a box slid at 6 m/s across sixteen quads keeps 80% of its speed with the filter and 1% without. A heightfield is a shape of its own, `heightfieldShape`, covered in [Terrain](https://driftengine.dev/docs/worlds/terrain). ## Sleeping and islands Bodies that touch, through contacts or joints, form an island, and only dynamic bodies join one, so two towers on one floor are two islands. An island whose bodies have all been still for long enough sleeps, counted in ticks, and wakes when something touches it. `islandCount` says how many there were on the last tick. No two islands share a body, so solving them in any order, or at once, gives the same bits. The `Executor` seam runs them: `SerialExecutor` by default, `ShuffledExecutor` in a random order, which the tests use to prove order does not matter, and `DisjointExecutor`. `new PhysicsWorld({ workers, pool: createIslandPool })` solves on a pool of workers from `@driftengine/physics/workers`, named at the call so a game that never asks for workers bundles none. It needs a cross-origin isolated page, since it shares memory; without one the world stays serial, correct, and says why in `parallelism.reason`. ## Determinism Contacts persist across ticks by feature, never by nearness within a tolerance, which is what makes warm starting correct and independent of order. No angle appears anywhere in the solve: limits compare cosines and quaternion components. The tick uses no `sin`, `atan` or `pow` that two engines could round differently. `fingerprintBodies(world.bodies)` hashes every body's state into one string, and two runs of the same inputs reach the same one tick for tick: it is how a replay or a rollback session checks that two machines agree. `fingerprintColliders` does the same for a `ColliderSet`. ## From DriftScript `drift/physics` reads and moves bodies of a world a script is handed: ```drs // Called every tick with the tick's number. Answers whether it fired on this one. fn fire(world: PhysicsWorld, ball: i32, tick: u32) -> bool { if tick % 150 != 30 { return false } let shot = tick / 150 physics.setPosition(world, ball, -14, 1.2, random.range(shot, -1.5, 1.5)) physics.setVelocity(world, ball, 30, random.range(shot + 1, 1, 4), random.range(shot + 2, -0.6, 0.6)) physics.wake(world, ball) return true } ``` | Capabilities | What they do | | ------------------------------------------------------------------ | ----------------------------------------------------------------------- | | `bodyCount`, `bodyX`, `bodyY`, `bodyZ`, `bodyVelX` to `bodyVelZ` | Read a body's position and velocity | | `bodyMass`, `sleeping` | Its mass, and whether it has settled | | `applyImpulse`, `applyForce`, `setVelocity`, `setPosition`, `wake` | Move it | | `setGravity` | Change the world's gravity | | `raycast`, then `hitBody`, `hitX`, `hitNormalX` and the rest | Cast a ray and read what it hit | | `contactCount`, `contactKind`, `contactA`, `contactB` | Read the tick's contact events | | Collider capabilities | Query and edit a `ColliderSet`; see [Queries and colliders](https://driftengine.dev/docs/simulation/queries) | Reads are `physics.read` and are deterministic; writes are `physics.write`. The world reaches a script as an argument, so the module needs no host service: ```ts /** The cannon, hosted, and called once a tick with the world it fires into. */ const cannon = hostScript(cannonScript); type Fire = (world: PhysicsWorld, ball: number, tick: number) => boolean; if (import.meta.hot) { import.meta.hot.accept('./cannon.drs', (next) => { if (next !== undefined) patchModule(cannon, next as Record, {}); }); } ``` --- # Joints Simulation. https://driftengine.dev/docs/simulation/joints Seven kinds of joint between bodies, with one-sided limits, motors and a breaking load, and a six-degree-of-freedom joint described axis by axis. A joint holds two bodies in a relationship: a hinge, a ball and socket, a slider, a rope. The physics world solves joints beside its contacts, stiffer than a contact because a joint is structural, and `jointHertz` and `jointDamping` set how stiff. The example is a bridge of planks hinged end to end, a door on a motor, a lamp swinging on a cord, and a chain that snaps when a ball lands in its basket. Open and shut the door, and make the chain breakable. (This chapter runs the `joints` example at https://driftengine.dev/docs/simulation/joints.) ## Adding a joint `addJoint(desc)` joins `bodyA` and `bodyB` and returns the joint's index. Either body may be static, which is how something is hung from the world. The common fields: - `anchorAX`, `anchorAY`, `anchorAZ` and `anchorBX`, `anchorBY`, `anchorBZ`: where the joint is on each body, in that body's own frame. - `axisX`, `axisY`, `axisZ`: the free axis in A's frame, which a hinge turns about and a slider travels along. - `lower` and `upper`: one-sided limits. A limit pushes only when the joint is past it, so a hinge swings freely between its stops. - `motorSpeed` and `motorMaxForce`: a motor drives the free axis toward a speed with at most that force. - `breakImpulse`: the accumulated impulse above which the joint gives way. `Infinity`, the default, never breaks. A joint captures the relative pose its bodies are in when it is made, so a rig can be posed and then jointed without anything snapping on the first tick. No angle appears in the solve: angular limits are sines of half angles, the same unit as a quaternion's components, so a quarter turn is `Math.sin(Math.PI / 4)`. `world.joints` is the `JointSet`: `count`, and per joint its `type`, bodies, `motorSpeed`, `motorMaxForce`, `broken` and the rest, which a game changes between ticks. `resetJointImpulses` clears what the solver carried from the last tick. ## The kinds | Type | What it holds | | ------------------ | ---------------------------------------------------------------------------- | | `JOINT_DISTANCE` | The two anchors `length` apart: a rope that does not slacken, or a strut | | `JOINT_SPHERICAL` | The two anchors together, any rotation free: a ball and socket | | `JOINT_REVOLUTE` | A hinge about the axis, with a limit and a motor | | `JOINT_PRISMATIC` | A slider along the axis, rotation locked, with a limit in metres and a motor | | `JOINT_FIXED` | Everything locked, solved as two coupled blocks | | `JOINT_CONE_TWIST` | A shoulder: swing within a cone (`swingCos`), twist within `twistSin` | | `JOINT_SIX_DOF` | Each of the six axes free, limited or locked, as you say | ### A bridge of hinges ```ts /** Twelve planks between two posts, each hinged to the next about the axis across the bridge. */ function bridge(): void { const left = add({ type: BODY_STATIC, shape: boxShape(0.2, 1.6, 1.1), x: -5.4, y: 1.6 }, POST); const right = add({ type: BODY_STATIC, shape: boxShape(0.2, 1.6, 1.1), x: 5.4, y: 1.6 }, POST); let previous = left; let anchorX = 0.2; for (let i = 0; i < 12; i += 1) { const plank = add( { type: BODY_DYNAMIC, shape: boxShape(0.38, 0.06, 0.9), x: -4.8 + i * 0.84, y: 3, density: 400, }, PLANK, ); world.addJoint({ type: JOINT_REVOLUTE, bodyA: previous, bodyB: plank, anchorAX: anchorX, anchorAY: previous === left ? 1.4 : 0, anchorBX: -0.42, axisZ: 1, }); previous = plank; anchorX = 0.42; } world.addJoint({ type: JOINT_REVOLUTE, bodyA: previous, bodyB: right, anchorAX: 0.42, anchorBX: -0.2, anchorBY: 1.4, axisZ: 1, }); } ``` Each plank is hinged to the next at their touching ends, about the axis across the bridge, and the first and last to the posts. The bridge sags under its own weight and swings when a ball lands. ### A door on a motor ```ts /** A door on a hinge with a motor, limited to swing from shut to a little past a right angle. */ function hingedDoor(): void { const frame = add( { type: BODY_STATIC, shape: boxShape(0.1, 1.2, 0.1), x: -2, y: 1.2, z: -4 }, null, ); door = add( { type: BODY_DYNAMIC, shape: boxShape(0.9, 1.1, 0.06), x: -1.05, y: 1.2, z: -4, density: 300 }, DOOR, ); doorHinge = world.addJoint({ type: JOINT_REVOLUTE, bodyA: frame, bodyB: door, anchorBX: -0.95, axisY: 1, /* Angular limits are sines of half angles: shut, and open to 110 degrees. */ lower: 0, upper: Math.sin((110 * Math.PI) / 360), motorSpeed: 0, motorMaxForce: 400, }); } ``` The hinge turns about y. Its limits are shut and 110 degrees open, as sines of half angles, and the motor drives toward one or the other at a speed the page sets each tick from the switch; the limit stops it at either end. A motor has a maximum force, so a door pushed hard enough gives. ### A lamp on a cord ```ts /** A lamp on a cord: a distance joint holds it two metres from its hook, and it swings. */ function lamp(): void { const hook = add({ type: BODY_STATIC, shape: sphereShape(0.05), x: 3, y: 5.5, z: -4 }, null); const shade = add({ type: BODY_DYNAMIC, shape: sphereShape(0.3), x: 4.2, y: 4, z: -4 }, LAMP); world.addJoint({ type: JOINT_DISTANCE, bodyA: hook, bodyB: shade, length: 2 }); } ``` A distance joint holds the lamp two metres from a static hook and leaves it free to swing. ### A chain that breaks ```ts /** Links joined at their ends, and a basket at the bottom. Breakable, each joint gives way above a load. */ function chain(breakable: boolean): void { const ceiling = add( { type: BODY_STATIC, shape: boxShape(0.3, 0.05, 0.3), x: 7.5, y: 5.6, z: 2 }, null, ); chainJoints = []; let previous = ceiling; let anchorY = -0.05; for (let i = 0; i < 8; i += 1) { const link = add( { type: BODY_DYNAMIC, shape: boxShape(0.08, 0.2, 0.08), x: 7.5, y: 5.35 - i * 0.42, z: 2, density: 800, }, LINK, ); chainJoints.push( world.addJoint({ type: JOINT_SPHERICAL, bodyA: previous, bodyB: link, anchorAY: anchorY, anchorBY: 0.21, breakImpulse: breakable ? 60 : Infinity, }), ); previous = link; anchorY = -0.21; } const basket = add( { type: BODY_DYNAMIC, shape: boxShape(0.5, 0.08, 0.5), x: 7.5, y: 1.85, z: 2, density: 300 }, BASKET, ); world.addJoint({ type: JOINT_SPHERICAL, bodyA: previous, bodyB: basket, anchorAY: -0.21, anchorBY: 0.1, }); } ``` Each link hangs from the last by a spherical joint. Made breakable, each joint gives way above a load: the chain carries itself and its basket, and a ball landing in the basket is more than the top joint can take. A joint that has given way has its `broken` flag set, and the solver skips it from then on. ## Six degrees of freedom ```ts /** Linear x, y, z then angular x, y, z, in the hips' own frame. Bounds are sines of half angles. */ export const hip = world.addJoint({ type: JOINT_SIX_DOF, bodyA: hips, bodyB: thigh, anchorAY: -0.1, anchorBY: 0.22, dof: [DOF_LOCKED, DOF_LOCKED, DOF_LOCKED, DOF_LIMITED, DOF_FREE, DOF_LOCKED], dofLower: [0, 0, 0, -Math.sin(Math.PI / 8), 0, 0], dofUpper: [0, 0, 0, Math.sin(Math.PI / 8), 0, 0], }); ``` `JOINT_SIX_DOF` describes each axis in A's frame, linear x, y and z then angular x, y and z, as `DOF_FREE`, `DOF_LIMITED` or `DOF_LOCKED` in `dof`, with `dofLower` and `dofUpper` for the limited ones (`DOF_COUNT` is six). An axis not described is locked, so a forgotten axis is rigid and never a pair of bodies flying apart. Angular bounds are sines of half angles. An all-locked six-DOF joint is softer than `JOINT_FIXED`, since it solves six independent rows where the fixed joint solves two coupled blocks; use the fixed one when everything should hold. It has no motor, and says so on the console when given one. --- # Queries and colliders Simulation. https://driftengine.dev/docs/simulation/queries Rays, swept shapes and overlaps against the world, sensors and contact events, a collider set for kinematic movement, and scenery that streams in by region. A game asks the physics world questions as often as it steps it: what is in front of the gun, is there room to stand up, what just walked into the trigger. Every query here fills a buffer the caller owns and allocates nothing. The example is a room of crates and balls pushed about by a sliding wall. A laser on a post, a DriftScript module, casts a ray every tick and lights what it meets, and a square of floor is a sensor that counts what is standing on it. (This chapter runs the `queries` example at https://driftengine.dev/docs/simulation/queries.) ## Rays, sweeps and overlaps ```drs fn scan(laser: mut Laser, world: PhysicsWorld, dt: f32) { laser.angle = laser.angle + dt * 0.7 let dx = math.cos(laser.angle) let dz = math.sin(laser.angle) // From half a metre up the post, level, any layer. if physics.raycast(world, 0, 0.5, 0, dx, 0, dz, laser.reach, -1) { laser.hit = physics.hitBody(world) laser.distance = physics.hitFraction(world) * laser.reach } else { laser.hit = -1 laser.distance = laser.reach } } ``` - `raycast(ox, oy, oz, dx, dy, dz, maxDistance, out, filter)` finds the nearest body a ray meets and fills a `RayHit` from `createRayHit()`: the `body`, the `fraction` of `maxDistance` it travelled, the point `x`, `y`, `z` and the normal `nx`, `ny`, `nz`. A ray that starts inside a body reports that body at fraction zero: a line of sight that started inside a wall does not see past it. - `shapecast(shape, pose, dx, dy, dz, out, filter)` sweeps a convex shape, posed by a `ShapePose` of position and quaternion, along a displacement and reports the first body it touches. - `overlap(shape, pose, out, filter)` writes every body overlapping a shape into an `Int32Array` and returns how many. A `QueryFilter` narrows any of them: `ignore`, a body to skip, usually the one asking; `layer`, the asker's own layer tested against each body's mask; and `mask`, the layers it wants, tested against each body's layer. `raycastWorld`, `shapecastWorld` and `overlapWorld` are the same queries over a `BodySet` and its tree, for a caller holding those without a world, and `isStaticBody` says whether a hit is scenery. Rays against a triangle mesh are two-sided, though its contacts are one-sided: a sight line that saw through a wall from behind is a worse answer than one that did not. ## Sensors and contact events ```ts /** Who is in the square: entered on one tick, still there until an exit says otherwise. */ const inside = new Set(); function drainEvents(): void { const events = world.events; for (let i = 0; i < events.count; i += 1) { const kind = events.data[i * 3]; const a = events.data[i * 3 + 1] ?? -1; const b = events.data[i * 3 + 2] ?? -1; const other = a === zone ? b : b === zone ? a : -1; if (other < 0) continue; if (kind === EVENT_ENTER) inside.add(other); if (kind === EVENT_EXIT) inside.delete(other); } } ``` A body added with `sensor: true` reports overlap and is never pushed out of it. Events from every contact and every sensor collect during the tick and are drained after it, from `world.events`: `count` triples of kind, first body and second body in `data`, where the kind is `EVENT_ENTER`, `EVENT_STAY` or `EVENT_EXIT`. They are ordered by pair, so a replay sees them in the order it recorded them. They are never callbacks during the solve: a callback that removed a body mid-solve would invalidate every index the solver holds. Drain them completely each tick, since a dropped exit leaves a game believing something is still inside a trigger. From DriftScript, `contactCount`, `contactKind`, `contactA` and `contactB` read the same events. ## A kinematic body ```ts /** The floor and four walls, the things on it, the sliding wall and the sensor square. */ const world = new PhysicsWorld(); world.addBody({ type: BODY_STATIC, shape: boxShape(8, 0.5, 8), y: -0.5 }); for (const [x, z, hx, hz] of [ [8.25, 0, 0.25, 8], [-8.25, 0, 0.25, 8], [0, 8.25, 8, 0.25], [0, -8.25, 8, 0.25], ] as const) { world.addBody({ type: BODY_STATIC, shape: boxShape(hx, 1, hz), x, y: 1, z }); } const things: { body: number; mesh: MeshHandle }[] = []; const crate = renderer.createMesh( new MeshBuilder().addBox([0, 0, 0], [0.4, 0.4, 0.4], [0.72, 0.56, 0.38]).build(), ); const ball = renderer.createMesh( new MeshBuilder().addSphere([0, 0, 0], 0.35, [0.35, 0.6, 0.85], 0, 18, 9).build(), ); for (let i = 0; i < 18; i += 1) { const x = (hashToUnit(i * 2) - 0.5) * 12; const z = (hashToUnit(i * 2 + 1) - 0.5) * 12; const round = i % 3 === 0; const body = world.addBody({ type: BODY_DYNAMIC, shape: round ? sphereShape(0.35) : boxShape(0.4, 0.4, 0.4), x: Math.abs(x) < 1 ? x + 2 : x, y: 0.5, z, density: 200, }); things.push({ body, mesh: round ? ball : crate }); } /** A wall that slides back and forth across the room: kinematic, so it pushes and is not pushed. */ const sweeper = world.addBody({ type: BODY_KINEMATIC, shape: boxShape(0.2, 0.6, 3), x: 0, y: 0.6, z: -3.5, }); /** A square of floor that reports what overlaps it and stops nothing. */ const zone = world.addBody({ type: BODY_STATIC, shape: boxShape(1.5, 0.3, 1.5), x: 5, y: 0.3, z: -5, sensor: true, }); ``` The sliding wall is `BODY_KINEMATIC`: never pushed and never integrated. The page sets its position each tick and gives it the velocity it is moving at, so the solver knows how fast it pushes the crates in its way. ## A collider set Not everything that moves needs dynamics. A `ColliderSet` is a spatial hash of convex colliders that a kinematic body is swept against one axis at a time, which is what the [character controller](https://driftengine.dev/docs/simulation/characters) and the cameras use. `boxCollider(cx, cy, cz, hx, hy, hz)` makes a box, and `colliderFromShape(shape)` wraps any convex shape in a world-space position; triangle meshes are refused, since the sweep tests a fixed list of axes and a mesh has none. ```ts const colliders = new ColliderSet([boxCollider(0, -0.5, 0, 20, 0.5, 20)]); const body: Body = { x: 0, y: 2, z: 0, hx: 0.35, hy: 0.9, hz: 0.35 }; /** How far it actually travelled along each axis, which is less where something was in the way. */ export const across = moveAxis(body, colliders, AXIS_X, 0.05); export const down = moveAxis(body, colliders, AXIS_Y, -0.02); ``` `moveAxis(body, set, axis, delta)` moves a `Body`, a box by its centre and half extents, as far as it can along one axis and returns how far it went. `ejectFromSolid` pushes a body that has ended up inside geometry back out, and reports it as the event it is. `segmentHit` tests a segment against the set's boxes for drawing, never for the simulation. `bodyBounds` and `aabbFromCenter` build the boxes these read. ### Streaming the colliders A set follows the player: build it empty, `add` the colliders of each region as it comes into reach, and `remove` the group a region was added as when it leaves. Only that group's cells are touched, so a crossing cost 0.090 milliseconds in the engine's own measurement, where rebuilding a set of the same size cost about 41, and queries on a streamed set ran at 1.25 to 1.31 times the speed of a freshly built one. One set for the player keeps an index meaning one thing; a set per region would make every query result a pair. `count` is the live colliders and `capacity` the slots; after the first `remove` the live ones are sparse, so a walk over every slot skips those where `liveAt(i)` is false. A set built by its constructor cannot be streamed: those colliders belong to a group `remove` refuses, so a streamed set starts empty. `bytes()` says what the resident ring costs, and `absorb(other)` folds one set into another without rehashing. `fingerprintColliders` hashes a set; on a set that has been streamed it means the same set with the same history. From DriftScript, `beginColliderGroup`, `addColliderBox`, `endColliderGroup` and `removeColliderGroup` edit a `Colliders` set, and `anyWithin`, `nearestWithin`, `nearCollider`, `nearX`, `nearY`, `nearZ` and `nearDistance` ask it what is close. ## Scenery by region A streamed world's scenery is one static triangle-mesh body a region, added as the region streams in and removed as it streams out. `StaticRegions` keeps the books: ```ts /** One static mesh body a region, added as it streams in and removed as it streams out. */ const world = new PhysicsWorld(); const scenery = new StaticRegions(world); export function streamIn(region: number, positions: Float32Array, indices: Uint32Array): void { scenery.add(region, { type: BODY_STATIC, shape: meshShape(positions, indices) }); } export function streamOut(region: number): void { scenery.remove(region); } /** The body a region stands as now, which changes as other regions leave. */ export const bodyOf = (region: number): number => scenery.bodyOf(region); ``` A region of hundreds of boxes as one mesh body is one add and one remove, and the mesh carries its own tree. `removeBody` fills the removed body's slot with the world's last body, which may be another region's, so `StaticRegions` follows each move and `bodyOf` always answers the index a region stands as now. A world that also holds bodies someone else tracks by index has to remove them through one place that follows them all. A `.drft` hands over what a region collides as: its regions carry collision triangles, and `DrftLoader` exposes the file's `colliders` as hulls, its `navigation` mesh and its `entities`, which a streaming reader also receives through `onColliders`, `onNavigation` and `onEntities`. --- # Characters Simulation. https://driftengine.dev/docs/simulation/characters A kinematic character controller with coyote time and jump buffering, ground surfaces for roads and decks, water, and an escape for a trapped body. A character that is a dynamic body falls over, cannot be steered crisply, and turns every question about movement into a question about torque. `CharacterController` is a kinematic capsule instead, swept through the same physics world everything else queries, so it stands on scenery and bodies alike and pushes the dynamic ones it walks into. Its feel, acceleration, air control, jump height, coyote time, rides on it as numbers. The example is a valley to walk about: across a bridge or down under it, up a flight of steps, off a slab too steep to stand on, into a pond and into crates. WASD or the arrows walk, Space jumps, and Q and E turn the camera; until a key is pressed, the character walks a circuit of its own. (This chapter runs the `character` example at https://driftengine.dev/docs/simulation/characters.) ## The controller ```ts /** Two feels for one character: quick to turn and short in the air, or slow to stop and floaty. */ const FEELS: Record = { snappy: { acceleration: 60, deceleration: 50, airControl: 0.4, jumpSpeed: 7, gravity: -24 }, floaty: { acceleration: 12, deceleration: 6, airControl: 0.8, jumpSpeed: 6, gravity: -11 }, }; let feel = flag('feel', 'snappy'); let player = new CharacterController({ ...FEELS[feel], coyoteTicks: 6, jumpBufferTicks: 6, ground, }); player.teleport(-8, 4, 4); ``` `new CharacterController(options)` takes: - `radius` and `halfHeight`, the capsule: 0.35 and 0.6, so 1.9 metres tall. - `stepHeight`, the highest lip walked over without a jump, 0.35. - `slopeCos`, the cosine of the steepest walkable slope, 0.7 (about 45 degrees). Steeper ground is slid down, with `slideBoost` added downhill. - `maxSpeed`, `acceleration`, `deceleration` and `airControl`, the share of control left in the air. - `jumpSpeed`, `gravity`, and `jumpCutoff`, the fraction upward speed is cut to when jump is released early, which is what makes a short tap a short hop. - `coyoteTicks`, how many ticks after leaving an edge a jump still counts, and `jumpBufferTicks`, how long a press made just before landing is remembered. Both are counted in ticks, never accumulated in seconds, so a replay matches after an hour of play. - `pushStrength`, how hard it shoves the dynamic bodies it walks into. - `filter`, which bodies it collides with, and `ground`, a surface to stand on beside the bodies. `teleport(x, y, z)` places it and clears its velocity, and `move(world, dt, input)` advances it one tick. The input is `moveX` and `moveZ`, the wanted velocity in metres a second, clamped to `maxSpeed`, and `jump`, held: the controller does its own edge detection and buffering. Afterwards `x`, `y`, `z`, `velX`, `velY` and `velZ` say where it is and how it moves, and `state` is `GROUNDED`, `AIRBORNE` or `SLIDING`. `setUp` and `setGravityDirection` turn its frame, for walls and spheres, with `moveY` and `projectMove` in the input for steering on a surface whose up is not world Y. ## The controls, in DriftScript The example's controls are a DriftScript module reading the page's `ActionMap` through `drift/input`: ```drs // The stick or the keys, turned by the camera's yaw so that up is away from the camera. fn steer(wish: mut Wish, actions: Actions, yaw: f32, speed: f32) { let across = input.axisX(actions, "move") let along = input.axisY(actions, "move") wish.x = (math.cos(yaw) * across + math.sin(yaw) * along) * speed wish.z = (math.cos(yaw) * along - math.sin(yaw) * across) * speed wish.jump = input.down(actions, "jump") } ``` `input.axisX` and `input.axisY` read a vector action as the stick convention has it, up negative, and `input.down` and `input.pressed` read a button. The page calls `steer` once a tick and hands its wish to the controller: ```ts /** The controls, hosted, and the wish they fill each tick. */ const controlsModule = hostScript(controlsScript); interface Wish { x: number; z: number; jump: boolean; } const wish = exported<() => Wish>(controlsModule, 'createWish')(); type Steer = (wish: Wish, actions: ActionMap, yaw: number, speed: number) => void; type Seek = ( wish: Wish, fx: number, fz: number, tx: number, tz: number, speed: number, jump: boolean, ) => void; if (import.meta.hot) { import.meta.hot.accept('./controls.drs', (next) => { if (next !== undefined) patchModule(controlsModule, next as Record, { Wish: [wish] }); }); } ``` ## Ground surfaces ```ts /** A valley along z, a pond dug into its west bank, and a bridge deck across it at z = 0. */ const smooth = (t: number): number => t * t * (3 - 2 * t); function valley(x: number, z: number): number { const bank = 2.6 * smooth(Math.min(1, Math.max(0, (Math.abs(x) - 1.5) / 4.5))); const pond = 1.6 * Math.max(0, 1 - Math.hypot(x + 12, z - 9) / 4); return bank - pond; } const SIDE = 81; const terrain = new Terrain({ width: SIDE, depth: SIDE, spacingM: 0.5, heights: Float32Array.from({ length: SIDE * SIDE }, (_, i) => valley((i % SIDE) * 0.5 - 20, Math.floor(i / SIDE) * 0.5 - 20), ), origin: [-20, 0, -20], }); /* Level with the banks where it meets them: a body walks from one field onto the other only where the two are at one height. */ const DECK_Y = 2.6; const deck = (x: number, z: number): number => Math.abs(x) < 6.5 && Math.abs(z) < 1.5 ? DECK_Y : Number.NaN; /** Two fields: whichever is nearer the height a body is at is the floor it stands on. */ const ground = heightSurface([(x, z) => terrain.heightAt(x, z), deck]); ``` A world whose floor is analytic, a road along a route, a heightfield, a deck, has one floor and not one per thing standing on it. Anything that answers "how high is the ground at this column, and which way does it face" is a `GroundSurface`, and the controller, the vehicle, the third-person camera and the rain all take one. The controller consults it only where the bodies found nothing walkable: a body is a thing that is there, and a surface is a description of where the ground is. - `heightSurface(field, options)` wraps a function of `(x, z)`, or a **list** of them. A layer answers `NaN` where it is not there, so a bridge deck is a floor over its span and nothing beside it, and a road passes under a road. Which layer a body gets is the one nearest the height it asks from, and a tie goes to the one below. `bounds` limits a field, and `normalAt` supplies exact normals in place of the central difference. - `RibbonSurface` is a road along a route, with its banking and width; `BoxSurface` is a set of pads; `CompositeSurface` answers several surfaces as one, as `heightSurface` does for a list. - `colliderSurface(set, { minY, maxY })` lets the slabs of a `ColliderSet` be ground, solved against their own faces so a ramp holds a body along its slope. `minY` and `maxY` are required: they bound the column the spatial hash walks. **Where two layers meet, they have to meet at one height.** A body walks from one layer onto another where both answer the same height; a kerb between two layers is not stepped up, and the example's deck is level with the banks for that reason. `coveredAbove` asks whether anything overhangs a point, which is how rain stops under a roof. ## Bodies, steps and slopes ```ts /** What the character collides with as bodies: the piers, a flight of steps, a slab and crates. */ const world = new PhysicsWorld(); const solid: { x: number; y: number; z: number; hx: number; hy: number; hz: number; qz?: number; }[] = [ { x: -2, y: 1.2, z: 0, hx: 0.4, hy: 1.2, hz: 1.2 }, { x: 2, y: 1.2, z: 0, hx: 0.4, hy: 1.2, hz: 1.2 }, ]; for (let step = 0; step < 8; step += 1) { solid.push({ x: 10 + step * 0.6, y: 2.6 + (step + 1) * 0.125, z: -8, hx: 0.3, hy: (step + 1) * 0.125, hz: 1.2, }); } solid.push({ x: 16, y: 3.6, z: -8, hx: 1.5, hy: 1, hz: 2 }); for (const box of solid) { world.addBody({ type: BODY_STATIC, shape: boxShape(box.hx, box.hy, box.hz), x: box.x, y: box.y, z: box.z, }); } /* A slab falling fifty degrees from the platform's edge toward +z: too steep to stand on, so a character who walks off the platform onto it slides down to the bank. */ const tilt = (50 * Math.PI) / 360; world.addBody({ type: BODY_STATIC, shape: boxShape(1.4, 0.15, 1.3), x: 16, y: 3.6, z: -5.15, qx: Math.sin(tilt), qw: Math.cos(tilt), }); const crates: number[] = []; for (let i = 0; i < 4; i += 1) { crates.push( world.addBody({ type: BODY_DYNAMIC, shape: boxShape(0.4, 0.4, 0.4), x: -9 + i * 1.1, y: 3.1, z: -6, density: 150, }), ); } ``` Against bodies the controller steps up any lip within `stepHeight` and slides down any face steeper than `slopeCos`. A dynamic body it walks into is pushed, by `pushStrength`. The example's circuit climbs the steps and walks off the platform onto the slab, where it slides to the bank. ## Water ```ts /** The pond: falling in costs speed on every axis, and a drop settles instead of sinking fast. */ const POND = { x: -12, z: 9, half: 3.4, level: 1.8 }; const sea = createBuoyancy({ level: POND.level, drag: 3, sinkSpeed: -1.2 }); ``` `createBuoyancy({ level, drag, sinkSpeed })` describes a body of water, and `applyBuoyancy(water, y, state, dt)` acts on anything with `velX`, `velY` and `velZ`, a controller included, and answers whether it is submerged. A kinematic body displaces nothing, so this is not a buoyant force: it is drag on every axis, so falling in costs speed and is a setback and never a shortcut, and a sinking speed the fall settles to. ## When the geometry traps a body A controller resolves a move against geometry and has no opinion about a body that has been asking to move for half a second and going nowhere. `StallEscape` does: ```ts /** Thirty ticks of going nowhere arms it, and it may push four metres before calling it sealed. */ const escape = new StallEscape({ stalledTicks: 30, budgetM: 4 }); /** Last in the tick, after the move has resolved: it reads where the body ended up. */ export function unstick( body: Body, colliders: ColliderSet, input: StallInput, respawn: () => void, ): void { if (escape.step(body, colliders, input) === ESCAPE_SEALED) respawn(); } ``` It judges progress as net travel over a window, never one tick's movement, since a body jammed under a low ceiling jitters while staying put. Grounded, supported and headroom are three separate facts: a body with all three can jump out and is not stuck however blocked it is, because being blocked is what a wall is for. An `EscapeVeto` refuses directions the world would not allow, such as off a deck edge that has no collider. The answer is `ESCAPE_IDLE`, `ESCAPE_EASED`, `ESCAPE_PUSHED` or `ESCAPE_SEALED`, and sealed is reported, never acted on: what being trapped costs a player is the game's decision. ## Movement of your own `SweptStep` moves a kinematic body horizontally through a `ColliderSet` one axis at a time, with the rules a sweep alone does not hold: a kerb to step over, a face the world calls solid with no collider, a corner where both axes refuse at once. A `WorldOpinion` supplies what the colliders do not know. `accelerateAlong(state, wishX, wishZ, wishSpeed, accel, dt)` is the accelerate a first-person game uses, clamped against the shortfall along the wish direction, which is also what makes air-strafing work, and it returns how much speed it added. ```ts /** Toward the wish, clamped against the shortfall along it: what makes air-strafing work. */ export function accelerate( velocity: { velX: number; velZ: number }, wishX: number, wishZ: number, dt: number, ): number { return accelerateAlong(velocity, wishX, wishZ, 7, 50, dt); } ``` --- # Vehicles Simulation. https://driftengine.dev/docs/simulation/vehicles A raycast vehicle of a chassis body and wheels that are rays on springs, gripping by tyre curves you supply, on bodies or an analytic road. A `Vehicle` is a chassis, an ordinary dynamic body, and wheels that are rays and not bodies. Each wheel casts down from its anchor, compresses a spring and a damper against what it finds, and pushes the chassis with its load, its drive and its grip, all as impulses at the anchor, so roll, pitch and weight transfer come out of the solver without being modelled. A raycast wheel cannot wedge in geometry or catch on another wheel, and it is stable at ordinary substep counts, which wheels made of bodies on joints are not. In exchange a car on its side behaves as a box. The example is a car on a ring of cones, with a ramp across its line. The driver is a DriftScript module: the keys or a stick, or a lap the car drives by itself until a key is pressed. Switch the tyres to ice. (This chapter runs the `vehicle` example at https://driftengine.dev/docs/simulation/vehicles.) ## The car ```ts /** * The chassis, a box of about 1,200 kilograms, and four wheels: the front ones steer, all drive. * * It starts on the line through the middle of the ramp, facing it, so the first press of W goes * straight up and off the end. Seven metres short of the ramp the chassis clears the outer ring of * cones by almost a metre; started at twelve, it overlapped one and came to rest propped on it with * two wheels in the air, and no key moved it. */ const chassis = world.addBody({ type: BODY_DYNAMIC, shape: boxShape(0.9, 0.35, 2), x: 18, y: 1.2, z: -7, density: 240, }); const WHEELS = [ { x: -0.85, y: -0.2, z: 1.3, steers: true, driven: true }, { x: 0.85, y: -0.2, z: 1.3, steers: true, driven: true }, { x: -0.85, y: -0.2, z: -1.3, driven: true }, { x: 0.85, y: -0.2, z: -1.3, driven: true }, ]; const TYRES: Record> = { tarmac: { longitudinal: defaultTyreCurve(1.2), lateral: defaultTyreCurve(1.4) }, ice: { longitudinal: defaultTyreCurve(0.25), lateral: defaultTyreCurve(0.3) }, }; let tyres = flag('tyres', 'tarmac'); let car = new Vehicle(chassis, { wheels: WHEELS, ...TYRES[tyres] }); ``` `new Vehicle(chassis, options)` takes the chassis's body index and: - `wheels`, each a `WheelOptions`: its anchor `x`, `y`, `z` in the chassis's frame, `radius` (0.35), `suspensionTravel` (0.3), spring `stiffness` in newtons a metre (40,000) and `damping` (4,000), and whether it `steers` and is `driven`. - `maxSteerTangent`, the largest steering angle as its tangent, 0.6. - `engineForce`, newtons at full throttle shared across the driven wheels (6,000), and `brakeForce` (9,000). - `longitudinal` and `lateral` tyre curves. - `filter`, which bodies the wheels see; the chassis is always ignored. - `ground`, a [ground surface](https://driftengine.dev/docs/simulation/characters#ground-surfaces) consulted where a wheel's ray found no body, so an analytic road is a road for wheels as well as feet. `update(world, dt, input)` runs one tick and is called before `world.step`. The input is `throttle` from −1 to 1, `brake` from 0 to 1 and `steer` from −1 to 1. Afterwards `grounded`, `compression` and `contact` say, per wheel, whether it touched, how far its spring is compressed and where. Compression stops at the suspension's travel: past it the wheel has bottomed out, and the chassis takes the load through its own collider, as a bump stop does. ## Tyres Grip is a table you supply: a `TyreCurve` is `slip` against `force`, the fraction of the wheel's load available as grip at that slip, read by linear interpolation and held past its last point. `defaultTyreCurve(peak)` rises to `peak` at a slip of 0.2 and falls away to 70% of it, which is what a tyre past its limit does, and `sampleTyreCurve` reads one. The tick may not use `sin` or `atan`, so the closed-form tyre models are out, and a table is edited by moving a point, which is easier to reason about than a coefficient. The example's tarmac is the defaults, 1.2 along and 1.4 across, and its ice a fifth of that; the curves are the vehicle's options, so the switch builds a new `Vehicle` on the same chassis. ## The driver, in DriftScript ```drs // Forward on the stick is throttle, back is reverse, sideways is steering, and Space brakes. fn drive(pedals: mut Pedals, actions: Actions) { pedals.throttle = 0 - input.axisY(actions, "move") pedals.steer = 0 - input.axisX(actions, "move") if input.down(actions, "brake") { pedals.brake = 1 } else { pedals.brake = 0 } } ``` and, until a key is pressed, the lap it drives by itself: ```drs // Steer toward a point ahead on a circle, at a steady throttle: the car laps by itself. fn lap(pedals: mut Pedals, x: f32, z: f32, heading: f32, radius: f32) { // The point a third of a radian further round the circle than the car is now. let around = math.atan2(z, x) + 0.35 let tx = math.cos(around) * radius - x let tz = math.sin(around) * radius - z // The turn from where the car points to the target, wrapped to half a turn either way. let turn = math.atan2(tx, tz) - heading let wrapped = math.atan2(math.sin(turn), math.cos(turn)) pedals.steer = math.clamp(wrapped * 2, -1, 1) pedals.throttle = 0.6 pedals.brake = 0 } ``` ```ts /** The driver, hosted, and the pedals it sets each tick. */ const driver = hostScript(driveScript); interface Pedals { throttle: number; brake: number; steer: number; } const pedals = exported<() => Pedals>(driver, 'createPedals')(); type Drive = (pedals: Pedals, actions: ActionMap) => void; type Lap = (pedals: Pedals, x: number, z: number, heading: number, radius: number) => void; if (import.meta.hot) { import.meta.hot.accept('./drive.drs', (next) => { if (next !== undefined) patchModule(driver, next as Record, { Pedals: [pedals] }); }); } ``` --- # Ragdolls and cloth Simulation. https://driftengine.dev/docs/simulation/ragdolls-and-cloth Ragdolls built from a skeleton's joints and driven toward an animated pose, and cloth that hangs, blows, drapes and pushes what it lands on. A ragdoll turns a skeleton into bodies and joints, so a character can fall, be knocked about, or stagger and try to stand. Cloth is a sheet of particles held together by constraints, for a flag, a cape or a tablecloth. Both live in the physics world and collide with its bodies. The example shoves a figure down a flight of stairs every six seconds, flies a flag in a gusting wind, and drops a sheet over a crate. Choose what the figure does after each shove: go limp, stagger, or hold its pose. (This chapter runs the `ragdoll` example at https://driftengine.dev/docs/simulation/ragdolls-and-cloth.) ## A ragdoll from a skeleton ```ts /** A standing figure as joints: where each is, and which joint it hangs from. */ const JOINTS: [number, number, number, number][] = [ [-1, 0, 1.0, 0], // hips [0, 0, 1.3, 0], // spine [1, 0, 1.55, 0], // chest [2, 0, 1.72, 0], // neck [3, 0, 1.95, 0], // head [2, 0.2, 1.6, 0], // left shoulder [5, 0.45, 1.6, 0], // left elbow [6, 0.7, 1.6, 0], // left hand [2, -0.2, 1.6, 0], // right shoulder [8, -0.45, 1.6, 0], // right elbow [9, -0.7, 1.6, 0], // right hand [0, 0.1, 0.95, 0], // left hip [11, 0.1, 0.5, 0], // left knee [12, 0.1, 0.06, 0], // left foot [0, -0.1, 0.95, 0], // right hip [14, -0.1, 0.5, 0], // right knee [15, -0.1, 0.06, 0], // right foot ]; const parents = JOINTS.map(([parent]) => parent); /** The standing pose as world matrices, sixteen floats a joint, placed on the platform. */ function standing(x: number, y: number, z: number): Float32Array { const matrices = new Float32Array(JOINTS.length * 16); JOINTS.forEach(([, jx, jy, jz], j) => { matrices.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x + jx, y + jy, z + jz, 1], j * 16); }); return matrices; } /** The same pose as each joint relative to its parent, which is what `drive` steers toward. */ const pose = { translation: new Float32Array(JOINTS.length * 3), rotation: new Float32Array(JOINTS.length * 4), scale: new Float32Array(JOINTS.length * 3).fill(1), }; JOINTS.forEach(([parent, jx, jy, jz], j) => { const [, px, py, pz] = JOINTS[parent] ?? [0, 0, 0, 0]; pose.translation.set(parent < 0 ? [jx, jy, jz] : [jx - px, jy - py, jz - pz], j * 3); pose.rotation[j * 4 + 3] = 1; }); ``` `ragdollFromBones(world, parents, worldMatrices, options)` takes a skeleton as plain data: a parent index per joint, −1 for a root, and each joint's world matrix, sixteen floats a joint. A skeleton from `@driftengine/animation` already has both, and neither package imports the other. ```ts /** A capsule a bone and a joint between each bone and its parent's, with knees nearly hinges. */ const swing = new Float32Array(JOINTS.length).fill(Math.SQRT1_2); for (const knee of [12, 13, 15, 16]) swing[knee] = 0.9; const doll = ragdollFromBones(world, parents, standing(-4, 3, 0), { density: 600, swingCos: swing, }); /** Put the doll back on its feet at the top of the stairs and push it toward them. */ function shove(count: number): void { doll.sync(world, standing(-4, 3, 0)); for (const body of doll.bodyOf) { if (body < 0) continue; world.setVelocity(body, 3.5, 0.5, (hashToUnit(count) - 0.5) * 1.5); } } ``` A bone is a joint and its parent. Each bone becomes a capsule standing along the bone, and each joint between two bones a cone-twist joint anchored at the end they share. Bones hanging from a joint that has no bone of its own, such as the spine and thighs under a root at the hips, are jointed to one another at the head they share. The options: - `radiusRatio`, a capsule's radius as a fraction of its bone's length (0.22), with `minRadius` as a floor, and `minLength`, below which a bone gets no body, which skips a rig's leaf tips. - `density`. - `swingCos` and `twistSin`, the cone each joint may swing in and how far it may twist, as one number for every joint or one per joint, indexed as `parents` is. A knee is nearly a hinge and a shoulder nearly a ball, so one number for a whole body is wrong somewhere: too loose, and a landing body folds a limb through its torso. Write the numbers out, since `Math.cos` may differ by a last digit between two engines and a limit is compared every tick. - `selfCollision`, on by default: bones collide with the rest of their own doll, except bones that share an end, which overlap there by construction. Off is cheaper and lets a foot reach inside a ribcage, so keep it for a crowd nobody looks at closely. - `layer` and `mask`. The `Ragdoll` it returns has `bodyOf`, the body each joint's bone is or −1, and `boneCount`. ### Driving it - `sync(world, worldMatrices)` puts every body back on its bone and clears its velocity. A ragdoll is built once, so between reactions its bodies sit where the last one left them; a reaction starts with `sync`, from the pose the character is in now. - `drive(world, pose, weight)` steers the bodies toward an animated pose: 1 tracks it, 0 goes limp, and between is a hit reaction, a body knocked off its pose that tries to return. The pose is anything with `translation`, `rotation` and `scale` per joint, relative to its parent, which an animation `Pose` is. - `writePose(out)` writes the ragdoll's shape back into a pose, so the skinned character is drawn where the bodies are. Each joint is turned by the bone that starts at it, the one a skinned limb follows: the forearm's body turns the elbow. Each joint is placed along its own bone as that bone's body holds it, so where a joint has several bones below it, the hips over a spine and two thighs, every branch is drawn on its own body and not swung by the first one's turn. A bone shorter than `minLength`, such as a collar sitting on the chest joint, gets no body and is transparent: what hangs below it is jointed to the bone above it, and does not collide with the bones it meets there. A root's rotation is written in the frame of the node placed at `rootX`, `rootY` and `rootZ`, so that node carries no rotation of its own. ## Cloth ```ts /** A flag twenty cells by twelve, hanging from a pole: the cells along the pole are pinned. */ const FLAG_COLUMNS = 20; const FLAG_ROWS = 12; const flagGrid = makeClothGrid(FLAG_COLUMNS, FLAG_ROWS, 0.08); for (let i = 0; i < flagGrid.positions.length; i += 3) { /* Turned to hang: columns run out from the pole along +z, rows run down. */ const along = flagGrid.positions[i] ?? 0; const down = flagGrid.positions[i + 2] ?? 0; flagGrid.positions.set([5, 4.5 - down, along - 0.8], i); } const flagCloth = new ClothBody(flagGrid.positions, flagGrid.links, flagGrid.bendLinks, { damping: 0.05, }); for (let row = 0; row < FLAG_ROWS; row += 1) flagCloth.pin(row * FLAG_COLUMNS); /** A sheet dropped over a crate, handing it back the momentum it loses on it. */ const crates = [ world.addBody({ type: BODY_DYNAMIC, shape: boxShape(0.5, 0.5, 0.5), x: 3, y: 0.5, z: 3.2, density: 40, }), ]; const SHEET = 18; let sheet = dropSheet(); function dropSheet(): ClothBody { const grid = makeClothGrid(SHEET, SHEET, 0.12); for (let i = 0; i < grid.positions.length; i += 3) { grid.positions[i] = (grid.positions[i] ?? 0) + 2; grid.positions[i + 1] = 2.5; grid.positions[i + 2] = (grid.positions[i + 2] ?? 0) + 2.2; } return new ClothBody(grid.positions, grid.links, grid.bendLinks, { /* Cloth contacts carry no friction, so air and floor alike are this damping: enough that a sheet settles where it lands and falls the way a sheet falls. */ damping: 2, coupling: 1, particleMass: 0.2, selfDistance: 0.1, thickness: 0.05, }); } ``` `makeClothGrid(columns, rows, spacing)` builds a grid of particles in the XZ plane with its `links`, stretch and shear constraints, and `bendLinks`, constraints that skip a particle and so resist folding. `new ClothBody(positions, links, bendLinks, options)` makes cloth of them, and `step(world, dt)` advances it after the world, colliding its particles with the world's bodies; pass `null` for cloth in empty space. `pin(index)` holds a particle where it is, as the flag's edge is held to its pole, and `pin(index, false)` lets it go. The cloth is solved by XPBD, so its stiffness is a compliance and means the same at any iteration count: - `stretchCompliance` and `bendCompliance`, metres of give a newton; zero is inextensible. - `iterations`, solver passes a tick (8). - `damping`, how much velocity it loses a second. Its contacts carry no friction, so damping is what stops a sheet sliding across a floor; the example's sheet uses 2. - `thickness`, how far a particle is held off a surface. - `gravityX`, `gravityY` and `gravityZ`. - `coupling`, from 0 to 1, how much of the momentum a particle loses against a body is handed back to that body, at the contact, so a sheet landing on one end of a plank tips it; and `particleMass`, in kilograms, which the coupling measures that momentum in (50 grams). - `selfDistance`, in metres, how close two particles not joined by a link may come, so a sheet does not pass through itself. A little under the grid spacing is the place to start. `position`, `velocity` and `invMass` are the particles' state, `count` their number. The example's wind is a velocity added to every free particle each tick. Bending resists bowing, not orientation, so cloth will not hold itself out like a cantilever. ### Drawing it A cloth's particles change every frame, so the mesh drawing it is created with `{ dynamic: true }` and rewritten with `updateMesh(mesh, positions, normals)`, which reuses the buffer instead of allocating one a frame. The example computes normals from each particle's neighbours, and draws both sides of every triangle. ## Cloth on a character A cape, a skirt or the tails of a coat is cloth that also follows a skeleton: most of it moves with the body, some of it swings free, and none of it may pass through the legs. That is a skinned cloth, and it is two things a model carries for each garment: a coarse simulation, and the finer mesh drawn, each of whose vertices is told which simulation triangle to follow. The simulation is a `SkinnedClothSetup` from `@driftengine/physics`: particles in the bind pose and their inverse masses, 0 for one that follows its skinning exactly; up to eight bone influences a particle with the inverse binds; stretch and bending constraints, each with a compliance in metres per newton, the inverse of a stiffness; tethers to fixed particles; limits that keep a particle within a sphere of its skinned place, or behind or in front of one; spheres and tapered capsules on bones for it to collide with; and parameters, every one with a default. `validateClothSetup` refuses a malformed set-up by name. A garment with variations has a set-up for each. The mesh is an ordinary skinned mesh with a `ClothBindingData`: for every vertex, the triangle it follows, where on it, how far off it along its normal, and how much, from 0 for skinned to 1 for cloth. `renderer.createClothBinding(mesh, data)` checks it against the mesh. `createSkinnedCloth(renderer, setup)`, from `@driftengine/core`, builds the solver. On WebGPU it runs on the device, and under WebGL2 the CPU solver it is checked against runs instead; `runsOn` says which. Once a frame, before the draws: ```ts advanceWindField(wind, profile, time, dt, 1); cloth.setWind(wind.velocityX, 0, wind.velocityZ); cloth.step(globals, model, dt); ``` `step` takes the joints' global matrices, not the palette, because a collider sits on a joint's own frame. It advances in whole fixed steps and draws on the remainder, as the rest of the simulation does. A jump past the set-up's teleport distance or angle resets the cloth by itself; a cut in a cinematic is `reset()`. The wind is the scene's one wind, sampled once and handed over. Every whole step `dt` holds is run, so a slow frame hands the next one more steps to take and can make it slower in turn. A caller handing the cloth each frame's time sets `maxSteps` in the set-up's parameters, two to four, and the time past them is dropped rather than owed: the cloth then runs slower than the clock for as long as the frames do. Unset, `advance(1)` is a whole second of cloth. A garment made to hold a shape gravity would undo, such as styled hair pinned at its roots, sets `pull` in its parameters: a stiffness drawing every free particle back toward where its skinning puts it, in metres a second squared for each metre away. The limits cannot do this, because a max distance is a sphere a particle may fall anywhere inside, so hair falls to its edge and hangs. With a pull it keeps its shape at rest, sitting `9.81 / pull` metres below it under gravity whatever the step, swings out of it as the body moves and settles back, as fast as `damping` lets it. A value authored as a share `k` of the offset kept a step, at a step `s`, is `(1 / k - 1) / s²`, and keeps exactly that share at that step. A garment held unevenly weighs its pull particle by particle with `pullWeights` in the set-up, one a particle from 0 to 1: a strap held at its root and hanging free at its tip, a styled fringe held nearly whole beside a coat that swings free. Each particle keeps `1 / (1 + w · pull · h²)` of its offset each substep, `h` the substep's length, and sits `9.81 / (w · pull)` metres below its skinned place at rest. Unset, every particle takes the whole pull. A weight of 0 is no pull at all, a free particle rather than a pinned one: `inverseMass` is what pins. Several garments step as one with `createSkinnedClothSet(renderer, setups)`: one compute pass and one submit a frame for all of them, and a step costs one garment's dispatches however many the set holds. Each garment is named by its index; pose each, then step the set once: ```ts /** Every garment of a character in one set, each held to two steps a frame. */ export function wardrobe(renderer: RendererApi, garments: readonly SkinnedClothSetup[]) { return createSkinnedClothSet( renderer, garments.map((setup) => ({ ...setup, parameters: { ...setup.parameters, maxSteps: 2 } })), ); } /** Once a frame, before the draws: each garment's rig, then one step for all of them. */ export function stepWardrobe( set: SkinnedClothSet, globals: Float32Array, model: Float32Array, dt: number, ): void { for (let g = 0; g < set.particles.length; g += 1) set.setPose(g, globals, model); set.step(dt); } ``` The garments of a set step together, so they share `step`, `substeps`, `iterations` and `maxSteps`, and a set whose garments disagree on one is refused by name. Everything else is each garment's own, its settle and blend steps included: a garment reset alone settles while the rest wait for it. A colour of constraints is dispatched over the most any garment has, so a set gains most where its garments are alike. Measured on a desktop GPU, fifteen capes took 0.79 ms a frame as a set and 8.9 ms as fifteen solvers; `particles[g]` is what `setCloth` draws garment `g` by. The draw places the mesh's vertices by the cloth in its vertex stage: ```ts renderer.setSkinPalette(palette); renderer.drawMesh(body, model); if (bound) renderer.setCloth(binding, cloth.particles); renderer.drawMesh(capeHandle, model); renderer.setCloth(null); renderer.setSkinPalette(null); ``` The shadow takes the same binding, through `sink.skinnedMesh(mesh, model, palette, material, { binding, particles })`, or the garment casts the shadow of its skinning. Self-collision is accepted in a set-up and not simulated: a garment its colliders and backstops hold looks right without it. `examples/garment/` builds a cape by hand, and the handbook maps a garment cooked elsewhere onto these two arrays. --- # Animation Simulation. https://driftengine.dev/docs/simulation/animation Skeletons, clips sampled at a time you supply, blend trees, state machines, two-bone IK, retargeting, root motion, springs and morph targets. `@driftengine/animation` is skeletons, clips, poses and the graphs over them, for 6.1 KB gzipped on top of core. Everything in it is a function of a time you hand it, and nothing in it reads a clock, so an animated character replays exactly and a playhead can scrub it backwards. It never touches the GPU either: it produces a palette, sixteen floats a joint, and core's renderer skins a mesh by it. The example builds a figure in code: a skeleton, a mesh bound to it a piece a bone, and three clips written as keys. It walks a circle and reaches for a lantern with its right hand as it passes. Switch it between idle, walk and run, and it eases from one to the other mid-stride. The pace and the reach are a DriftScript module: under `npm run examples`, edit it and save, and the figure takes the change without the page reloading. (This chapter runs the `animation` example at https://driftengine.dev/docs/simulation/animation.) ## A skeleton and a pose ```ts /** Seventeen joints in a relaxed standing pose, each with its parent and a name. */ const JOINTS: [string, number, number, number, number][] = [ ['hips', -1, 0, 1.0, 0], ['spine', 0, 0, 1.25, 0], ['chest', 1, 0, 1.5, 0], ['neck', 2, 0, 1.68, 0], ['head', 3, 0, 1.82, 0], ['leftShoulder', 2, 0.22, 1.55, 0], ['leftElbow', 5, 0.25, 1.27, 0], ['leftHand', 6, 0.27, 1.0, 0], ['rightShoulder', 2, -0.22, 1.55, 0], ['rightElbow', 8, -0.25, 1.27, 0], ['rightHand', 9, -0.27, 1.0, 0], ['leftHip', 0, 0.1, 0.95, 0], ['leftKnee', 11, 0.1, 0.52, 0], ['leftFoot', 12, 0.1, 0.08, 0], ['rightHip', 0, -0.1, 0.95, 0], ['rightKnee', 14, -0.1, 0.52, 0], ['rightFoot', 15, -0.1, 0.08, 0], ]; /** The inverse of each joint's place in the bind pose: here only a translation, undone. */ const inverseBind = new Float32Array(JOINTS.length * 16); JOINTS.forEach(([, , x, y, z], j) => { inverseBind.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -x, -y, -z, 1], j * 16); }); const skeleton = new Skeleton( JOINTS.map(([name, parent]) => ({ name, parent })), inverseBind, ); /** The bind pose as each joint relative to its parent, which a clip leaves where it does not reach. */ const bind = createPose(JOINTS.length); JOINTS.forEach(([, parent, x, y, z], j) => { const [, , px, py, pz] = JOINTS[parent] ?? ['', -1, 0, 0, 0]; bind.translation.set(parent < 0 ? [x, y, z] : [x - px, y - py, z - pz], j * 3); }); ``` `new Skeleton(joints, inverseBind)` takes each joint's `name` and `parent`, −1 for a root, and an inverse bind matrix a joint: sixteen floats, column-major, taking a vertex from the model's space into that joint's. Parents come before their children, and the constructor refuses a list that is out of order, since the palette is resolved in one pass in index order. A rig imported from glTF or read from a `.drft` file arrives as the same joints and matrices. A `Pose` is three flat arrays, each joint relative to its parent: `translation`, three floats a joint, `rotation`, a quaternion of four, and `scale`, three. `createPose(jointCount)` makes one at rest and `restPose(jointCount, out)` puts one back. `skeleton.applyPose(pose)` resolves it: `world` then holds each joint's matrix in the model's space and `palette` the matrices a skinned mesh is drawn by. ## Skinning ```ts /** A piece of the body a bone, each bound rigidly to the joint the bone hangs from. */ const SKIN: Vec3 = [0.85, 0.66, 0.52]; const CLOTH: Vec3 = [0.3, 0.42, 0.62]; const body = new MeshBuilder(); body.setJoint(0).addBox([0, 1.0, 0], [0.17, 0.1, 0.11], CLOTH); body.setJoint(1).addBox([0, 1.2, 0], [0.16, 0.13, 0.1], CLOTH); body.setJoint(2).addBox([0, 1.45, 0], [0.21, 0.14, 0.12], CLOTH); body.setJoint(3).addCapsule([0, 1.68, 0], 0.045, 0.05, SKIN); body.setJoint(4).addSphere([0, 1.86, 0], 0.13, SKIN, 0, 16, 10); for (const [shoulder, side] of [ [5, 1], [8, -1], ] as const) { body.setJoint(shoulder).addCapsule([side * 0.235, 1.41, 0], 0.055, 0.11, CLOTH); body.setJoint(shoulder + 1).addCapsule([side * 0.26, 1.14, 0], 0.05, 0.1, SKIN); body.setJoint(shoulder + 2).addSphere([side * 0.27, 0.97, 0], 0.055, SKIN); } for (const [hip, side] of [ [11, 1], [14, -1], ] as const) { body.setJoint(hip).addCapsule([side * 0.1, 0.74, 0], 0.075, 0.15, CLOTH); body.setJoint(hip + 1).addCapsule([side * 0.1, 0.3, 0], 0.06, 0.16, [0.25, 0.25, 0.28]); body.setJoint(hip + 2).addBox([side * 0.1, 0.04, 0.05], [0.06, 0.04, 0.11], [0.2, 0.18, 0.16]); } const figure = renderer.createMesh(body.build()); ``` `MeshBuilder.setJoint(index)` binds every vertex added after it to one joint at full weight, which is rigid skinning: right for a figure made of solid pieces, a robot, or a lamp on an arm. A model from a modelling tool carries smooth skinning instead, up to four joints a vertex with a weight each, in the mesh's `joints` and `weights`. ```ts /* The palette is each joint's world matrix times its inverse bind; the mesh deforms by it. */ renderer.setSkinPalette(skeleton.palette); renderer.drawMesh(figure, model); renderer.setSkinPalette(null); ``` `setSkinPalette(palette)` chooses the palette the following draws skin by, and `null` stops. A shadow is cast by the same palette, through the caster sink's `skinnedMesh(mesh, model, palette)`: a skinned mesh handed to `mesh` casts its bind pose, so a running figure would throw the shadow of a statue. Both backends skin in the vertex shader, and a mesh with no joints carries none of it. ### Points in their joints' spaces Some formats store a vertex differently: as up to four points, each in the space of the joint it follows, with a weight each, and a normal in the space of the first. Posed, the vertex is the weighted sum of each point moved by its joint, which ordinary skinning cannot express, since it moves one bind-pose position by a blend of joints. Such a mesh is created `{ dynamic: true }` and given a point skin, which poses it on the device every frame: ```ts /** A mesh stored as points in its joints' spaces, posed on the device once a frame. */ export function posedOnDevice(renderer: RendererApi, data: MeshData, points: PointSkinData) { const mesh = renderer.createMesh(data, { dynamic: true }); const skin = renderer.createPointSkin(mesh, points); /* Each joint's transform into the mesh's model space: no inverse bind, as the points have none. */ return (joints: Float32Array, model: Float32Array) => { renderer.posePointSkin(skin, joints); renderer.drawMesh(mesh, model); }; } ``` `PointSkinData` holds four joint indices and four weights a vertex, four points of three floats a vertex, and one normal a vertex in its first joint's space; an influence of weight 0 is skipped. The joints handed to `posePointSkin` are each joint's transform into the mesh's model space, sixteen floats a joint, with no inverse bind, since the points are already in each joint's space. WebGPU poses in a compute pass and WebGL2 by transform feedback, into the mesh's own positions and normals, so every pass draws it as any dynamic mesh, its shadow and its motion included, and the main thread hands over only the joints. The mesh's bounds become a box around each joint's reach, so it is culled as it moves without the posed vertices coming back to the CPU. `disposePointSkin` frees it. A skin that changes shape a few hundred vertices at a time, a hand closing or a picture on a face taken away, is rewritten in part rather than made again: `updatePointSkin(skin, first, data)` takes vertices `first` onward, as many as `data` holds, its four arrays a range's worth, and sends only those. The pose after it reads the rewrite and a pose before it does not, on both backends. The bounds take in what a rewrite reaches and never shrink, since the vertices it replaced may have been the farthest, so a skin that changes back and forth settles at the box of all its shapes; `createPointSkin` measures a skin afresh. A joint none of its vertices named before grows what the device holds for the joints, once. ## Clips ```ts /** A rotation about x as a quaternion: positive swings a hanging limb forward. */ const pitch = (a: number): number[] => [-Math.sin(a / 2), 0, 0, Math.cos(a / 2)]; /** A looping clip from keys spread evenly over its duration, a joint's angles at a time. */ function clip( name: string, durationSec: number, angles: Record, bob: number[], ): AnimationClip { const tracks: JointTrack[] = []; for (const [joint, keys] of Object.entries(angles)) { const times = Float32Array.from(keys, (_, i) => (i / (keys.length - 1)) * durationSec); tracks.push({ joint: Number(joint), path: 'rotation', times, values: Float32Array.from(keys.flatMap(pitch)), }); } const times = Float32Array.from(bob, (_, i) => (i / (bob.length - 1)) * durationSec); tracks.push({ joint: 0, path: 'translation', times, values: Float32Array.from(bob.flatMap((y) => [0, y, 0])), }); return { name, durationSec, tracks }; } /** One way, back through the middle, and the other way: a leg or an arm across a stride. */ const swing = (a: number): number[] => [a, 0, -a, 0, a]; /** A stride a second: legs and arms swing opposite, a knee folds as its foot passes, the hips dip. */ const WALK = clip( 'walk', 1, { 11: swing(0.45), 14: swing(-0.45), 12: [0, -0.15, 0, -0.6, 0], 15: [0, -0.6, 0, -0.15, 0], 5: swing(-0.35), 8: swing(0.35), }, [1.0, 0.97, 1.0, 0.97, 1.0], ); ``` An `AnimationClip` is a `name`, a `durationSec` and its `tracks`. A `JointTrack` names a `joint` and a `path`, `'translation'`, `'rotation'` or `'scale'`, with `times` ascending in seconds and `values`, three floats a key, or four for a rotation. Clips usually come from a file; these are written by hand to show there is nothing more to one. `sampleClip(clip, seconds, out)` brings the time into the clip, so a clip loops, interpolates between the keys either side, slerping rotations, and writes into `out`. A joint no track names is left as it was, so a clip that moves one arm can be sampled over a pose holding the rest of the body. Below a tree, three functions combine poses, each into a pose you own: - `blendPoses(a, b, t, out)` interpolates every channel of two poses, so `out` decides what a joint neither pose moved blends from. - `addPose(base, delta, weight, out)` layers a delta on a base: a breath, a flinch, a lean. - `setJoint(pose, joint, translation, rotation, scale)` writes one joint. Nothing here allocates per frame; every sampler and blend fills a target you made once. ## Blend trees ```ts /** Idle, walk and run over one speed parameter. The walk and run take distance as their clock. */ const tree = new BlendTree( { kind: 'oneDimensional', parameter: 'speed', children: [ { at: 0, node: { kind: 'clip', clip: IDLE } }, { at: 1.4, node: { kind: 'clip', clip: WALK, clock: 'walkClock' } }, { at: 4, node: { kind: 'clip', clip: RUN, clock: 'runClock' } }, ], }, JOINTS.length, bind, ); const pose = createPose(JOINTS.length); ``` `new BlendTree(root, jointCount, bind)` takes a tree of `BlendNode`s: - `clip`, a clip, sampled at the tree's time or at the value of its `clock`. - `lerp`, two nodes `a` and `b` blended by a `parameter` from 0 to 1. - `oneDimensional`, `children` at stops along a `parameter`, ascending; a value between two stops blends the two either side. This is a blend space over one axis, the usual shape for locomotion. `set(parameter, value)` sets one and throws on a name no node takes, since a misspelt parameter would otherwise do nothing visible. `evaluate(seconds, out)` samples the whole tree. Give it the bind pose whenever the clips rotate and do not translate, which is most clips: a blend interpolates every channel, so without one the joints a clip leaves alone blend toward zero and fold onto their parents. ### Clocks A stride has to advance with distance, or the feet slide while the body passes over them; an idle has to advance with time, since someone standing still still breathes. So a `clip` node may name a `clock`, a parameter holding its own time in seconds, and a node without one keeps the time given to `evaluate`. The example's walk and run keep metres walked, scaled to each clip's pace, and its idle keeps the frame clock. A name is either a weight or a clock, and the tree refuses one used as both. ## The rig's logic, in DriftScript ```drs // One frame: ease the pace, sample the blend, and reach where the lantern is near. // The lantern's position is given in the figure's own frame, which is where its joints are. fn animate(gait: mut Gait, tree: Blend, skeleton: Skeleton, pose: Pose, at: f32, dt: f32, lanternX: f32, lanternY: f32, lanternZ: f32) { // A metre a second of change in pace a second, either way. gait.speed = gait.speed + math.clamp(gait.wanted - gait.speed, 0 - dt, dt) gait.travelled = gait.travelled + gait.speed * dt animation.blendSet(tree, "speed", gait.speed) // Each clip's time is distance: the walk plays at its own pace at 1.4 metres a second, the // run at 4, so a foot stays where it was put whatever the pace. animation.blendSet(tree, "walkClock", gait.travelled / 1.4) animation.blendSet(tree, "runClock", gait.travelled / 4) animation.blendAt(tree, at, pose) // The right shoulder, elbow and hand are joints 8, 9 and 10. Reach within a metre and a half, // elbow bending down and back. let dx = lanternX + 0.2 let dy = lanternY - 1.6 let dz = lanternZ let near = math.sqrt(dx * dx + dy * dy + dz * dz) < 1.5 gait.reached = false if gait.reaching && near { gait.reached = animation.reach(skeleton, pose, 8, 9, 10, lanternX, lanternY, lanternZ, -0.4, 0.8, -1) } } ``` ```ts /** The rig's logic, hosted, and its record of the pace. */ const rig = hostScript(rigScript); interface Gait { wanted: number; speed: number; travelled: number; reaching: boolean; reached: boolean; } const gait = exported<() => Gait>(rig, 'createGait')(); type Animate = ( gait: Gait, tree: BlendTree, skeleton: Skeleton, pose: Pose, at: number, dt: number, x: number, y: number, z: number, ) => void; if (import.meta.hot) { import.meta.hot.accept('./rig.drs', (next) => { if (next !== undefined) patchModule(rig, next as Record, { Gait: [gait] }); }); } ``` A script drives a tree its host built: the host holds the skeleton and knows the bind pose, so building trees stays in TypeScript, and a script sets parameters and samples. `drift/animation` offers: - `blendSet` and `blendAt`, a tree's parameter and its evaluation. - `sample`, a clip at a time, and `blend`, two poses into a third. - `pose` and `toRest`, a pose at rest and a pose put back to rest. - `reach`, the two-bone solve below. - `motion`, `rootMotion` and `stripRoot`, root motion, with `motionX`, `motionY` and `motionZ` for its step and `motionTurnX` to `motionTurnW` for its turn. The switches set `gait.wanted` and `gait.reaching` on the record the page holds, and a save of the module keeps the record, so the figure carries on from where it was. ## Reaching `solveTwoBone(skeleton, pose, root, mid, tip, target, pole)` bends a chain of two bones, a shoulder, elbow and hand or a hip, knee and foot, so its tip lands on a target, writing the two rotations into the pose. The target and the pole are points in the skeleton's own space, which is why the example turns the lantern into the figure's frame first. It answers whether the target was in reach; one out of reach straightens the chain toward it, as an arm reaching too far extends. The pole is a point the middle joint leans toward. A straight chain has no plane to bend in, and without a pole the elbow would flip as the character turned; the example's points down and behind the shoulder. The solve is closed form, so its answer does not depend on an iteration count. Limits and twist are left to the game, which knows how far its knees may bend. ## State machines ```ts /** Ground and air: a locomotion tree, a jump clip, and the fades between them. */ export function locomotion( walk: AnimationClip, run: AnimationClip, jump: AnimationClip, jointCount: number, bind: Pose, ): { machine: AnimationStateMachine; gait: BlendTree } { const gait = new BlendTree( { kind: 'lerp', parameter: 'speed', a: { kind: 'clip', clip: walk }, b: { kind: 'clip', clip: run }, }, jointCount, bind, ); const air = new BlendTree({ kind: 'clip', clip: jump }, jointCount, bind); const machine = new AnimationStateMachine( [ { name: 'ground', tree: gait }, { name: 'air', tree: air }, ], [ { from: 'ground', to: 'air', durationSec: 0.1, when: (p) => (p.grounded ?? 1) === 0 }, { from: 'air', to: 'ground', durationSec: 0.2, when: (p) => (p.grounded ?? 1) === 1 }, ], jointCount, bind, ); return { machine, gait }; } /** Each tick: the machine reads its own parameters, and each tree reads its own. */ export function animateLocomotion( rig: { machine: AnimationStateMachine; gait: BlendTree }, speed: number, grounded: boolean, dt: number, out: Pose, ): void { rig.gait.set('speed', Math.min(1, speed / 4)); rig.machine.set('grounded', grounded ? 1 : 0); rig.machine.advance(dt); rig.machine.evaluate(out); } ``` `new AnimationStateMachine(states, transitions, jointCount, bind)` takes states, each a `name` and a tree, and transitions, each `from`, `to`, a `durationSec` to crossfade over and a `when`, your own predicate over the parameters. The first state is where it starts, and a transition naming a state that does not exist is refused at construction. - `set(parameter, value)` sets a parameter the predicates read, any name, since the predicates are yours. A state's tree keeps its own parameters, set on the tree. - `advance(dt)` moves the active state's clock and any fade, and takes the first transition out of the active state whose condition holds. A fade, once started, runs to its end, so a parameter sitting on a threshold does not flick between two states. - `evaluate(out)` writes the pose, crossfaded while a fade runs. - `current` names the active state and `transitioning` says whether a fade is running. Each state keeps its own clock, so a looping clip is not restarted when something else changes, and a zero-length transition is a cut. ## Retargeting ```ts /** A clip authored on one rig, worn by another of different proportions. */ export function wear( clip: AnimationClip, source: Skeleton, target: Skeleton, at: number, scratch: Pose, out: Pose, ): void { const map = buildRetargetMap(source, target); if (map.unmatched.length > 0) console.warn('joints the target lacks:', map.unmatched); sampleClip(clip, at, scratch); retargetPose(map, source, scratch, target, out); } ``` `buildRetargetMap(from, to)` matches two skeletons by exact joint name, and lists in `unmatched` the joints of the source the target lacks; build it once. `retargetPose(map, from, source, to, out)` plays a pose on the other rig. Rotations transfer and translations do not, since two rigs of different proportions share joint orientations and not bone lengths; the root's translation is the exception, as that is where a walk travels. A joint the target has and the source does not, a tail, is left as it was. ## Root motion ```ts /** A walk whose clip carries the travel: the body is moved by it, and the pose stays put. */ const motion = createRootMotion(); export function stepWithRootMotion( clip: AnimationClip, from: number, to: number, body: { x: number; z: number; heading: number }, pose: Pose, ): void { extractRootMotion(clip, 0, from, to, motion); /* The step is in the root's own frame at `from`, so turn it by the body's heading first. */ const c = Math.cos(body.heading); const s = Math.sin(body.heading); const dx = motion.translation[0] ?? 0; const dz = motion.translation[2] ?? 0; body.x += c * dx + s * dz; body.z += -s * dx + c * dz; sampleClip(clip, to, pose); /* Without this the root moves in the pose as well, and the character goes twice as far. */ stripRootMotion(clip, 0, pose); } ``` Some clips carry their own travel: the root walks forward in the clip, and the character should move exactly as far. `extractRootMotion(clip, rootJoint, from, to, motion)` answers how far the root went between two times, in the root's own frame at `from`, as a `translation` and a `rotation`. Loops are accumulated, so a clip that wraps between the two times still answers a step forward. `stripRootMotion(clip, rootJoint, pose)` then pins the pose's root to where the clip has it at time zero. The two go together. Extract without stripping and the character moves twice, at double speed. A bob authored on the root leaves the pose along with the travel and arrives in `motion.translation[1]`, so a game whose height is held by a character controller has to put it back in the pose if it wants it. ## Springs ```ts /** A ponytail's tip, two hertz and a little under critical, trailing a head that sways. */ export function ponytail(time: number, out: Float32Array): void { sampleSpring( { frequencyHz: 2, damping: 0.6, maxOffsetM: 0.3 }, (t, at) => { /* A pure function of the time it is handed: called for times before `time` too. */ at[0] = Math.sin(t * 1.5) * 0.2; at[1] = 1.7; at[2] = 0; }, time, out, ); } /** A chain of four links hanging from the same head: a braid, three floats a link. */ const BRAID: SpringLink[] = [0, 1, 2, 3].map(() => ({ frequencyHz: 3, damping: 0.5, restOffsetM: [0, -0.08, -0.02], })); export function braid(time: number, out: Float32Array): void { sampleSpringChain( BRAID, (t, at) => { at[0] = Math.sin(t * 1.5) * 0.2; at[1] = 1.7; at[2] = 0; }, time, out, ); } ``` Secondary motion, hair, a coat, an antenna, is a damped spring trailing what it hangs from. `sampleSpring(settings, anchorAt, seconds, out)` answers where the spring's mass is at a time, and like a clip it is sampled, not stepped, so a playhead dragged backwards gets the same answer the forward pass got. The settings: - `frequencyHz`, how fast it would ring with no damping: a few hertz for hair, under one for a heavy coat. - `damping`, the damping ratio: below 1 overshoots, 1 settles without overshooting, above 1 sags in. Zero throws, since a spring that never forgets cannot be sampled at a time. - `maxOffsetM`, how far the mass may fall behind, for the frame a fast pan would otherwise leave a braid in the air. `anchorAt(t, out)` is where the spring is pulled, and it must be a pure function of the `t` it is handed: it is called for earlier times, back as far as `springSettleSec(settings)`, how long the spring takes to forget. An anchor that reads a clock breaks the sampling without failing. If the anchor comes from a clip, sample the clip at the time it is handed. `sampleSpringChain(links, rootAt, seconds, out)` is a chain, three floats a link, each `SpringLink` a spring with a `restOffsetM` from the link above, so the chain hangs. Each link trails where the one above it actually is, so a chain remembers longer than any link, and `springChainSettleSec(links)` is its lookback. ## Rigid animation ```ts /** A door on a hinge node: a clip with one rotation track drives the node, no skeleton at all. */ export function swingDoor(clip: AnimationClip, hinge: SceneNode): RigidAnimation { return new RigidAnimation(clip, [hinge]); } /* Each frame, at the door's own time: `door.apply(seconds)`. */ ``` Much of what moves in a game moves whole: a door, a lift, a turntable. `new RigidAnimation(clip, nodes)` binds a clip to scene nodes, one per joint its tracks name, `null` for one not in the scene, and `apply(seconds)` writes each node's position, rotation and scale. `applyPoseToNode(pose, joint, node)` does it for one joint of a pose you sampled yourself. Both mark the node moved, so its world matrix follows. This is the one part of the package that touches core, and it needs no shader at all. ## Morph targets ```ts /** A face with two expressions: deltas per vertex, interleaved, and a weight for each per draw. */ export function face( renderer: RendererApi, head: MeshData, smile: Float32Array, blink: Float32Array, ): MeshHandle { const vertices = head.positions.length / 3; const deltas = new Float32Array(vertices * 2 * 3); for (let v = 0; v < vertices; v += 1) { deltas.set(smile.subarray(v * 3, v * 3 + 3), (v * 2 + 0) * 3); deltas.set(blink.subarray(v * 3, v * 3 + 3), (v * 2 + 1) * 3); } return renderer.createMesh({ ...head, morphTargets: deltas, morphTargetCount: 2 }); } const weights = new Float32Array(2); export function drawFace( renderer: RendererApi, mesh: MeshHandle, model: Float32Array, time: number, ): void { weights[0] = 0.8; weights[1] = time % 4 < 0.15 ? 1 : 0; renderer.setMorphWeights(weights); renderer.drawMesh(mesh, model); renderer.setMorphWeights(null); } ``` A morph target is a shape a mesh can lean toward: a smile, a blink, a dent. A mesh carries its targets as `morphTargets`, position deltas interleaved by vertex, so target `t` of vertex `v` starts at `(v * morphTargetCount + t) * 3`, and `morphTargetCount` says how many, up to `MAX_MORPH_TARGETS`, eight. `setMorphWeights(weights)` chooses a weight a target for the following draws. The deltas belong to the mesh and the weights to the draw, so two characters sharing a head wear different expressions from one copy of it. Targets move positions and leave normals alone, which costs some shading accuracy on a strongly morphed surface. glTF morph targets import into the same fields. --- # Navigation Simulation. https://driftengine.dev/docs/simulation/navigation Routes over a graph of lanes and roads, and over a navigation mesh built from a level's geometry, with the following of a route in DriftScript. There are two shapes of world to find a way through. Some are already a network: roads, corridors, rails, the lanes between doors. Core routes over those as a graph of places and the ways between them. Others are open ground an agent may cross anywhere, and for those `@driftengine/nav` builds a navigation mesh from the level's own geometry. Both search with the same A\*, and both answer the same route every time for the same question, ties included, so a route can be decided inside the fixed step and replayed. The example is a town square. Six villagers walk the lanes from door to door, routed and steered by a DriftScript module through `drift/navigation`. Three dogs run where they like across the open ground, round the fountain and the market stalls, on a navigation mesh. Show the mesh or the lanes, and pack the stalls away or put them out: the mesh is rebuilt round them while everyone keeps walking. (This chapter runs the `navigation` example at https://driftengine.dev/docs/simulation/navigation.) ## A graph ```ts /** * The lanes, as places and the ways between them: eight doors, then the middle of each street, * then eight points round the fountain. The doors come first, so a door is a node below eight. */ const lanePoints: number[] = []; for (const [x, z] of BUILDINGS) { /* Each building has a door on the street running north and south, and one on the other. */ lanePoints.push(Math.sign(x) * 6.2, 0, z, x, 0, Math.sign(z) * 6.2); } /* Nodes 8 to 11, the streets: south, east, north, west. */ for (const [x, z] of [ [0, -13.5], [13.5, 0], [0, 13.5], [-13.5, 0], ]) { lanePoints.push(x ?? 0, 0, z ?? 0); } /* Nodes 12 to 19, the ring, starting east and turning toward the north. */ for (let k = 0; k < 8; k += 1) { lanePoints.push(Math.cos((k * Math.PI) / 4) * 4.5, 0, Math.sin((k * Math.PI) / 4) * 4.5); } /** Each door to its street, each street to the ring, and the ring round. Every way runs both ways. */ const DOOR_TO_STREET = [8, 11, 8, 9, 10, 11, 10, 9]; const STREET_TO_RING = [18, 12, 14, 16]; const laneEdges: NavEdge[] = [ ...DOOR_TO_STREET.map((street, door) => ({ from: door, to: street })), ...STREET_TO_RING.map((ring, at) => ({ from: 8 + at, to: ring })), ...Array.from({ length: 8 }, (_, k) => ({ from: 12 + k, to: 12 + ((k + 1) % 8) })), ]; const lanes: NavGraph = buildNavGraph(lanePoints, laneEdges); ``` `buildNavGraph(positions, edges)` takes the places as `x`, `y` and `z` a node and the ways between them as `NavEdge`s: `from` and `to`, a `cost`, which defaults to the distance between the two, and `bidirectional`, true unless you say otherwise. A cost is how you prefer a road or avoid a hill, and it may be more than the distance and never less: an edge cheaper than flying is refused, since the search's estimate of what is left assumes it, and with it gone the first route found would not be the cheapest. `new NavSearch(graph)` is the search, made once and reused, since its scratch is the size of the graph. `find(from, to, out)` writes the nodes of the cheapest route into `out` and answers how many, 0 for none, which is an answer and not an error: a graph with a gap in it has two sides. `nearestNavNode(graph, x, y, z, maxDistance)` is how an agent gets onto the network, and the distance keeps one that has wandered off from being snapped to the far side of the map; it is a scan, fine for the hundreds of nodes of a road network. A graph is the right shape when the ways through a world are a network already. An agent on one takes the corners the graph has and no others, so open ground crossed by two nodes is crossed in a straight line. ## Following a route A route is a list of nodes, and walking it is a separate problem: when a waypoint counts as reached, what to aim at, what to do when the walker is pushed off the line. `new NavPath(graph, capacity, options)` holds one route and answers it: - `set(nodes, count)` stores a route `find` wrote, and `clear()` forgets it. - `steer(x, y, z, out)` writes into a `NavSteer`, from `createNavSteer()`, the point to aim at: a `lookaheadM` along the route, two metres unless you say otherwise, so a walker cuts a corner and does not zigzag from node to node. It writes `remainingM`, the distance left along the route, and `arrived`, true within `arriveM` of the end, half a metre by default, and true with no route at all. Where the walker is along the route is worked out from where it stands, every time, so a walker shoved backwards past a node aims at the right place and does not turn round for a node already behind it. `NavPath` moves nothing: speed, turning and collision are the game's, which is the same line the character controller draws. ## Walking it in DriftScript ```drs // One frame of one villager: rest at a door, choose the next, or walk toward the point its route // says to aim at, which is a little way along the lane and so cuts corners the way people do. fn walk(villager: mut Villager, route: NavPath, lanes: NavGraph, dt: f32) { if navigation.arrived(route, villager.x, 0, villager.z) { if villager.resting > 0 { villager.resting = villager.resting - dt return } // The doors are the lanes' first eight nodes. let door = random.index(villager.seed + villager.trips, 8) let here = navigation.nearest(lanes, villager.x, 0, villager.z) if navigation.routeBetween(route, lanes, here, i32.clamp(door)) { villager.trips = villager.trips + 1 villager.resting = 2.5 } return } let dx = navigation.steerX(route, villager.x, 0, villager.z) - villager.x let dz = navigation.steerZ(route, villager.x, 0, villager.z) - villager.z let distance = math.sqrt(dx * dx + dz * dz) if distance > 0.01 { villager.x = villager.x + dx / distance * villager.pace * dt villager.z = villager.z + dz / distance * villager.pace * dt villager.heading = math.atan2(dx, dz) } } ``` ```ts /** The villagers' walking, hosted with the lanes it routes over, and a route for each villager. */ const walking = hostScript(walkScript, { navigation: { graph: lanes, search: new NavSearch(lanes) }, }); interface Villager { x: number; z: number; heading: number; pace: number; resting: number; trips: number; seed: number; } type Walk = (villager: Villager, route: NavPath, lanes: NavGraph, dt: number) => void; const villagers = Array.from({ length: 6 }, (_, at) => { const villager = exported<() => Villager>(walking, 'createVillager')(); villager.x = lanePoints[at * 3] ?? 0; villager.z = lanePoints[at * 3 + 2] ?? 0; villager.seed = at * 97; villager.pace = 1.1 + hashToUnit(at) * 0.5; return { villager, route: new NavPath(lanes, 32, { lookaheadM: 1.2, arriveM: 0.3 }) }; }); if (import.meta.hot) { import.meta.hot.accept('./walk.drs', (next) => { if (next !== undefined) { patchModule(walking, next as Record, { Villager: villagers.map(({ villager }) => villager), }); } }); } ``` `drift/navigation` needs the network it routes over, so the host passes `navigation`, a graph and a search over it, to `bindModule`, with `maxRouteNodes` for the longest route it will store, 256 if absent; a longer one is refused and not cut short. A module then has: - `nearest` and `nearestWithin`, the node nearest a place, or `-1`. - `route`, from one place to another, and `routeBetween`, between two nodes you have. Both store the route in a `NavPath` and answer whether there was one. - `path`, the route the host keeps for an entity between steps, and `clear` and `following`. - `steerX`, `steerY` and `steerZ`, the point to aim at; `remaining`, the distance left along the route; and `arrived`. The route is a function of the graph and its ends, so these are deterministic and a `@deterministic` system may call them. In the example each villager's `NavPath` is made by the page and handed in, and the module chooses doors with `drift/random`, seeded by the villager's own count of trips, so a run replays exactly. Under `npm run examples`, change the rest at a door or the pace and save: the villagers keep where they are and walk by the new rule. ## A navigation mesh ```ts /** Four buildings round a cross of streets, a fountain in the middle, and four market stalls. */ const BUILDINGS: [number, number][] = [ [-13.5, -13.5], [13.5, -13.5], [-13.5, 13.5], [13.5, 13.5], ]; const STALLS: [number, number][] = [ [5, -3.5], [-4.5, 5], [3.5, 5.5], [-5.5, -4], ]; /** The square as triangles: what is drawn, and what the navigation mesh is built from. */ function square(stalls: boolean): MeshData { const builder = new MeshBuilder().addBox([0, -0.25, 0], [20, 0.25, 20], [0.55, 0.52, 0.47]); for (const [x, z] of BUILDINGS) builder.addBox([x, 2.5, z], [6.5, 2.5, 6.5], [0.78, 0.66, 0.52]); builder.addCylinder([0, 0.4, 0], 2.5, 0.4, 'y', [0.62, 0.62, 0.66], 0, 24); if (stalls) { for (const [x, z] of STALLS) builder.addBox([x, 0.6, z], [1.2, 0.6, 0.8], [0.55, 0.38, 0.24]); } return builder.build(); } ``` ```ts /** Geometry in, convex walkable polygons out, sized for a dog: a metre tall and 0.4 m across. */ function bake(stalls: boolean): { mesh: PolyMesh; query: NavMeshQuery; ms: number } { const started = performance.now(); const field = voxeliseWalkable(square(stalls), { cellSize: 0.3, cellHeight: 0.2, maxSlope: 45, agentHeight: 1, agentRadius: 0.4, maxStep: 2, }); const regions = buildRegions(field, { minRegionSpans: 40, maxStep: 2 }); const mesh = buildPolyMesh(buildContours(field, regions, 1.3), 6, field); return { mesh, query: new NavMeshQuery(mesh), ms: performance.now() - started }; } ``` A navigation mesh is the walkable ground as convex polygons, built from triangles. Four steps: 1. `voxeliseWalkable(geometry, settings)` finds where an agent could stand, as spans in columns on a grid. Its settings are the grid, `cellSize` and `cellHeight`, and the agent: `maxSlope` in degrees, `agentHeight`, `agentRadius`, and `maxStep`, how many cells high a step it can climb. A face too steep to stand on is a solid in every cell it crosses, so a wall is in the way however thin it is; a floor with too little headroom above it is not walkable; and the walkable ground is eroded by the agent's radius from every edge, wall and ledge higher than `maxStep`. Two floors at one place, a bridge over a road, are two spans. 2. `buildRegions(field, settings)` divides it into regions by watershed, so a corridor between two rooms is where they divide. `maxStep` is the same number again, and `minRegionSpans` is the smallest region kept: smaller ones are merged into a neighbour. Where two obstacles sit diagonally from each other, such as the fountain and a building's corner, the watershed leaves strips a cell wide; the example's 40 folds them in. 3. `buildContours(field, regions, maxDeviation)` outlines each region, simplified to within `maxDeviation` cells of the true edge. Holes are kept, so a path goes round a pillar, and where two regions meet, their shared border is simplified the same way from both sides, so they meet edge to edge. 4. `buildPolyMesh(contours, maxVertsPerPoly, field)` cuts the outlines into convex polygons of up to that many corners, each knowing its neighbours. The `PolyMesh` it returns holds `polyCount` polygons and their corners in cells, with `originX`, `originZ` and `cellSize` to turn them into metres; `polyVertexCount`, `polyNeighbour`, `polyArea` and `polyIsConvex` read a polygon. The example draws every polygon's edges from these. The polygons are flat and one layer deep. Where two floors overlap, only the lower becomes polygons, and the floor sealed inside a closed box stays walkable inside its walls, an island no route from outside reaches. Building one is a bake: the square takes 40 to 110 milliseconds here, so do it when a level loads or changes, as the stalls switch does, and never every frame. ## Paths across it ```ts /** Path from where the dog is to its goal, over whichever mesh is current. */ function route(dog: Dog): boolean { dog.count = baked.query.findPath(dog.x, dog.z, dog.goalX, dog.goalZ, 1.5, dog.path); dog.next = 1; return dog.count > 1; } ``` `new NavMeshQuery(mesh)` searches the mesh, and `findPath(fromX, fromZ, toX, toZ, extent, out)` writes the path as `x` and `z` pairs and answers how many points, 0 for none. `extent` is how far off the mesh a point may be and still be snapped onto it, so a goal inside a building or past the edge of the square answers no path and the dog picks another. The search runs over the portals between polygons, the overlaps of their edges, and then pulls the path tight through them, so a path across open ground is one straight line and a path round an obstacle is the shortest way round it. `findPolyPath(from, to, out)` answers the polygons a path crosses, and `nearestPoly(mesh, x, z, extent)` the polygon under a point. A query holds scratch for its mesh, so make one per mesh and reuse it, and a new mesh needs a new query. What a mesh does not do is avoidance: the dogs run through the villagers and through each other. How an agent moves along a path is the game's, as with a graph. `@driftengine/nav` is 8.8 KB gzipped, and nothing in core imports it; the graph, the search and `NavPath` are core's. --- # Entities Simulation. https://driftengine.dev/docs/simulation/entities Generational handles, components as typed columns, systems that declare what they touch, prefabs, saved scenes and rewinds, from DriftScript and TypeScript. `@driftengine/entities` is the entity model: handles that know when they have gone stale, components stored as typed columns, queries over them, systems that say what they read and write, a schedule on the fixed step, prefabs, scenes saved by stable field ids, and snapshots for a rewind. It imports no other engine package and declares no components, so a world holds only what your game says it holds. DriftScript has the model built into the language. A `.drs` file declares `component`s, `prefab`s and `system`s, and `for e in query<…>()` is a loop the compiler checks and lowers to an array index. The example is a pond at dusk: fireflies wander over the water, four frogs on lily pads catch the ones that come near, and new ones hatch to keep the number the pond is set to. Every rule is a system in DriftScript; the page builds the world, puts the frogs on their pads and draws what the stores hold. Set the pond to keep forty, or run time backwards and let it pick up from wherever it stops. (This chapter runs the `entities` example at https://driftengine.dev/docs/simulation/entities.) ## Components ```drs component Position { x: f32 = 0 y: f32 = 0 z: f32 = 0 } component Velocity { x: f32 = 0 y: f32 = 0 z: f32 = 0 } // A fly, and its own seed and count of turns, which together pick its next heading. component Fly { seed: u32 = 0 turns: u32 = 0 } // A frog: how far its tongue reaches, the fly it has its eye on if any, how many it has caught, // how long before it can catch again, and how long its tongue stays out and where it went. component Frog { reach: f32 = 2.5 target: Entity? caught: u32 = 0 resting: f32 = 0 tongue: f32 = 0 tongueX: f32 = 0 tongueY: f32 = 0 tongueZ: f32 = 0 } // The pond itself: how many flies it keeps, and how many have hatched. component Pond { flies: u32 = 12 hatched: u32 = 0 } ``` A component is a named set of fields, and each field becomes one column in a store: `f32` and `f64`, the integer widths from `i8` to `u64`, `bool`, `Entity` for a handle, `String`, and a fieldless `enum`, whose variant is kept as an integer, which is where a state machine's state lives. A store is a sparse set, so adding a component to an entity, taking it away and walking everything that has it all cost the same whoever else is in the world. A component with no data of its own, a marker, narrows a query by a fact, not by a value. An optional field, `T?`, keeps its absence in a column beside its value, and reads and writes as an option from a script, in a query loop or through a handle. A frog's `target` is an `Entity?`: `none` while it has no fly in its eye, `some(fly)` once it has, and `if let` reads it back. ## Prefabs ```drs // What a hatchling and a frog start as. Every value is a constant: where each goes is set after. prefab Hatchling { Position { y: 1 } Velocity {} Fly {} } prefab Sitter { Position {} Frog { reach: 2.5 } } ``` A prefab is a value: a name and the components an entity made from it starts with. Every value in it is a constant, so it can be read, saved and shown without being run, and an entity made from one keeps no link back to it. A script makes one with `ecs.instantiate(world, "Hatchling")` and writes whatever should differ afterwards; the page makes the frogs with `instantiate`, below. ## Systems ```drs // Everything that has a velocity moves by it, a sixtieth of a second each fixed step. system Move { reads Velocity writes Position update { for e in query() { e.Position.x = e.Position.x + e.Velocity.x / 60 e.Position.y = math.clamp(e.Position.y + e.Velocity.y / 60, 0.4, 2) e.Position.z = e.Position.z + e.Velocity.z / 60 } } } ``` A `system` is a body the schedule runs every fixed step, and it declares what it `reads` and `writes`, a write implying a read. The declarations are checked twice. The compiler works out what the body touches and refuses a declaration that leaves something out, naming the system and the component, and warns about one that names something the body never touches. The schedule refuses again at run time: a system that touches a component it did not declare is skipped, and the console says which and why, once. A schedule built from declarations is only right if they are true, which is why both ends check. ```drs // Four times a second, each rested frog fixes on the nearest fly within its reach. system Hunt { reads Fly reads Position writes Frog update at 4Hz { for frog in query() { if frog.Frog.resting > 0 { continue } var best = frog.Frog.reach * frog.Frog.reach frog.Frog.target = none for fly in query() { let dx = fly.Position.x - frog.Position.x let dy = fly.Position.y - frog.Position.y let dz = fly.Position.z - frog.Position.z let distance = dx * dx + dy * dy + dz * dz if distance < best { best = distance frog.Frog.target = some(fly) } } } } } ``` `update at 4Hz` runs the body every fifteenth step of the 60 Hz fixed step; a rate that does not divide it exactly is refused, because rounding it would make a replay run the system a different number of times. Queries nest, and a component named in a query counts as a read, even one whose fields the body never looks at. `.without()` narrows a walk to entities that do not carry `T`, and `.with()` to those that do. ```drs // A frog with a fly in its eye catches it: out goes the tongue, and the fly is gone. system Catch { reads Position writes Frog update { for frog in query() { frog.Frog.tongue = math.max(frog.Frog.tongue - 1 / 60, 0) frog.Frog.resting = math.max(frog.Frog.resting - 1 / 60, 0) if let fly = frog.Frog.target { if ecs.alive(world, fly) { frog.Frog.tongueX = fly.Position.x frog.Frog.tongueY = fly.Position.y frog.Frog.tongueZ = fly.Position.z frog.Frog.tongue = 0.2 frog.Frog.resting = 4 frog.Frog.caught = frog.Frog.caught + 1 ecs.destroy(world, fly) } frog.Frog.target = none } } } } ``` `e.Component.field` reads and writes through any handle, not only the one a loop is on. Inside a loop it is an index into a column; through another handle it is a lookup, still checked by name, so a misspelt field is an error at the line that wrote it. `ecs.destroy` inside a system waits until the system returns, because removing an entity moves the last one in its store into the gap, and a walk in progress would skip it. `ecs.alive` answers whether a handle still names a live entity. ```drs // Four times a second, while the pond has fewer flies than it keeps, one hatches over the water. // A hatchling is made with every component its prefab names, so the system declares all three: the // compiler sees the fields this body writes, and the schedule checks the components it adds. system Hatch { writes Pond writes Position writes Velocity writes Fly update at 4Hz { for pond in query() { if ecs.count(world, "Fly") < pond.Pond.flies { pond.Pond.hatched = pond.Pond.hatched +% 1 let seed = pond.Pond.hatched *% 2246822519 let fly = ecs.instantiate(world, "Hatchling") fly.Position.x = random.range(seed, -5, 5) fly.Position.z = random.range(seed +% 1, -5, 5) // Hatching from the water, it rises before it wanders. fly.Velocity.y = 0.6 fly.Fly.seed = seed } } } } ``` Making an entity is immediate, and one made during a walk may be visited by it. A system that makes an entity from a prefab writes every component the prefab names, so it declares them all: the compiler sees the fields its body writes and the schedule checks the components it adds. `ecs` also has `create`, `attach`, `detach` and `has` for an entity built by hand, `count` and `at` to walk a store by index, and `findNearest`, a search for the nearest entity within a radius by three position fields you name. ## The host ```ts /** * The script's components become stores, its prefabs become prefabs, and its systems become a * schedule. The registry and the world outlive every reload; the schedule is rebuilt on one. */ const pond = loadModule(pondScript as Record); const registry: ComponentRegistry = new Map(); const prefabs = new Map(); let registered = registerEntityModule(pond, registry); for (const prefab of registered.prefabs) prefabs.set(prefab.name, prefab); const bound = bindModule(pond, { entities: { components: registry, prefabs } }); if (!bound.bound) throw new Error(bound.reason); const world = new World(); let schedule = buildSchedule(registered.systems); if (import.meta.hot) { import.meta.hot.accept('./pond.drs', (next) => { if (next === undefined) return; patchModule(pond, next as Record); /* The stores are kept, so every fly and frog keeps its components; the systems are new. */ registered = registerEntityModule(pond, registry); for (const prefab of registered.prefabs) prefabs.set(prefab.name, prefab); schedule = buildSchedule(registered.systems); }); } ``` `registerEntityModule(module, registry)` turns what a module declares into the engine's own objects: a component type per `component`, registered by name, a `Prefab` per `prefab`, and a `SystemDefinition` per `system`. `bindModule` is handed the same registry and the prefabs by name, which is how `ecs` resolves the names a script writes. `buildSchedule(systems)` orders the systems and `runSchedule(world, schedule, tick)` runs one fixed step of them; the tick decides which strided systems are due. A system that throws is skipped and the rest still run. The failure is logged once per system, or handed every time to a reporter passed as a fourth argument, which gets the system's name, the tick and the error and can throw to stop the schedule there. A reload keeps the registry, so every store, and with it every entity's components, survives an edit. The module is patched, registered again for any new component or system, and the schedule is rebuilt over the same world. A component the host made itself is declared in a script as `component Name from host { … }`, which asserts its shape when the module binds instead of making a second one. ```ts /** A frog on each lily pad, from the script's own prefab, with the page saying where. */ const PADS: [number, number][] = [ [4, 0], [0, 4], [-4, 0], [0, -4], ]; const sitter = prefabs.get('Sitter'); if (sitter === undefined) throw new Error('pond.drs declares no Sitter'); const frogs: Entity[] = PADS.map(([x, z]) => instantiate(world, sitter, { Position: { x, y: 0.15, z } }), ); const pondEntity = world.create(); world.add(pondEntity, Pond, { flies: 12 }); ``` `instantiate(world, prefab, overrides)` makes an entity from a prefab, with overrides by component name; an override for a component the prefab does not have is refused, since adding it or ignoring it would both hide a typo. ## From TypeScript ```ts /** A component is a name and its fields' types; each field becomes one typed column. */ const Health = defineComponent('Health', { current: 'f32', max: 'f32' }); const Hunger = defineComponent('Hunger', { value: 'f32' }); /** A field holding a handle is typed `Entity`, so a scene load can rewrite it. */ const Follows = defineComponent('Follows', { leader: 'Entity' }); const world = new World(); const wolf = world.create(); world.add(wolf, Health, { current: 30, max: 30 }); world.add(wolf, Hunger, { value: 0 }); ``` ```ts /** Hunger rises once a second, and health falls while it is high. Each says what it touches. */ const schedule = buildSchedule([ { name: 'hunger', writes: [Hunger], everyTicks: 60, run(view) { const hunger = view.view(Hunger, true); for (const entity of view.query(Hunger)) { const at = hunger.sparse[entity % 2 ** 26] ?? 0; (hunger.value as Float32Array)[at] = ((hunger.value as Float32Array)[at] ?? 0) + 1; } }, }, { name: 'starve', reads: [Hunger], writes: [Health], everyTicks: 60, after: ['hunger'], run(view) { for (const entity of view.query(Hunger, Health)) { if ((view.read(entity, Hunger, 'value') as number) < 50) continue; const current = view.read(entity, Health, 'current') as number; view.write(entity, Health, 'current', current - 1); if (current <= 1) view.destroy(entity); } }, }, ]); /** One fixed step: the schedule, at the tick the loop is on. */ export function tick(count: number): void { runSchedule(world, schedule, count); } ``` The same model with no script: `defineComponent(name, fields)` declares a type, and a world's `create`, `add`, `remove`, `has`, `read`, `write` and `destroy` do what they say. A system is a `SystemDefinition`: a `name`, `reads` and `writes`, `everyTicks` for a stride, `after` for the systems it must follow, and `run(view)`, whose `SystemView` checks every access against the declarations. The schedule keeps declaration order, adjusted by `after`, and refuses a cycle by naming the systems in it. ## Reading the stores ```ts /* A host reads the stores' columns directly, the way any renderer would. */ const positions = world.view(Position); const frogColumns = world.view(Frog); const spot = (entity: Entity): number => positions.sparse[entity % 2 ** 26] ?? 0; ``` ```ts /* Every entity with a Fly and a Position, drawn where its Position column says. */ let count = 0; for (const fly of world.query(Fly, Position)) { const i = spot(fly); flyModel[12] = (positions.x as Float32Array)[i] ?? 0; flyModel[13] = (positions.y as Float32Array)[i] ?? 0; flyModel[14] = (positions.z as Float32Array)[i] ?? 0; renderer.drawMesh(flyMesh, flyModel); count += 1; } ``` `world.view(type)` hands back a component's live columns, typed arrays by field name, and `sparse`, which maps an entity's slot to its row: `sparse[entity % 2 ** 26]`. A renderer reads positions this way, with no call per entity. `world.query(a, b, c, d)` walks the entities carrying up to four components, narrowed further with `with` and `without`; the cursor comes from a pool and goes back when the walk ends, so a query in a frame allocates nothing. ## Saving a scene ```ts /** A pack: a leader, and followers made from one prefab with a handle to it written after. */ const pupPrefab = definePrefab('pup', [ [Health, { current: 10, max: 10 }], [Follows, {}], ]); const pups: Entity[] = [0, 1, 2].map(() => { const pup = instantiate(world, pupPrefab, { Health: { max: 12 } }); world.write(pup, Follows, 'leader', wolf); return pup; }); ``` ```ts /** A save names the component types it holds; a load is handed the same, and refuses in words. */ export function save(): string { return JSON.stringify(serializeWorld(world, [Health, Hunger, Follows])); } export function load(text: string): World { const fresh = new World(); const result = deserializeWorld(fresh, JSON.parse(text) as SerializedScene, [ Health, Hunger, Follows, ]); if (!result.loaded) throw new Error(result.reason); return fresh; } ``` `serializeWorld(world, types)` writes the entities carrying those component types, and `deserializeWorld(world, scene, types)` reads them into a world, answering `loaded` with the new handles, or a `reason` and nothing written. Every value is stored by a field id, never by position or bare name, so a field added in the middle of a component does not shift the ones after it. Loading across a change migrates: a field added since arrives with its default, one removed is dropped, and one whose type changed is refused by name. A handle in an `Entity` field is saved as a position in the scene and rewritten on load to the new handle, so a pup still follows its leader in the world it was loaded into. ## Rewinding ```ts /** * Five seconds of the whole world, a snapshot a tick. A slot is reused once it is written, so after * the first lap the ring allocates nothing. */ const RING = 300; const ring: WorldSnapshot[] = Array.from({ length: RING }, createWorldSnapshot); const ringTicks = new Float64Array(RING); let head = 0; let held = 0; let tick = 0; function step(): void { /* The switch's number wins over whatever the world held, rewound or not. */ world.write(pondEntity, Pond, 'flies', flies); runSchedule(world, schedule, tick); tick += 1; world.saveInto(ring[head % RING] as WorldSnapshot); ringTicks[head % RING] = tick; head += 1; held = Math.min(held + 1, RING); } function stepBack(): void { if (held <= 1) return; head -= 1; held -= 1; const at = (head - 1 + RING) % RING; world.loadFrom(ring[at] as WorldSnapshot); tick = ringTicks[at] ?? tick; } ``` A snapshot is the whole world at one tick: `createWorldSnapshot()` makes a slot, `saveInto` fills it and `loadFrom` puts the world back. It covers every store the world has and takes no list of types, since a component left out of a rewind is state that survived it. A slot grows to the world's size on its first save and is reused after, so a ring of them allocates nothing once it has gone round. A snapshot is not a save: it never goes on a wire or into a file, and it does not migrate. ## Handles ```ts /** A handle is one number: which slot, and how many times that slot has been reused. */ export function describe(entity: Entity): string { return `slot ${entityIndex(entity)}, use ${entityGeneration(entity)}, ${world.alive(entity) ? 'alive' : 'gone'}`; } ``` An `Entity` is one number: a 26-bit slot and a 27-bit generation, the whole 53 bits a double holds exactly. Destroying an entity frees its slot, and the next entity to take the slot has the next generation, so an old handle is not alive and never names the newcomer. That gives sixty-seven million live entities and 134 million reuses of each slot. `entityIndex` and `entityGeneration` take a handle apart and `packEntity` puts one together. In a script a handle is `Entity` and stays one: it can be stored in an `f64`, but a number a script computed cannot be passed where a handle is wanted. --- # Chemistry Simulation. https://driftengine.dev/docs/simulation/chemistry Matter as parcels of real substances, whose heat, phase changes, burning and smoke follow from conserved energy, steered from DriftScript. `@driftengine/chemistry` models bulk matter: what a thing is made of, what temperature it is, and what it turns into. A parcel of matter holds a mass and an enthalpy, and its temperature is worked out from what it is made of at that moment. Melting, boiling and burning are reactions that balance element by element, so a kettle sits at a hundred degrees while it boils, a green log will not catch at a fire that lights a dry one, and nobody wrote either rule down. It is 18.1 KB gzipped and imports no other engine package. The example is a campfire: oak and kindling beside a bed of embers, a kettle, a block of ice, an iron nail and a copper coin, each heating at the rate its own substance decides. The camp is a DriftScript module: the rain, a keeper who lays a new log on, seasoned or green, and a notebook of what happened. Lay a green log and watch it steam instead of catching; let it rain and everything that can hold water stops at the boiling point; let the wind blow. The fire runs about four times faster than the clock, and slower on a machine that cannot keep that up. (This chapter runs the `chemistry` example at https://driftengine.dev/docs/simulation/chemistry.) ## Installing it ```ts /** Three families of substance, and a world with air over it: one metre cells, 8³ to a chunk. */ const chem = installChemistry({ libraries: [ORGANIC, FOOD, METAL], maxChunks: 8 }); /** * The fire's own fixed step: a sixteenth of a second of chemistry each tick of the page, so it runs * about four times faster than the clock. * * **Fifteen times was the first choice, and it was more than the air can afford.** The air steps in * substeps a step's length decides, so what it costs follows how many seconds of fire pass each * second: about 77 ms of a desktop's time per second of fire with the smoke in two chunks. A quarter * second sixty times a second asked for more than a second of work every second, and the page fell * to three frames a second while the fire went on burning. */ const DT = 1 / 16; /** The hearth sits at (4, 4, 4) in the air's cells, and the scene is drawn in those same metres. */ const HEARTH: Vec3 = [4, 4, 4]; ``` `installChemistry(options)` builds a world from the families of substance a game uses, and wires the rest: the species, the reactions between them, the substances, the parcels, the air over them, and the world that steps them all. The families are entry points of their own, so a game that wants a campfire pays for a campfire: - `library/organic`: oak, pine, paper, cotton, leather and straw. - `library/food`: water, ice, butter, beef muscle, potato, egg white and sugar. - `library/fuel`: ethanol, petrol, diesel, kerosene and paraffin wax. - `library/polymer`, `library/mineral`, `library/metal` and `library/biological`. Each costs between 625 bytes and 1.3 KB. `cellSize` is the air's cell in metres, one by default, `maxChunks` how many 8³ chunks of air may be live at once, and `ambient` the air's starting state. `match(names)` resolves material names to substances exactly, with no synonyms, and returns the names that matched nothing, so a model's `pine_bark_02` is a decision for you and not a guess. Positions are in the air's cells, which at the default size are metres. ## Parcels ```ts /** What is on the hearth: a substance, where it sits, and the box it fills. */ interface Thing { readonly label: string; readonly at: Vec3; readonly size: Vec3; parcel: number; meshes: MeshHandle[]; } function spawn(label: string, substance: string, at: Vec3, size: Vec3): Thing { const index = chem.substances.indexOf(substance); const bounds = parcelFromBounds(size[0], size[1], size[2], chem.substances.densityOf(index)); const parcel = chem.parcels.spawn({ substance: index, mass: bounds.mass, temperature: 288.15, area: bounds.area, x: at[0], y: at[1], z: at[2], }); return { label, at, size, parcel, meshes: charSteps(parcel, size) }; } ``` `parcels.spawn({ substance, mass, temperature, area, x, y, z })` puts a parcel in the world, and `parcelFromBounds(width, height, depth, density)` gives the mass and surface area of a box of it. A parcel has depth: nested shells of equal mass, so heat enters the surface and conducts inward, a thin piece heats through and a thick one does not. An 80 mm log's core stays at room temperature while its surface chars. Reading one: `temperatureOf`, `surfaceTemperatureOf` and `coreTemperatureOf`, in kelvin; `massOf`, `charFractionOf`, `wetnessOf` and `wettable`; `burning` and `smouldering`; and `heatReleaseOf`, in watts, negative while it is drying or charring and taking heat in. Changing one: `addHeat`, `wet` and `dry`, `ignite`, which offers a flame, and `douse`. ## A tick ```ts /* The embers radiate; every parcel is offered a flame, which is one of the five conditions. */ chem.world.sources.clear(); chem.world.sources.add(hx, hy + 0.05, hz, 1150, 0.2, 90000); chem.world.contacts.clear(); for (const thing of things) chem.parcels.ignite(thing.parcel); exported(camp, 'weather')(notes, chem, DT); chem.world.simulate(DT, wind, 0); /* The events are cleared at the top of the next step, so they are read now. */ exported(camp, 'notice')(notes, chem, named('kettle').parcel, named('ice').parcel); ``` `world.sources` holds what radiates, cleared and filled each tick: a position, a temperature, an area and a power. Every parcel works out what reaches it, so a log twice as far from the fire takes four times as long. `world.contacts` holds what touches what. `world.simulate(dt, windX, windZ)` steps it all: conduction through the shells, the reactions, the air's transport, and the parcels drawing oxygen from the cell they sit in and pushing what they make back into it. Ignition is five conditions: a surface hot enough, enough fuel coming off it, oxygen above the limiting fraction, a mixture at the surface inside its flammability limits, and a pilot flame, which is what `ignite` offers and which lowers the temperature needed. A wet log's steam thins the mixture below its limit, so it does not catch however long a match is held to it. Going out is four: fuel gone, too little oxygen, the surface cooled, or the flame blown off, and a smoulder survives air a flame cannot. What happened is an event buffer, drained each tick and cleared at the start of the next. Twenty-one kinds are named; four are raised today, a parcel igniting, going out, and starting and stopping a smoulder. The camp watches the kettle and the ice by their temperature and their phase. ## The camp, in DriftScript ```drs // Rain wets everything that can hold water, a little each tick; a nail or a coin stays dry. fn weather(camp: Camp, chem: Chemistry, dt: f32) { if camp.rain <= 0 { return } var parcel: i32 = 0 while parcel < chemistry.parcelCount(chem) { if chemistry.alive(chem, parcel) && chemistry.wettable(chem, parcel) { chemistry.wet(chem, parcel, camp.rain * dt) } parcel += 1 } } ``` ```drs // A log of oak laid on the fire and offered a flame: seasoned, or green, which is the same wood // with water poured on. Whether it catches is the chemistry's answer. fn stoke(chem: Chemistry, green: bool, x: f32, y: f32, z: f32) -> i32 { let oak = chemistry.substance(chem, "oak") let log = chemistry.place(chem, oak, 2.5, 0.16, x, y, z) if green { chemistry.wet(chem, log, 0.9) } chemistry.ignite(chem, log) return log } ``` ```drs // What happened this tick: catching and going out from the chemistry's event buffer, read before // it is cleared, and the kettle and the ice by watching them. fn notice(camp: mut Camp, chem: Chemistry, kettle: i32, ice: i32) { var at: i32 = 0 while at < chemistry.eventCount(chem) { let kind = chemistry.eventKind(chem, at) if kind == ChemistryEvent.Ignited { camp.caught += 1 camp.lastCaught = chemistry.eventParcel(chem, at) } if kind == ChemistryEvent.Extinguished { camp.putOut += 1 } at += 1 } if chemistry.surfaceTemperature(chem, kettle) >= 99.5degC { camp.boiled = true } // Ice that is no longer all solid has begun to melt: `Mixed` while some of it is water. if chemistry.phase(chem, ice) != MatterPhase.Solid { camp.melting = true } } ``` ```ts /** The camp, hosted with the chemistry it reads and writes. */ const camp = hostScript(campScript, { chemistry: chem }); interface Camp { rain: number; caught: number; putOut: number; boiled: boolean; melting: boolean; lastCaught: number; } const notes = exported<() => Camp>(camp, 'createCamp')(); type Weather = (camp: Camp, chem: unknown, dt: number) => void; type Stoke = (chem: unknown, green: boolean, x: number, y: number, z: number) => number; type Notice = (camp: Camp, chem: unknown, kettle: number, ice: number) => void; if (import.meta.hot) { import.meta.hot.accept('./camp.drs', (next) => { if (next !== undefined) patchModule(camp, next as Record, { Camp: [notes] }); }); } ``` `drift/chemistry` is handed the world it reads and writes, and every call takes it as its first argument. A module has: - `substance` and `species`, by id, refusing one that is not installed and saying where to find it. - Reading a parcel: `parcelCount`, `alive`, `temperature`, `surfaceTemperature` and `coreTemperature`, `mass`, `moisture`, `wetness` and `wettable`, `charFraction`, `phase`, `burning` and `smouldering`, `heatRelease` in kilowatts, `ignitionProgress` and more. - Reading the air at a point: `ambientTemperature`, `oxygenFraction`, `humidity`, `pressure`, `concentration`, `smokeDensity` and `visibility`. - Changing things: `place`, `destroy` and `move`, `addHeat`, `setTemperature`, `wet` and `dry`, `ignite` and `douse`, `addSpecies`, `mix`, and `release` and `addAirHeat` into the air. - The events: `eventCount`, and `eventKind`, `eventParcel`, `eventSpecies` and `eventValue` by index. A write is inside the determinism boundary: a parcel's enthalpy is simulated state integrated on the fixed step, so a `@deterministic` function may change chemistry. Temperatures may be written in `degC` as a threshold, `>= 99.5degC`, and the compiler refuses one used as a difference, which would be 273.15 kelvin out. ## Drawing it ```ts /* Every reading a picture needs: char colour, Planck glow, wetness, and what is left of it. */ writeSurface( chem.parcels, things.map((thing) => thing.parcel), surface, ); emitSmoke(chem.air, hx - 4, hy, hz - 4, 8, smoke, { threshold: 2e-6, size: 0.3, wind: wind * 0.3, }); /* The air's cells are a metre across, so a puff in the cell the camera is in fills the view. */ for (let i = 0; i < smoke.count; i += 1) { const dx = (smoke.positions[i * 3] ?? 0) - camera.position[0]; const dy = (smoke.positions[i * 3 + 1] ?? 0) - camera.position[1]; const dz = (smoke.positions[i * 3 + 2] ?? 0) - camera.position[2]; if (dx * dx + dy * dy + dz * dz < 1.5) smoke.alphas[i] = 0; } ``` `@driftengine/chemistry/present` turns readings into pictures, and every mapping is a physical quantity. `writeSurface(parcels, handles, out)` writes each parcel's colour, darkening toward its own char colour as it chars, its glow, from Planck at its surface temperature, its roughness, from the water on it, and its scale, from what is left of it. `emitSmoke(air, x, y, z, cells, out, options)` writes a particle for every cell of air holding smoke, coloured by the ratio of soot, nearly black, to droplets, nearly white: a flame smokes dark and a smoulder or a wet log smokes pale, with nothing choosing. `flameHeight(kilowatts, diameter)` is the height of a flame, and `crackleRate`, `hissRate` and `roarLevel` are levels for sound. The targets are described by shape only, so core's particles take the smoke directly and neither package imports the other. The example draws each thing from meshes built emissive and white, `setEmissiveColor([1, 1, 1])`, and binds a white emissive map one texel wide whose `emissiveScale` is the glow `writeSurface` gave it: a [material](https://driftengine.dev/docs/rendering/materials)'s map modulates a mesh's own emission, so the colour comes from the chemistry, and a thing too cold to glow is drawn with a scale of zero. Emissive in this engine is also gated on the environment's `nightFactor`, so embers that glow at dusk look dead at noon; the example sets it to one. ## Without a scene ```ts /** Seasoned oak, dry basis, as mass fractions that must sum to one. */ const species = new SpeciesRegistry(); registerStandardSpecies(species); const oak = massFractions(species, { cellulose: 0.43, hemicellulose: 0.26, lignin: 0.26, extractives: 0.04, ash: 0.01, }); /** Ten kilograms of it, reduced to moles of each of the fifteen elements. */ export function carbonInTenKilograms(): number { const mass = new Float64Array(species.count); oak.species.forEach((s, i) => { mass[s] = (oak.fraction[i] ?? 0) * 10; }); const elements = new Float64Array(ELEMENT_COUNT); elementTotals(species, mass, elements); return elements[ELEMENTS.indexOf('C')] ?? 0; } ``` ```ts /** * A litre of water on a kilowatt, in a world with no air: the registries and the parcels wired by * hand, which is the part of `installChemistry` that comes before the atmosphere. */ const reactions = new ReactionRegistry(species); const substances = new SubstanceRegistry(species, reactions); installLibrary(FOOD, species, reactions, substances); const parcels = new ParcelStore(substances); const kitchen = new ChemistryWorld(parcels, null); const water = parcels.spawn({ substance: substances.indexOf('water'), mass: 1, temperature: 293.15, area: 0.05, }); /** It climbs to boiling, then stays at a hundred while the kilowatt goes into boiling it away. */ export function heatFor(seconds: number): number { for (let t = 0; t < seconds; t += 1) { parcels.addHeat(water, 1000); kitchen.simulate(1); } return parcels.temperatureOf(water) - 273.15; } ``` ```ts /** * Sixteen hex digits over every parcel, and the air where there is one: two runs that agree print * the same. */ export function fingerprint(): string { return fingerprintChemistry(kitchen); } ``` The pieces underneath are usable on their own. `massFractions(species, fractions)` is a material that must sum to one, and `elementTotals` reduces kilograms of species to moles of each of the fifteen elements, which is the ledger every reaction is checked against. A `ChemistryWorld` with no air steps parcels alone, in microseconds; the air is most of what a step costs. `fingerprintChemistry(world)` is sixteen hexadecimal digits over every parcel's composition and enthalpy and the air, for checking that two runs agree. ## What it costs A parcel whose surface and reactions have been still for thirty ticks sleeps and is not stepped, and wakes on heat, water, a contact, or a fire coming near, so a pile of cold stones costs nothing. A parcel far from the camera can be stepped coarser with `setTier`, from `TIER_HERO` through `TIER_NEAR` and `TIER_FAR` to `TIER_DISTANT`, one shell every sixteenth tick. Every tier conserves mass, elements and energy exactly, so a parcel may change tier mid-burn; what a coarse tier gives up is accuracy, and a lumped parcel chars more, having no cold core to hide behind. --- # Agents and behaviour Simulation. https://driftengine.dev/docs/simulation/agents Behaviour trees that pause, interrupt and resume, and agent sessions whose deterministic floor keeps them moving while a model answers late. Two ways to give a character something to do. A behaviour tree is a routine written as data: a tree of named steps that can be paused, stepped, interrupted by something more urgent, and picked up again where it left off. An agent session, from `@driftengine/ai`, is for a character that may also ask a model what to do next: a deterministic floor that always has an answer, a model asked ahead of time, and every answer checked against the world before it is acted on. The example is a village square. Three villagers go about their errands, from their stalls to the well and home again, run for the awning when it rains and go back to exactly what they were doing when it stops. The town crier walks the square deciding where to go next. The day is a DriftScript module that advances the routines, watches them, and tells the crier when the weather turns. Let it rain, hold the baker where he is, and give the crier a model to ask, a slow one or a quick one. (This chapter runs the `agents` example at https://driftengine.dev/docs/simulation/agents.) ## A behaviour tree ```ts /** * One villager's day. The first branch is guarded by the rain: while it rains, shelter wins, and * the errand it interrupted is suspended where it was, not started again. */ const DAY: BehaviorSpec = { name: 'day', selector: [ { name: 'out of the rain', whileTrue: 'raining', does: { name: 'shelter', sequence: [ { name: 'run to the awning', action: 'toAwning' }, { name: 'wait it out', action: 'waitOut' }, ], }, }, { name: 'errands', sequence: [ { name: 'walk to the stall', action: 'toStall' }, { name: 'trade', action: 'trade' }, { name: 'walk to the well', action: 'toWell' }, { name: 'draw water', action: 'drawWater' }, { name: 'walk home', action: 'toHome' }, { name: 'rest', action: 'rest' }, ], }, ], }; ``` A tree is written as a `BehaviorSpec`, every node named: - `sequence`, children in order: it fails when one fails and succeeds when the last does. - `selector`, children in order until one does not fail: a list of alternatives. - `action`, one of your verbs, which takes time and answers `RUNNING` until it is done, then `SUCCESS` or `FAILURE`. - `condition`, one of your questions, answered now. - A guard, `whileTrue` and `does`, which runs its child only while a condition holds. A selector of guards is a list of priorities, and it is how a routine is interrupted. When the rain guard's condition comes true, shelter wins, and the errand that was running is suspended, not abandoned: its place in every sequence is kept, so when the rain stops each villager carries on from the step they had reached. A branch is reset only when it finishes. Most behaviour-tree libraries reset on interruption, and the difference is a villager who goes back to the stall after a shower against one who goes home and starts the day again. ```ts /** A villager, and the verbs the tree calls by name. */ interface Villager { readonly name: string; readonly home: Vec3; readonly stall: Vec3; x: number; z: number; heading: number; /** Seconds left on each timed step, by name: kept while a step is suspended, cleared when done. */ readonly timers: Map; } let raining = flag('rain', 'dry') === 'raining'; const DT = 1 / 60; function walkTo(v: Villager, target: Vec3, pace: number): BehaviorStatus { const dx = target[0] - v.x; const dz = target[2] - v.z; const distance = Math.hypot(dx, dz); if (distance < 0.1) return SUCCESS; const step = Math.min(distance, pace * DT); v.x += (dx / distance) * step; v.z += (dz / distance) * step; v.heading = Math.atan2(dx, dz); return RUNNING; } /** * Spend a while at a place: walk back to it first, which is what a step resumed after the rain * needs, then count down a timer that is kept while the step is suspended. */ function spend(v: Villager, place: Vec3, step: string, seconds: number): BehaviorStatus { if (walkTo(v, place, 1.4) === RUNNING) return RUNNING; const left = (v.timers.get(step) ?? seconds) - DT; if (left > 0) { v.timers.set(step, left); return RUNNING; } v.timers.delete(step); return SUCCESS; } /** Where each villager stands at their stall, at the well and at their own door. */ const stallOf = (v: Villager): Vec3 => [v.stall[0], 0, v.stall[2] + 1.4]; const wellOf = (v: Villager): Vec3 => [ WELL[0] - 1.2 + HOMES.indexOf(v.home) * 1.2, 0, WELL[2] + 1.4, ]; const doorOf = (v: Villager): Vec3 => [v.home[0] - 1.6, 0, v.home[2]]; const tree = buildBehaviorTree(DAY, { actions: { toAwning: (v: Villager) => walkTo(v, [AWNING[0], 0, AWNING[2] + (HOMES.indexOf(v.home) - 1) * 1.2], 3.2), waitOut: () => (raining ? RUNNING : SUCCESS), toStall: (v: Villager) => walkTo(v, stallOf(v), 1.4), trade: (v: Villager) => spend(v, stallOf(v), 'trade', 4), toWell: (v: Villager) => walkTo(v, wellOf(v), 1.4), drawWater: (v: Villager) => spend(v, wellOf(v), 'draw', 3), toHome: (v: Villager) => walkTo(v, doorOf(v), 1.4), rest: (v: Villager) => spend(v, doorOf(v), 'rest', 4), }, conditions: { raining: () => raining }, }); ``` `buildBehaviorTree(spec, tasks)` resolves the names once against your `actions` and `conditions`, each a function of whatever context you hand a tick, and flattens the tree into arrays, so a tick allocates nothing and reads no clock. A `BehaviorRunner` is one character's place in a tree that any number share: `tick(context)` advances it, `paused` holds it while the world carries on and `stepOnce` advances it anyway, `reset()` starts it from the top, and `status` is what the last tick answered. `activePath(out)` fills in the chain of nodes the last tick was inside, root first, and `nameOf` turns one into the name it was written with, which is how the example's readout says what everybody is doing without any of it being kept twice. ## The day, in DriftScript ```drs // One frame of the village: every routine advanced, then asked what it is doing. fn day(square: mut Square, first: Behavior, second: Behavior, third: Behavior, crier: Agent) { behavior.setPaused(first, square.holdFirst) behavior.tick(first) behavior.tick(second) behavior.tick(third) square.sheltering = count(first, "shelter") + count(second, "shelter") + count(third, "shelter") square.trading = count(first, "trade") + count(second, "trade") + count(third, "trade") // The crier hears about the weather once, when it changes. if square.raining != square.wasRaining { if square.raining { ai.wake(crier, "it started raining", 5) } else { ai.wake(crier, "the rain stopped", 3) } square.wasRaining = square.raining } } fn count(villager: Behavior, node: String) -> u32 { if behavior.doing(villager, node) { return 1 } return 0 } ``` ```ts /** The village's day, hosted with the routines it drives and the agents it may wake. */ const village = hostScript(villageScript, { behavior: { context: (routine) => villagers[routines.indexOf(routine as BehaviorRunner)], }, ai: { agents: { get: (id) => (id === 'crier' ? session : undefined) } }, }); interface Square { raining: boolean; wasRaining: boolean; holdFirst: boolean; sheltering: number; trading: number; } const square = exported<() => Square>(village, 'createSquare')(); type Day = ( square: Square, first: BehaviorRunner, second: BehaviorRunner, third: BehaviorRunner, crier: AgentSession, ) => void; if (import.meta.hot) { import.meta.hot.accept('./village.drs', (next) => { if (next !== undefined) patchModule(village, next as Record, { Square: [square] }); }); } ``` `drift/behavior` drives a tree its host built; a script does not author one, since the actions a tree calls are your own verbs in TypeScript. The host hands over a `context` function, which gives the tick of each runner the thing its actions act on. A module has `tick` and `step`, `restart`, `setPaused` and `paused`, `status`, `depth`, and `doing(behavior, name)`, whether the character is inside a node of that name right now. `doing` is what lets a script react to a routine without a second copy of its state: count who is sheltering, light a lantern while someone walks home, refuse to talk to someone mid-errand. Watching is deterministic and advancing is not, so a `@deterministic` system may ask `doing` and not call `tick`. ## An agent that never waits ```ts /** The floor: whichever corner is furthest from him, so he always has somewhere to go next. */ const CORNERS: Vec3[] = [ [-8, 0, -5], [8, 0, -5], [-8, 0, 3], [8, 0, 3], ]; const floor = new UtilityPolicy( CORNERS.map((corner, at): PolicyOption => ({ intent: { id: `walk to corner ${at + 1}`, priority: 1, toolIds: ['navigate@1'], args: [{ agentId: 'crier', x: corner[0], y: 0, z: corner[2] } satisfies NavigateArgs], expectedExtentMs: UNKNOWN_EXTENT, source: 'floor', }, score: () => Math.hypot(corner[0] - crier.x, corner[2] - crier.z), })), ); ``` A model may take fifty milliseconds to answer, or five seconds, or never, and a character that waits for it visibly stands still. So an `AgentSession` keeps two things. The floor is an `AgentPolicy`, deterministic and synchronous, that picks an intent whenever the slot is empty; `UtilityPolicy` scores a fixed list of options and takes the highest, ties to the first. And while the current intent runs, the next is already being asked for: one request per agent in flight at most, sent when the time left on the current intent falls to the provider's measured latency, so a fast model is asked later, against fresher context, and a slow one earlier. ```ts /** A provider that answers after a stated number of ticks: a stand-in for a model, slow or quick. */ const PLACES: [string, Vec3][] = [ ['the well', [8, 0, 3]], ['the stalls', [0, 0, -5]], ['the awning', [-8, 0, 3]], ]; function provider(latencyTicks: number): DeterministicProvider { return new DeterministicProvider((index: number) => { const [, at] = PLACES[index % PLACES.length] as [string, Vec3]; const events: AiEvent[] = [ { kind: 'toolCall', callId: `c${index}`, toolId: 'navigate@1', args: { agentId: 'crier', x: at[0], y: 0, z: at[2] }, }, { kind: 'done', reason: 'complete' }, ]; return { latencyTicks, events }; }); } let answering: DeterministicProvider | undefined; let session = new AgentSession({ agentId: 'crier', policy: floor, tools, world }); function connect(latencyTicks: number | null): void { session.dispose('the provider changed'); answering = latencyTicks === null ? undefined : provider(latencyTicks); session = new AgentSession({ agentId: 'crier', policy: floor, provider: answering, tools, world, }); } ``` An `Intent` names the tools to call and their arguments, how long it is expected to take, and whether it came from the `floor` or a `model`. `tick(tick, nowMs)` returns the intent to carry out, never nothing; `complete(nowMs)` says the current one is done, and `maxIntentMs` reclaims one that was never completed. `current` and `buffered` are the two slots. `observe` tells the agent something happened, and `whileBusy` says what happens to news that arrives while a request is out: fold it into the next, interrupt, or drop it. A provider that is slow, absent or over budget costs the character quality, never motion: with nobody to ask, the crier walks his corners on the floor alone, and with a slow model the floor fills the gaps while the model's answers arrive. ## Tools and their guards ```ts /** * The crier walks a grid of lanes, and the navigation bridge is the one tool he is given: walk to * a point, guarded by there being a route to it from where he is. */ const lanes: NavGraph = buildNavGraph( [-8, 0, -5, 0, 0, -5, 8, 0, -5, -8, 0, 3, 0, 0, 3, 8, 0, 3], [ { from: 0, to: 1 }, { from: 1, to: 2 }, { from: 3, to: 4 }, { from: 4, to: 5 }, { from: 0, to: 3 }, { from: 1, to: 4 }, { from: 2, to: 5 }, ], ); const crier = { x: 0, y: 0, z: 3, heading: 0, path: new NavPath(lanes, 16, { arriveM: 0.3 }) }; const world = { lanes, crier }; const tools = new ToolRegistry(); for (const tool of navigationBridge({ graphOf: (w) => w.lanes, positionOf: (w, _id, out) => { out[0] = w.crier.x; out[1] = 0; out[2] = w.crier.z; return true; }, pathOf: (w) => w.crier.path, })) { tools.register(tool); } ``` ```ts /** A tool is a versioned id, a schema its arguments are checked against, a guard and an act. */ const sell: ToolDefinition<{ item: string; count: number }, { sold: number }, Shop> = { id: 'sell@1', description: 'Sell some of one item from the shop.', schema: { kind: 'object', fields: { item: { kind: 'enum', values: ['bread', 'nails', 'cloth'] }, count: { kind: 'number' }, }, }, /* Asked when the intent is proposed and again when it is acted on: still open, still in stock. */ admits: (args, shop) => shop.open && (shop.stock.get(args.item) ?? 0) >= args.count, execute: (args, shop) => { shop.stock.set(args.item, (shop.stock.get(args.item) ?? 0) - args.count); return { sold: args.count }; }, }; const tools = new ToolRegistry(); tools.register(sell); ``` A model never runs code. A tool is registered under a versioned id, `navigate@1`, with a schema its arguments are validated against, an `admits` guard and an `execute`. An intent buffered ahead of time was decided against an older world, so it is a proposal: its guard is asked again when it would start, and one whose guard has gone false is discarded and the floor covers. A model never writes its own guards. `applyCommand(tools, world, command, tick)` runs one tool call through the same checks, which is how the example starts each intent's walk. `navigationBridge(adapter)` gives an agent the one tool every game needs, walking to a point over a `NavGraph`, guarded by a route existing from where it is; the adapter answers which graph, where the agent is, and which `NavPath` it follows. `AuthoritativeAgent` decides an agent's model intents on one peer and replays them on the others, so a networked game asks one model once. ## Providers, budgets and replay ```ts /** A model behind your own endpoint, which holds the key; this package never sees one. */ const provider = createProxyProvider({ endpoint: '/api/model', model: 'shopkeeper', capabilities: { text: true, streamingText: true, structuredOutput: true, toolCalling: true, realtimeAudio: false, imageInput: false, local: false, }, }); /** The floor: mind the shop. Over budget, the agent runs on this alone and says it is degraded. */ const floor = new UtilityPolicy([ { intent: { id: 'mind the shop', priority: 0, toolIds: [], args: [], expectedExtentMs: 5000, source: 'floor', }, score: () => 1, }, ]); const log = new CommandLog(512); export const shopkeeper = new AgentSession({ agentId: 'shopkeeper', policy: floor, provider, tools, world: { stock: new Map([['bread', 12]]), open: true }, budget: new Budget({ requests: 120, costMicros: 50_000 }), log, maxIntentMs: 20_000, }); ``` ```ts /** What the model decided is in the log, so a replay or a rewind asks no provider at all. */ export function replay(ticks: number): string[] { const again = new ReplaySession(log, floor, 'shopkeeper'); const intents: string[] = []; for (let tick = 0; tick < ticks; tick += 1) intents.push(again.tick(tick, tick * 16).id); return intents; } ``` `createProxyProvider` talks to an endpoint you run, which holds the key; the package itself never holds a credential. `createLocalProvider` wraps a model running on the device, accepted only once it has answered a probe, and a failed probe is refused and never falls back to a remote one, since that would quietly move where a player's data goes. `DeterministicProvider` answers after a set number of ticks, which is what the example and every timing test use. A `Budget` caps requests, tokens, cost and wall time, and an agent over it runs on its floor alone and says so in `degraded`. `interruptProvider` is a second, faster model asked only when something interrupts. Every model decision that is accepted is written to a `CommandLog`, and a `ReplaySession` plays a run back from it without asking any provider, which is also what a rewind is. ## The crier, from a script `drift/ai` reaches an agent a host registered: `agent(id)` resolves one; `wake(agent, reason, priority)` tells it something happened and `consider` asks it to think; `intentId` and `degraded` read it; `reachable`, `navigate` and `path` reach the navigation bridge; and `deciding` says whether this peer decides its model intents. The village's day wakes the crier when the rain starts and when it stops. Nothing hands a script the tools or arguments a model chose, since a deterministic system branching on a model's answer would take the other branch on replay. --- # Importing models Content. https://driftengine.dev/docs/content/importing-models Reading glTF, OBJ, STL, USD, 3MF, FBX and Blender files, at build time with the baker or in a worker when a player brings a file. `@driftengine/assets` reads models made elsewhere. There are two places to do it. A model you ship is baked ahead of time into a `.drft` container, which loads fast and streams onto the screen. A model someone brings at run time, a file dropped on a page or an asset a player picks, is read in a worker, written into the same container in memory, and streamed by the same loader. Either way it reaches the screen by one path. The example is a turntable with three models made for it, a lantern as glTF, a vase as OBJ with its material file, and a gear as STL, and it takes any model you drop on the page, with the files it names dropped beside it. It is 28.7 KB gzipped on top of core. (This chapter runs the `models` example at https://driftengine.dev/docs/content/importing-models.) ## What it reads Every format is read by a reader that runs anywhere, with no filesystem and no native code, and is given what it needs as arguments. Support is tiered, and the tier is stated wherever the format is: - **Supported**: glTF 2.0, `.gltf` and `.glb`, which is the one to export when you can choose; Wavefront `.obj` with its `.mtl`; `.stl`; USD as `.usdz` or `.usda`; and `.3mf`. - **Experimental**: `.fbx`, `.kn5`, and Blender's own `.blend`, from 2.79 to 5.x, read from the file's description of itself: meshes, normals, UVs, colour attributes, shape keys, Principled materials with their packed pictures, lights, cameras, the hierarchy and keyed animation. What only Blender can evaluate, a modifier other than the smoothing ones, a constraint, a rig or geometry nodes, is refused by name and never half imported. `MODEL_FORMATS` lists every extension with its tier, `readerFor(extension)` answers whether one is read, and `recognise(bytes)` identifies by its contents a file there is no reader for, a Maya `.mb` or a 3ds Max `.max`, and says which export would work, so it is not fed to a reader that would fail on it. ## Reading one ```ts async function convert({ name, bytes, folder, dropped }: ConvertRequest): Promise { const started = performance.now(); const file = new Uint8Array(bytes); /* A file the model names, by the places it could be: the engine says what to look for. */ const beside = async (named: string): Promise => { for (const candidate of assetCandidates(named)) { const own = dropped?.[basenameOf(candidate)]; if (own !== undefined) return new Uint8Array(own); if (folder === undefined) continue; const found = await fetch(new URL(candidate, folder)); if (found.ok) return new Uint8Array(await found.arrayBuffer()); } return null; }; /* The two zipped or deflated formats need their decompressor ready before the parse. */ const ext = extensionOf(name); const inflate = ext === '.fbx' ? await prepareFbxInflate(bytes, browserInflate) : undefined; const inflateRaw = ext === '.3mf' ? await prepareZipInflate(bytes, browserInflateRaw) : undefined; const imported = await readModel({ name, bytes: file, beside, decompress: unpack, ...(inflate === undefined ? {} : { inflate }), ...(inflateRaw === undefined ? {} : { inflateRaw }), }); /* Y up, one vertex per distinct corner, and no attribute every vertex holds the same value of. */ const up = imported.declaredUp; const oriented = up === undefined ? imported.meshes : orientMeshes(imported.meshes, up); const meshes = oriented.map((mesh) => dropDefaultAttributes(weldMesh(mesh))); /* The pictures the model carries or names, by what their own bytes say they are. A picture that cannot be found is left out, and the surfaces that wear it draw untextured. */ const textures = []; for (const reference of imported.textures ?? []) { const image = reference.bytes ?? (await beside(reference.name)); if (image === null) continue; const info = describeImage(image); textures.push({ name: reference.name, codec: info.codec, width: info.width, height: info.height, bytes: image, }); } /* A coarse outline of the whole model, drawn while the rest arrives, where one is worth it. */ const outline = buildCoarseLevel(meshes, { cells: DEFAULT_COARSE_CELLS }); const drft = writeDrft({ meshes, ...(outline !== null && isOutlineWorthWriting(outline, meshes) ? { lods: [outline] } : {}), ...(imported.materials === undefined ? {} : { materials: imported.materials as DrftMaterial[] }), ...(textures.length === 0 ? {} : { textures }), }); return { ok: true, drft, meshes: meshes.length, ms: performance.now() - started }; } ``` `readModel({ name, bytes, ... })` is the one entry point from a file to meshes. What a format needs beyond its own bytes is passed in: - `beside(name)`, for a file the model names: a `.gltf`'s buffers and pictures, an `.obj`'s `.mtl`. Models rarely state a path that is still true, so `assetCandidates(name)` lists where it could be, the stated path without its drive, the bare file name, and the usual texture folders, and you look in those places. - `inflate` and `inflateRaw`, decompressors for `.fbx` and `.3mf`, which `prepareFbxInflate` and `prepareZipInflate` make ready from the browser's own, since the parse that uses them cannot wait. - `decompress`, for a compressed `.blend`. Blender wrote gzip until 2.9, which a browser has, and zstd from 3.0, which a browser does not, so the example refuses such a file with what to do. A format that needs one of these and is not given it fails with the name of what to pass. `readModel` answers with `meshes`, `materials` paired to them by position, the `textures` the model carries or names, `warnings` and `notes` about what it met, and, where the format has them, `nodes`, `lights`, `skins`, `clips`, a `unitScale`, and the up axis and handedness it was authored with. `orientMeshes` turns a model to y up, `weldMesh` merges the vertices a reader emits one per triangle corner, about six times what the model has, and `dropDefaultAttributes` removes an attribute every vertex holds the same value of. Reading at run time has costs a bake does not. A large model takes seconds to parse and weld, so it never runs on the page's own thread or inside a frame: the example posts the bytes to a worker and gets back one transferred buffer. And the arrays it makes are fresh, so it holds more memory than a baked file would. The container it writes is larger than a baked one too, since it neither quantises vertices nor finds the meshes a model repeats: a 154 MB glTF scene comes to 197 MB this way and bakes to 80 MB. ## Onto the screen ```ts /** Every model is fitted to the turntable: this wide, this tall, standing on it. */ const FIT: DrftFit = { footprint: 1.8, height: 1.6, baseY: 0.1 }; const worker = new Worker(new URL('./convert.ts', import.meta.url), { type: 'module' }); let loader: DrftLoader | null = null; /** The loader whose pipelines have been compiled, so each is prepared once. */ let prepared: DrftLoader | null = null; /** Send a file's bytes to the worker, and stream the container it answers with. */ function open(request: ConvertRequest): void { status = { label: request.name, line: 'READING' }; worker.postMessage(request, [request.bytes]); } worker.onmessage = (event: MessageEvent) => { const reply = event.data; if (!reply.ok) { status = { label: status.label, line: reply.reason }; return; } loader?.dispose(); loader = new DrftLoader(renderer, { uploadsPerFrame: 4 }); status = { label: status.label, line: `${reply.meshes} ${reply.meshes === 1 ? 'MESH' : 'MESHES'} CONVERTED IN ${reply.ms.toFixed(0)} MS`, }; /* The loader streams from a response; a container from a worker is wrapped in one. */ void loader.consume(new Response(reply.drft), FIT); }; ``` ```ts /** Three formats: glTF with its pictures inside it, OBJ with a material beside it, and STL. */ const SAMPLES: Record = { lantern: 'lantern.glb', vase: 'vase.obj', gear: 'gear.stl', }; /* Beside this page: a bundler rewrites `new URL(..., import.meta.url)` for a file, not a folder. */ const folder = new URL('assets/', location.href).href; async function sample(label: string): Promise { const name = SAMPLES[label] ?? 'lantern.glb'; const response = await fetch(new URL(name, folder)); open({ name, bytes: await response.arrayBuffer(), folder }); } /* Any model dropped on the page, and the files dropped with it, such as its `.mtl` or textures. */ addEventListener('dragover', (event) => event.preventDefault()); addEventListener('drop', (event) => { event.preventDefault(); const files = [...(event.dataTransfer?.files ?? [])]; const model = files.find((file) => readerFor(extensionOf(file.name)) !== undefined); if (model === undefined) return; void Promise.all(files.map(async (file) => [file.name, await file.arrayBuffer()] as const)).then( (read) => { const dropped = Object.fromEntries(read); const bytes = dropped[model.name] as ArrayBuffer; delete dropped[model.name]; open({ name: model.name, bytes, dropped }); }, ); }); ``` The worker writes a `.drft` with `writeDrft`, and `DrftLoader.consume(response, fit)` streams it exactly as `load(url, fit)` streams one from a server. The fit is the one thing a loader cannot guess, since a model arrives in its author's units: `footprint` and `height` are what its larger side is scaled to, and `baseY` is where its lowest point sits; `{ fit: 'none' }` keeps it as it is. Dropped files come with the files beside them, so dropping an `.obj` together with its `.mtl` and pictures finds them by name. ```ts /* Every part in its whole material: its copies through one instanced draw, a blended part translucent and writing no depth, glass as glass, each with its own reflectivity. */ loader?.draw(); ``` `draw()` draws this frame's parts into the open mesh pass, each by every rule a container needs: its whole material, so foliage keeps its alpha test and a one-sided card its faces; its copies through one instanced draw, where a baked container found a mesh repeated; a blended part translucent and writing no depth, since its alpha is in its texture; glass as glass; and each part's own reflectivity. A rule missed is a wrong picture rather than an error, a repeated arch drawn once or a decal drawn as a black patch, which is why the loader keeps them. ```ts /* The sun's map around the model as it was fitted, once its file has said how large it is. */ const span = loader?.shadowFit(env.directionalDir, renderer.shadowMapSize, lightMatrix) ?? null; if (span !== null) env.shadowDepthSpan = span; renderer.beginShadowPass(lightMatrix, 'static'); renderer.drawShadowCasters(casters); renderer.endShadowPass(); ``` `casters` offers a shadow pass every part that stands in the light: all but a decal, which would shadow the surface it lies on, each with its material, so a cutout casts the shape in its texture. The example's own `casters` adds the plinth, and is made once so a frame allocates nothing. `shadowFit` fits the sun's map to the model as it was placed, from the bounds its file declares, and returns the depth span the environment takes, or null until the file has said. For a scene of known size that is not one model, `computeLightMatrixForBounds` takes a box; a world that follows a player wants `computeLightMatrix` around the viewer, where the map's texels go furthest. ```ts /* Once the finished model is in, every pipeline its parts draw with is compiled off the frame, so no later frame waits on one. A game would hold its loading screen until this resolves. */ if (loader !== null && loader !== prepared && loader.progress.phase === 'ready') { prepared = loader; void loader.prepare(); } ``` `prepare()` compiles, off the frame, every pipeline the parts will draw with, and resolves when they are ready; one frame drawn behind a loading screen as well compiles the shadow passes' own. A caller who needs a part its own way, a map switched off or a part left out, draws `parts` itself: each is a mesh and the indices of the images its material wears, or -1, with its scales, opacity, reflectivity, cutout, blend, sidedness, glass and copies. `writePartMaterial` turns one into the renderer's material, and `PartDraws` draws any list of them by the same rules as `draw()`. The [`.drft` chapter](https://driftengine.dev/docs/content/drft) covers what else a container holds and how a loader streams it. ## Baking for a release What ships should be baked: a `.drft` is laid out to be uploaded as it arrives, carries a coarse outline to draw while the rest streams, and needs none of the work above at load. The baker runs from a checkout of the engine: ```sh npm run bake -- path/to/model.glb -o public/model.drft npm run bake -- ./a-bought-bundle -o public/model.drft ``` Given a folder, it takes the best-supported format in it and says what it passed over. It welds, quantises, builds the outline and the levels of detail, and can cap or re-encode textures, build colliders, and hand a `.blend` it cannot read to an installed Blender, saying which route each file took. [Command-line tools](https://driftengine.dev/docs/content/cli) lists its options. --- # The .drft container Content. https://driftengine.dev/docs/content/drft The engine's own file: loaded without parsing, streamed onto the screen as it arrives, and opened by every future reader. A `.drft` file is a model, a level or a world, baked into the layout the engine uploads. Its vertex and index arrays sit in the file at the alignment a GPU takes, so reading one is building views over the bytes, with nothing parsed and nothing copied. Its pictures are inside it, so a level is one fetch and cannot half load. And a file written today opens in every reader to come. `@driftengine/drft` reads and writes the container and depends on nothing; it is 14.3 KB gzipped. `DrftLoader`, in `@driftengine/assets`, streams one onto the screen. The [models example](https://driftengine.dev/docs/content/importing-models) writes a container in a worker and streams it with that loader. ## Writing and reading one ```ts /** Two meshes and a name: everything else a container can carry is optional. */ const crate = new MeshBuilder().addBox([0, 0.5, 0], [0.5, 0.5, 0.5], [0.6, 0.45, 0.3]).build(); const lid = new MeshBuilder().addBox([0, 1.05, 0], [0.55, 0.05, 0.55], [0.4, 0.3, 0.2]).build(); export const file: ArrayBuffer = writeDrft({ head: { name: 'crate' }, meshes: [crate, lid] }); ``` ```ts /** Read whole: each array is a view over the file's own bytes, with nothing parsed or copied. */ export function describe(bytes: ArrayBuffer): string { const asset = readDrft(bytes); const vertices = asset.meshes.reduce((sum, mesh) => sum + mesh.positions.length / 3, 0); return `${asset.head.name}: ${asset.meshes.length} meshes, ${vertices} vertices`; } ``` `writeDrft(source)` takes meshes and, optionally, a `head` with a name and units, materials, textures, levels of detail, a hierarchy, skins, clips, lights, colliders, a navigation mesh, an entity scene and more, and answers one `ArrayBuffer`. `readDrft(bytes)` reads it back whole, as a `DrftAsset`: its `head`, `meshes`, `lods`, `materials` and `textures`, `nodes`, `instances`, `lights`, `skins` and `clips`, `navigation`, `entities` and the rest, each empty where the file had none. For something you ship, the [baker](https://driftengine.dev/docs/content/cli) writes it from a model. ## What a file holds A header, a table of chunks, and the chunks. Each chunk is named by four characters and is either optional or required. Most of what a container can carry is optional: - Geometry: `MESH`, one mesh, its attributes stored separately and in the order a mesh uploads them; `MSHQ`, the same in as few bytes as its data needs; `LODM`, a coarse version of the whole asset to show while the rest arrives; `MSHL`, a mesh's cluster levels for the [GPU-driven pipeline](https://driftengine.dev/docs/rendering/gpu-driven); `INST`, meshes drawn many times; and `KITS` and `MSHC`, a world built from [a kit of pieces](https://driftengine.dev/docs/worlds/worlds-from-a-kit). - Surfaces: `MATL`, a material per mesh with the pictures it wears; `TEXS`, the pictures; `DTEX`, a material as a [decode program](https://driftengine.dev/docs/worlds/drifttexture); `SUBS`, which [substance](https://driftengine.dev/docs/simulation/chemistry) each material is made of; `SDFV`, signed distance fields. - A scene: `NODE`, the hierarchy; `LITE`, its lights; `LVOL`, fixed light summed into a volume; `COLL`, the hulls it collides as; `NAVM`, a [navigation mesh](https://driftengine.dev/docs/simulation/navigation); `ENTS`, its [entities](https://driftengine.dev/docs/simulation/entities). - Motion: `SKIN`, `ANIM` and `MORP`, a rig, its clips and its morph targets. - A streamed world's `REGN` regions, a [splat capture](https://driftengine.dev/docs/worlds/splats)'s `SPLT` blocks, and the weights of small networks the engine evaluates. ## Compatibility The rules are the contract, and they are strict: 1. An old file always opens. A reader loads any file whose required reader version is its own or older, with no expiry and no migration. 2. An optional chunk a reader does not know is skipped, which is what makes adding one free. 3. A required chunk a reader does not know is a refusal naming it, never a partial asset. 4. A minor version only adds; it never changes the meaning of a byte already written. 5. A major version means the layout changed, and a newer file refuses to open in an older reader with both versions named. A test opens a fixture written by each released minor version's own writer, so the old bytes really are old. ## Streaming it onto the screen `DrftLoader` exists so a model builds up on screen instead of appearing after a wait. Its bytes stream, and what arrives is queued and uploaded a few pieces a frame, each fading in: - An outline first, where the file carries one: a coarse whole model drawn until the real geometry is complete, so the picture is an object sharpening, not parts appearing in empty space. - Then the parts, `uploadsPerFrame` and `uploadMsPerFrame` bounding the work in any one frame, and `revealSec` the fade. - Then, after the last byte, the parts merged into one mesh for each image and blend they share, so a model of 187 parts draws in seven calls once it has arrived. `load(url, fit)` fetches and streams, `consume(response, fit)` streams a response from anywhere, and `update(dt)` advances the uploads each frame. `progress` reports the phase, from connecting through the outline, materials, geometry and textures to `ready`, or `absent` for a missing file and `failed` with a `message`. A load never throws: a scene is usually still worth drawing without its model. Once loaded, a loader answers what the file held: `parts` and `textures` to draw, `nodes`, `lights`, `skins`, `clips` and `morphs`, `colliders` and `navigation`, `entities`, a streamed world's `regions`, `modelBounds` and the `placement` it was fitted with. `transform` and `surface` let a consumer decide a material's look by its name as parts arrive, `onMesh` takes a mesh for drawing its own way, `onImage` takes each picture instead of uploading it, and `dispose()` releases everything. ## Waiting for more than one thing ```ts /** Everything a loading screen waits on, weighted, so its bar means something. */ const loading = new LoadTracker(); loading.add('level', 4_000_000); loading.add('music', 900_000); loading.add('settings', 2_000); /** Each part reports as it goes; the summary is the weighted whole and the one to talk about. */ export function loadingLine(levelFraction: number): string { loading.report('level', levelFraction); const { fraction, activeId } = loading.summary; return `${Math.round(fraction * 100)}%, waiting on the ${activeId}`; } ``` A loading screen usually waits on several things at once, a level, its music, a settings file, and a bar that gives each the same share spends most of its life at a half. `LoadTracker` weighs them: `add(id, weight)` registers one, in bytes or any unit that is the same across them, `report(id, fraction)` and `finish(id)` move it, and `summary` gives the weighted `fraction`, whether it is `done`, and `activeId`, the heaviest thing still unfinished, which is the one a person is actually waiting for. A weight can be raised once its real size is known without losing the progress made. --- # Sound and music Content. https://driftengine.dev/docs/content/audio A mix of buses and snapshots, sounds by name, music whose kick drives lights, sounds placed among rooms and walls, and scripts that play it all. `@driftengine/audio` is the engine's sound: a mix built as a tree of buses, sounds addressed by name, layered music with live kick detection, sounds placed in the world with rooms and walls between them, and synthesis, so a game is never silent while its files are missing. It is 6.1 KB gzipped on top of core, and a build that never places a sound in the world does not carry the panner. The example is a courtyard at dusk, and the camera is the listener. A bell strikes on a clock a DriftScript file keeps, and the music ducks under it. A cart rolls past behind a house, muffled while the house is in the way, its pitch falling as it goes by. Stand in the crypt and its reverb takes over, while the lanterns keep time with the kick. Every sound in it is synthesised, so it loads no audio file. Click the page to hear it: a browser starts sound only after a gesture. (This chapter runs the `audio` example at https://driftengine.dev/docs/content/audio.) ## A graph and a gesture ```ts /* The graph: one music stem into a mix of buses. A browser that will give no audio at all still gets a graph, on a context that never plays, so the page and its script run the same. */ const graph = (await AudioGraph.create({ stemCount: 1 })) ?? (await AudioGraph.create({ stemCount: 1, context: new OfflineAudioContext(2, 1, 48000) })); if (graph === null) throw new Error('no audio graph, even offline'); const mix = graph.console; /* Every sound is a named slot: its files are tried first and its synth stands in when none loads. This page lists no files, so all five are made here. */ const sounds = graph.registry; sounds.register('bell', { urls: [], synth: (context) => metalBuffer(context, 5, 155, 0.9) }); sounds.register('wheels', { urls: [], synth: (context) => noiseBuffer(context, 3, 0, () => 0.05) }); sounds.register('fire', { urls: [], synth: (context) => fireLoopBuffer(context) }); sounds.register('wind', { urls: [], synth: (context) => windLoopBuffer(context) }); sounds.register('beat', { urls: [], synth: beatBuffer }); await sounds.load(graph.context); const slot = (name: string): AudioBuffer => { const buffer = sounds.get(name); if (buffer === undefined) throw new Error(`the ${name} slot did not build`); return buffer; }; graph.loadStem(0, slot('beat')); graph.setStemGain(0, 0.8); ``` `AudioGraph.create(options)` builds the graph, and returns null only when the browser has no audio at all. A context made before the person has clicked or pressed a key is suspended, which is not a failure: nothing is lost, its clock waits, and `wake()` on the first gesture starts it. `audible` says whether it is producing sound. On an iPhone the graph also claims the playback session, so a phone with its ringer switched off still plays the game; an application building its own context calls `claimPlaybackSession()` and `audioContextConstructor()` for the same reason. ```ts /* A context only plays after a gesture on the page, so the first click or key wakes it and starts the music and the loops. Started before one, each would only add a warning to the console. */ let started = false; const listen = (): void => { graph.wake(); if (started) return; started = true; graph.start(); gusts.start(); fire.start(); cart.start(); }; addEventListener('pointerdown', listen); addEventListener('keydown', listen); ``` ## Sounds by name A sound is a slot, registered with the files it may be and a synthesised stand-in, then loaded once. The files are tried in order and the first that decodes wins. A slot nothing loads gets its synth, and `resolved` says which each slot got, so a game is audible from its first day and a file dropped into the folder replaces the stand-in with no change to the code. `audioCandidateUrls(name)` lists a name in every format in `AUDIO_FORMATS`, Opus first, so a sound can arrive in whatever it was saved as. A slot registered **without** a `synth` is required: a score that has to be the file or nothing. When none of its files loads, `load` still settles every other slot, then rejects with an error naming each missing required slot and the files it tried, and `unbuilt` lists it. The stand-ins are ordinary functions of a context: `noiseBuffer` and `toneBuffer`, `metalBuffer` for a struck bar, `fireLoopBuffer`, `waterLoopBuffer` and `windLoopBuffer`, `ambienceBuffer`, `driftScrapeBuffer` and `silentBuffer`. A folder whose contents are not known in advance announces them in a manifest written at build time: ```ts /** * A folder of sounds announcing itself: a manifest written at build time names them, and each * becomes a slot that tries every format it might have been saved in, silent if none loads. */ export async function registerFolder(sounds: SoundRegistry): Promise { const names = await fetchAudioManifest('/audio/manifest.json'); for (const name of names) { sounds.register(name, { urls: audioCandidateUrls(name), synth: silentBuffer }); } return names; } ``` ## The mix ```ts /* The yard's own sounds on a bus of their own, under the effects, so the crypt can turn them down. */ const yard = mix.bus('yard', { parent: graph.layout.effects }); /* Two mixes the script recalls by name: the yard as it is, and the crypt, where the music and the yard are far away. */ mix.snapshot('yard'); graph.layout.music.setLevel(0.35); yard.setLevel(0.4); mix.snapshot('crypt'); graph.layout.music.setLevel(1); yard.setLevel(1); /* The wind, on a bus made after both snapshots: a recall leaves alone a bus it never saw, so the weather belongs to the script's `fade` and to nothing else. */ const wind = mix.bus('wind', { parent: graph.layout.effects, level: 0 }); const gusts = graph.context.createBufferSource(); gusts.buffer = slot('wind'); gusts.loop = true; gusts.connect(wind.input); ``` The mix is a tree of buses on a `MixConsole`, `graph.console`. The graph's own layout, `graph.layout`, is a `music` bus and an `effects` bus into a master filter, with two reverbs and a delay fed from the music; `mix.bus(name, options)` adds one of your own under any parent. Each bus has a fader, `setLevel` and `fadeLevel`, which is the player's setting, and a duck over it, `duck(factor, seconds)`, which is the game's: a duck comes back to wherever the fader is, including a level the player changed in the meantime. A bus can be muted, soloed, sent to a return with `send`, and given inserts. `liftInsert`, `slamInsert` and `masterFilterInsert` are the ones the layout uses; `convolverInsert` and `delayInsert` build returns, and `impulseResponse` the room a convolver plays. `snapshot(name)` captures every fader, mute and send, and `recall(name, seconds)` crossfades back to it. Insert parameters are left out, because something per frame usually writes them. A bus made after a snapshot was taken is untouched by its recall, which is why the example's wind has a bus made afterwards: the crypt's snapshot turns the yard down and leaves the weather to the script. Music is a set of stems played in lockstep: `loadStem(index, buffer)`, `setStemGain` to bring layers in and out, `start`, `hold` and `release`, and `setPlaybackRate`, with the transport kept where the tape actually is. `restart(fromSec)` starts every stem again from a point in the track, locked together, for music held to a clock of the game's own, such as a frame counter that resumes after a skip; it returns how long until that point is heard. `createLoop(buffer)` starts a looping bed through the effects, and `play(buffer, gain, pan)` plays a one-shot. `cutoffForSpeed` gives the master filter's cutoff for a speed, so the sound opens up as something goes faster. ## Where a sound is There are two ways to place a sound, at very different prices. The cheap one is arithmetic: `distanceGain(distance, radius)` and `stereoPan(dx, dz, yaw)`, applied to a loop or a one-shot. It is right for anything diffuse, a fire, a shoreline, rain on a roof, where how near and which side is all a player reads. ```ts /** * A fire heard the cheap way: a loop through the effects, louder as you near it and on its side * of your head. Right for anything diffuse, where how close and which way is all a player reads. */ export function hearFire( loop: AmbientLoop, fire: readonly [number, number], ears: readonly [number, number], yaw: number, ): void { const dx = fire[0] - ears[0]; const dz = fire[1] - ears[1]; loop.setGain(distanceGain(Math.hypot(dx, dz), 25)); loop.setPan(stereoPan(dx, dz, yaw)); } ``` The other is a listener and sources placed in the world: ```ts /* The ears, and the things heard from a place: a room the listener can stand in, the fire, and a cart that passes. A placed source is the expensive path, for when the direction is information. */ const listener = createListener(mix); const crypt = addReverbZone( listener, 'crypt', { x: 9.5, y: 1.5, z: -7.5, radius: 2.2, blend: 1.5 }, { seconds: 3.4, decay: 2.2, wet: 0.85 }, ); const fire = createSpatialSource(listener, slot('fire'), { loop: true, bus: yard, refDistance: 2 }); const cart = createSpatialSource(listener, slot('wheels'), { loop: true, bus: yard, doppler: true, refDistance: 4, }); fire.place(1.5, 0.4, -3, 0); /* What a line from a sound to the ears can be blocked by: the house, the tower and the crypt's walls, as boxes. The listener asks, spread over the sources, and the answer is smoothed. */ const SOLIDS: readonly (readonly number[])[] = [ [-5, 0, -12.2, 5, 4.4, -9.8], [-10.4, 0, -8.4, -7.6, 8, -5.6], [7, 0, -10, 12, 3, -9.65], [7, 0, -10, 7.35, 3, -5], [11.65, 0, -10, 12, 3, -5], [7, 0, -5.35, 8.8, 3, -5], [10.2, 0, -5.35, 12, 3, -5], ]; const walls: OcclusionProbe = (ax, ay, az, bx, by, bz) => { for (const box of SOLIDS) if (crosses(box, ax, ay, az, bx, by, bz)) return 0.85; return 0; }; listener.probe = walls; ``` `createListener(mix)` is the ears, set each frame from the camera with `set(x, y, z, yaw, pitch, dt)`. Its velocity is derived from its movement, and `warp` moves it without travelling, for a cut. `createSpatialSource(listener, buffer, options)` is a sound through an HRTF panner, for when the direction is information: a footstep behind you, a voice through a doorway. With `doppler` its pitch moves with relative speed, up to `maxDopplerCents`. `place` it each frame, and `warp` it to jump. Occlusion is a function you give the listener as its `probe`, answering how blocked the line between two points is, from 0 to 1. The engine never sees your walls: you close the probe over whatever you have, a collider set or a tile map. Probes are spread across frames and the answer is smoothed, and `setOcclusion` states it outright for a source whose answer you already know. `addReverbZone(listener, name, shape, options)` is a space with its own tail: a sphere, full inside its radius and fading out over `blend`. The zones the listener stands in decide the reverb of everything heard there, at most `MAX_OPEN_ZONES` of them, the one being left and the one being entered. Its convolver is built with the zone, never on entry. A sound inside a space heard from outside it attaches the zone itself: ```ts /** * A voice inside the crypt carries the crypt's tail even to a listener outside it, which a * listener-based zone alone cannot do. One gain node, since the zone's convolver already exists. */ export function listenInto(voice: SpatialSource, crypt: ReverbZone): void { voice.attachZone(crypt); } ``` A four-channel ambisonic recording is a whole soundfield, decoded around the listener through six virtual speakers at one fixed cost however much is in it: ```ts /** * A four-channel ambisonic recording, a forest at night, decoded around the listener's head at a * fixed cost however many birds are in it. It follows the listener; turning the head turns it. */ export function forest(listener: AudioListenerGraph, recording: AudioBuffer): () => void { const field = createAmbisonicSoundfield(listener, recording, { loop: true }); field.setGain(0.6); field.start(); return () => field.follow(); } ``` `encodeFoa`, `foaDecodeGain` and `foaDecodeMatrix` are the arithmetic underneath, for a consumer encoding its own. ## Rhythm `graph.createKickDetector()` listens to the music bus, never to the game's own sounds, and its `update(nowMs)` advances it once a frame. `pulse` spikes on each kick and falls back, which is what a light should follow. `level` is the low end left once the bassline is masked out, which keeps moving with the kick on a loud master where `energy`, the raw low end, sits at its ceiling. The bands it listens to are `RHYTHM_BANDS`. Ahead of time, `analyseTrack(samples, sampleRate)` finds where the kicks are in a whole track: a `BeatMap` of beats and their strengths, a tempo and how sure it is, and a loudness envelope for finding drops. It looks ahead, so a cut placed on a beat lands on the transient, and a track gives the same map every time. Syncopated music can read at twice its tempo, as the example's beat does, so `beatGrid(bpm, offsetSec, durationSec)` makes a grid from a tempo you know, and `TapTempo` from one a player tapped. ```ts /** * Where the kicks are in a whole track, found once ahead of time; the same pulse a live detector * would give, read at any instant of a rendered clip; and, for music whose tempo is known, a grid. */ export function beatsOf( track: AudioBuffer, bpm: number, ): { map: BeatMap; pulse: RenderedPulse; grid: BeatMap } { const map = analyseTrack(track.getChannelData(0), track.sampleRate); const pulse = new RenderedPulse(track); const grid = beatGrid(bpm, 0, track.duration); return { map, pulse, grid }; } /** Or the player taps along, and the tempo is what they tapped. */ export const tapper = new TapTempo(); export function tapped(nowMs: number): number | null { tapper.tap(nowMs); return tapper.bpm; } ``` `RenderedPulse` reads the live detector's pulse out of a finished buffer at any instant, so a clip rendered offline flashes exactly as the game did. ## Rendering offline A graph built on an `OfflineAudioContext` renders the mix to a buffer, faster than real time, for a clip or a test. Offline there is no "now", so `at(seconds)` puts every move that follows at that instant of the clip: ```ts /** * A mix rendered to a buffer, for a clip: the same graph on an offline context, every move * scheduled at the instant it belongs to rather than at a clock that is not running. */ export async function renderClip(score: AudioBuffer, seconds: number): Promise { const context = new OfflineAudioContext(2, Math.ceil(seconds * 48000), 48000); const graph = await AudioGraph.create({ stemCount: 1, context, levels: { music: 0.8, effects: 1 }, }); if (graph === null) throw new Error('no graph on an offline context'); graph.loadStem(0, score); graph.setStemGain(0, 1); graph.at(0); graph.start(); /* Halfway through, the score goes under for two seconds. */ graph.at(seconds / 2); graph.layout.music.duck(0.2, 0.3); graph.at(seconds / 2 + 2); graph.layout.music.duck(1, 0.5); return context.startRendering(); } ``` `levels` starts the faders where a player had them, and `random` seeds the noise the reverbs are made of, so two renders agree sample for sample. `captureStream()` taps the live mix for a `MediaRecorder` instead, which aligns its tracks by when they arrive and so cannot be frame-exact. ## From DriftScript `drift/audio` gives a script nine capabilities. `sound(slot)` answers a `Sound?`, absent when the slot holds nothing, so a script cannot play silence and believe it played; `play` and `playPanned` play it. `distanceGain` and `stereoPan` are the cheap arithmetic, and deterministic, so a `@deterministic` function can use them. `duck`, `fade` and `recall` turn the mix by the names the host gave its buses and snapshots, and answer `false` when nothing has that name. `pulse` reads the host's kick detector, and is `0` without one. The courtyard's bell: ```drs // The bell strikes on its own clock and is heard the cheap way: louder the nearer you stand, and // on the side it is on. The music steps aside for it and comes back as the ring dies away. fn toll(yard: mut Courtyard, ears: Ears) { if yard.next > yard.clock + yard.every { yard.next = yard.clock + yard.every } if yard.returns >= 0 && yard.clock >= yard.returns { audio.duck("music", 1, 2.5) yard.returns = -1 } if yard.clock < yard.next { return } yard.next = yard.clock + yard.every yard.since = 0 yard.strikes += 1 let dx = BELL_X - ears.x let dz = BELL_Z - ears.z let near = audio.distanceGain(math.sqrt(dx * dx + dz * dz), 80m) if let clang = audio.sound("bell") { audio.playPanned(clang, near, audio.stereoPan(dx, dz, ears.yaw)) } audio.duck("music", 0.3, 0.12) yard.returns = yard.clock + 2.5 } ``` Sound is outside the [determinism](https://driftengine.dev/docs/concepts/determinism) boundary: playing one, moving the mix or reading the kick is an effect a `@deterministic` function may not have. A simulation decides that a door opened, and something outside the fixed step decides what it sounds like. The host binds the module with its graph, its registry and, when it runs one, its kick detector: ```ts /* The script, bound to the mix and the sounds, and to the kick detector listening to the music. */ const kick = graph.createKickDetector(); const script = hostScript(courtyardScript, { audio: { graph, registry: sounds, ...(kick === null ? {} : { kick }) }, }); interface Courtyard { every: number; next: number; since: number; strikes: number; clock: number; windy: boolean; glow: number; } interface Ears { x: number; z: number; yaw: number; indoors: boolean; } const court = exported<() => Courtyard>(script, 'createCourtyard')(); const ears = exported<() => Ears>(script, 'createEars')(); type Tick = (yard: Courtyard, ears: Ears, dt: number) => void; if (import.meta.hot) { import.meta.hot.accept('./courtyard.drs', (next) => { if (next !== undefined) { patchModule(script, next as Record, { Courtyard: [court], Ears: [ears] }); } }); } ``` The listener, placed sources and reverb zones cannot be scripted yet. Each is an object with a lifetime, and handing one to a script is a design about who disposes of it. A script works out where and how loud a sound should be, as the courtyard's does for its bell, and the page places it. --- # Command-line tools Content. https://driftengine.dev/docs/content/cli The baker and its options, exporting back to glTF, comparing two containers, a distance-field font, the visual gate, the frame audit and the dev servers. The engine's tools run from a checkout of its repository, in Node, and none of them ships inside a package a game installs. They are what produces the files a game loads, a baked `.drft` or a font atlas, and what checks a change to the engine did what it says. The one exception is `drift-package`, the packager, which is published as a command of its own with `@driftengine/package`. ## The baker ```sh npm run bake -- path/to/model.glb -o public/model.drft npm run bake -- ./a-bought-bundle -o public/model.drft npm run bake -- ./a-bought-bundle --from obj -o public/model.drft ``` `bake` reads a model in any format [the importers](https://driftengine.dev/docs/content/importing-models) read and writes a [`.drft` container](https://driftengine.dev/docs/content/drft). Given a folder, it looks through it for every model, picks the best-supported format present, and prints what it chose and what it passed over, because a bought asset usually ships the same model several times over and the reader used should never be a surprise. `--from` names the format to take from a folder instead. On the way it welds the mesh to one vertex per distinct corner, drops attributes every vertex holds the same value of, derives tangents where a material has a normal map, finds copies an export merged into one mesh and writes them as one mesh drawn many times, quantises the geometry, embeds the pictures the model names, and builds the coarse outline a loader draws while the rest arrives. Every step it took and every warning is printed. | Option | What it does | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `-o file` | Where to write the container. | | `--from ext` | Take this format from a folder, `obj` or `fbx` for example, instead of the best-supported one. | | `--up axis` | Which way is up in the source, one of `+x`, `-x`, `+y`, `-y`, `+z`, `-z`, over what the file declares. It is never guessed; the baker warns when a model sits below its origin. | | `--lod cells` | The outline's grid resolution, 40 cells by default. | | `--no-lod` | Write no outline, for a model where the printed triangle count comes out absurd. | | `--no-levels` | Skip the separate level-of-detail files a bundle ships beside its model, each otherwise baked whole with its own pictures. | | `--max-texture px` | Halve every picture until its longer side fits in `px`. | | `--texture-codec jpeg` | Re-encode opaque PNGs as JPEG, normal maps excepted. `jpeg-all` takes the normal maps too. | | `--normals-directx` | The normal maps point green down, as DirectX tools write them; turn each over on the way in. | | `--decode-dds` | Decode each DDS to a PNG rather than keep its BC blocks and mip chain, for a reader older than container 1.24. | | `--blend-as-cutout` | Bake every blended material as a cutout at 0.5. Foliage is often exported blended; each conversion is printed so a pane of glass is caught. | | `--simplify m` | Reduce every mesh to the triangles its shape needs, the surface moving no more than `m` metres. | | `--sdf m` | Write a signed distance field over the static geometry at `m` metres a voxel, for [traced light](https://driftengine.dev/docs/rendering/driftray). | | `--no-instances` | Write merged copies as they came, without finding the repeats. | | `--no-quantise` | Write full-precision geometry. Quantised geometry is about a third of the size, within stated bounds. | | `--collider none` | The default: write no collision shape, since a bake should not invent one. | | `--collider box` | One box around the model. | | `--collider hull` or `hull:N` | Convex hulls decomposed from the model, 16 at most or `N`, up to 32, for [rigid bodies](https://driftengine.dev/docs/simulation/rigid-bodies). | | `--direct` | Read a `.blend` with the engine's own reader, whatever it has to approximate. | | `--via-blender` | Export a `.blend` through an installed Blender, found on the path or named by the `BLENDER` environment variable. | A `.blend` is read directly first. When it holds something only Blender can evaluate, a rig, a constraint or a modifier, the baker hands it to Blender's own glTF exporter, and says which route it took and why. Without Blender installed, the direct read stands and the approximations are listed. ## The way back out ```sh npm run export -- public/model.drft -o model.glb ``` `export` writes a container as a glTF 2.0 binary, so a baked character or level opens in Blender or any glTF editor, is improved there, and bakes back with `bake`. What glTF has a field for goes in that field: the meshes, the materials, the skeleton with the bone names a game binds by, every clip by name, the attachment points as nodes under the bones they follow, and the lamps. What it has no field for, the entity manifest, the colliders, the regions and the meshes drawn many times, rides in the file's `extras`, which Blender keeps. Export from Blender with custom properties, punctual lights and attributes included, or the lamps and the engine's own vertex values are left out of what it saves. A container the baker wrote comes back byte for byte. What a modelling tool changed comes back as it changed it: an edited material is read from its glTF fields, a moved lamp stands where it was moved, and the baker says which of the engine's own values it could not restore. A world built from kit pieces and a Gaussian splat capture are refused, since glTF has no form for either, and a picture held as raw texels or block-compressed goes out as PNG. In code, `drftToGlb` does the export and `bakeModel` is the bake the command runs. ## Comparing two containers ```sh npx tsx scripts/drft-diff.ts a.drft b.drft ``` `drft-diff` compares what two containers mean, the geometry totals, the materials and the pictures, and ignores how their bytes are laid out, since two readers of one model can legitimately group its meshes differently. It is how a `.glb` and an `.fbx` of the same asset are shown to bake to the same thing, and `npm run bake:check` uses it to prove two bakes of one file agree. ## A distance-field font ```sh npm run sdf-font -- --font ./Display.ttf --out ./public/fonts --glyphs ./glyphs.txt ``` `sdf-font` turns a TrueType font and a list of characters into the atlas and metrics that [distance-field text](https://driftengine.dev/docs/rendering/text-and-overlays) draws: `atlas.png`, and `metrics.json`, which `parseSdfFont` reads. It draws each glyph large through headless Chrome's own text stack and runs a distance transform over it, so it needs no font parser, and measures kerning by setting each pair. More `--font` arguments are fallbacks in order, `--runs` adds whole strings drawn as one entry, and `--size`, `--padding`, `--distance-range`, `--texels-per-em` and `--supersample` (4 by default) tune the atlas. ## The visual gate A test cannot see a picture, so a change to rendering is checked by photographing held frames before and after it: ```sh npm run demo # in one terminal node scripts/shots.mjs capture before node scripts/shots.mjs capture after # after the change, with the server restarted node scripts/shots.mjs diff before after ``` `?hold=N` freezes every scene at the same frame, so two captures of one build differ in no pixel and any difference is the change. `--backend=webgl2` photographs the other backend under its own name, so a comparison never compares a backend with itself. `--delta` is how far a pixel must move to count, and a faint effect needs it lower than the default. `--islands` sorts the changed pixels into regions so a defect stands out from noise, and `--base` with `--scenes=0` points the gate at a page of your own. The capture refuses a software renderer, whose pictures would compare nothing real. `probe-check.mjs` drives the backend acceptance probe and prints what it costs to compile every shader the engine ships on this machine. ## The frame audit ```sh node scripts/frame-audit.mjs # a phone viewport node scripts/frame-audit.mjs --desktop node scripts/frame-audit.mjs --url=https://example.com/your-game/ ``` A clock on a desktop cannot say why a frame is slow on a phone: a phone's GPU is bound by memory traffic a desktop's hides. `frame-audit` counts what a frame moves instead, the passes, which attachments are stored and loaded and how many bytes that is, by wrapping the page's own WebGPU calls before its scripts run. Those numbers are the same on every device, so they can be read here and trusted there. ## The dev servers | Command | What it serves | | ------------------ | -------------------------------------------------------------------------------------------------------- | | `npm run examples` | The examples this manual runs, every one at its own address; `?backend=webgl2` forces the other backend. | | `npm run demo` | The engine's own scenes, the pages the visual gate photographs. | | `npm run editor` | The editor. | --- # Input Interface. https://driftengine.dev/docs/interface/input Keyboard, mouse, gamepads and touch through one action map, with rebinding and saving, prompts for the device in use, rumble, and scripts that read it. [Moving things](https://driftengine.dev/docs/start/moving-things) introduces the three layers: an `InputSource` that captures the devices, an `ActionMap` that names what the player means, and `TouchControls` for a touch screen. This chapter goes further: every device at once, gamepads by what they are, a controls screen that rebinds and saves, rumble, touch in detail, and scripts that read all of it. The example is a puck in an arena. The keyboard, a gamepad and a touch screen all drive it, because its script asks an action map what the player means and never which device said so. The panel on the right rebinds boost and brake to the next key or button pressed, and the prompts name whatever the player last used: a key, the label printed on their pad, or a tap. (This chapter runs the `input` example at https://driftengine.dev/docs/interface/input.) ## Every device at once ```ts /* Every device at once. The keys listed are kept from the page, so Space does not scroll it. */ const input = new InputSource(canvas, [ 'Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ShiftLeft', ]); const actions = new ActionMap(input, { move: { stick: 'left', up: ['KeyW', 'ArrowUp'], down: ['KeyS', 'ArrowDown'], left: ['KeyA', 'ArrowLeft'], right: ['KeyD', 'ArrowRight'], }, boost: { keys: ['Space'], buttons: ['faceDown'] }, brake: { keys: ['ShiftLeft'], buttons: ['faceRight', 'l2'] }, }); /* A stick where the left thumb lands, and taps and holds on the right of the screen. */ const touch = new TouchControls(input, { stickBase: document.querySelector('#stick-base') ?? undefined, stickNub: document.querySelector('#stick-nub') ?? undefined, }); ``` `new InputSource(target, preventDefaultCodes, options)` reads the keyboard, the mouse, touches and gamepads together. The codes listed keep their browser default from happening, so Space does not scroll the page. The options turn a device off with `sources`, which leaves it inert, never taking the prompts, and stops the gamepad poll outright; set the stick `deadzone`, `DEFAULT_DEADZONE` when omitted; and with `autoPoll: false` leave the sampling to you, calling `poll()` at the start of each fixed step so a recorded replay samples the same input on every run. `setSourceEnabled(source, enabled)` does the same at run time, which is the example's gamepad switch. `lastDevice` is the device the player last actually used, never one that is merely connected: a pad left on the desk changes nothing until it is pressed or its stick moved, and the mouse counts only after it has travelled a little way. `onDeviceChange(listener)` is told when that changes and only then. Prompts follow it, so a player who picks up a pad sees its buttons and one who goes back to the keyboard sees keys. A key typed into a text field is not the game's, and `isTypingTarget(element)` is the test the source applies. ## Gamepads `pads` is every connected pad and `pad(index)` one of them, as a `GamepadView`, up to four for local play. Buttons are named by position, `faceDown`, `faceRight`, `faceLeft` and `faceUp`, the shoulders `l1`, `r1` and the triggers `l2`, `r2`, `select`, `start`, the stick clicks `l3` and `r3`, the d-pad and `guide`, so a binding means the same place on every pad. A view answers `down`, `pressed` and `consumePress` for a button, `axis` for a stick, deadzoned, and `trigger` for how far a trigger is pulled. On a pad whose `mapping` is not `standard`, `button(index)` and `rawAxis(index)` read it by number. `identity` says what the pad is. Its `family` is `xbox`, `playstation`, `nintendo` or `generic`, read from the vendor, and `label(button)` is what is printed on the plastic: `faceDown` is A on one family, Cross on another and B on a third. `glyph(button)` is a stable key such as `xbox.a` for an icon set of your own; the engine ships no art. A pad can rumble where the browser can drive its motors, which most cannot. `canRumble` says so, and a settings screen greys the control out when it is false. `rumble(durationMs, strong, weak)` drives the low and high motors, from 0 to 1, for at most `MAX_RUMBLE_MS`, and `stopRumble` stops it. Both answer whether the platform took the request, and false is a real answer, never an error. An action map forwards all three to the pad it reads. ## Rebinding and saving ```ts function bind(binding: Binding, said: string): void { if (waiting === null) return; const displaced = actions.rebind(waiting, binding); actions.save(store, SAVED); if (note !== null) { note.textContent = displaced.length > 0 ? `${said} was taken from ${displaced.join(' and ')}` : ''; } waiting = null; drawRows(); } addEventListener('keydown', (event) => { if (waiting === null) return; event.preventDefault(); bind({ device: 'keyboard', code: event.code }, keyName(event.code)); }); /** Called each frame while a row is waiting: the first button any pad pressed. */ function listenToPads(): void { if (waiting === null) return; for (const pad of input.pads) { for (const button of BUTTONS) { if (pad.pressed(button)) { bind({ device: 'gamepad', button }, pad.identity.label(button)); return; } } } } ``` `bindingsFor(action)` is what currently satisfies an action, and `rebind(action, binding)` adds one: a key by its code, a pad button by its position, or a mouse button, `{ device: 'mouse', button: 'left' }`, which a digital action also takes from its definition as `mouseButtons`. A mouse button is pressed over the source's target; a game binding the right one cancels `contextmenu` on its canvas, so the browser's menu does not open on the release. It returns the actions that lost that binding, because what to do when a key already serves another action is a decision for your game, to take it, to warn, or to refuse; the example takes it and says so. `resetToDefaults()` restores every action, or one when named. ```ts /* What the player changed survives a reload. Only the changes are written, so a default the game alters later still reaches a player who never touched it. */ const store = defaultStore(); const SAVED = 'driftengine.examples.input'; actions.load(store, SAVED); ``` `save(store, key)` writes only what the player changed, so an action the game adds or a default it alters in a later version still reaches every player who never touched it. `load(store, key)` applies the record over the defaults; a record that cannot be read leaves the defaults in force and says so once. The store is any `KeyValueStore`: `defaultStore()` is the browser's own storage, `MemoryStore` keeps it in memory for a test, and a packaged game passes its own. A directional action is read two ways. `vector` shortens the keys and the stick to the rim together, so a keyboard diagonal is no faster than a straight line, which is right for walking. `axis` reads each on its own, so two keys held give a full 1 on each, which is right for a throttle and steering. The example's stick switch moves between them. ## Touch `new TouchControls(input, options)` divides the screen. The left part, `splitRatio` of it, is a stick that appears where the thumb lands, `stickRadiusPx` wide with its own `stickDeadzone`; the right part is taps, holds and flicks. It reports signals and never verbs: - `moveX` and `moveY`, the stick, up negative as a gamepad stick's is. - `primaryHeld`, a thumb held on the right, and `consumePrimaryPress()`, a tap, claimed once. A tap fires on release, so `tapMaxMs` is the action's latency, and `fireOnHold` decides whether a still thumb also fires it. - `secondaryHeld`, a downward flick being held, for a slide or a crouch, and `consumeLook(out)`, the drag since you last asked, for a camera. `classifyRightGesture` is the rule that decides whether a drag on the right is a look or a flick, and when in doubt it is a look: a missed flick costs one slide, a look wrongly taken costs the camera for the whole gesture. `gestureMovePx`, `swipeMaxMs` and `swipeDominance` tune it. Call `tick(performance.now())` once a frame, so a hold resolves on time. The stick needs no page elements, and `stickBase` and `stickNub` are where it is drawn when you want it seen. ## From DriftScript `drift/input` reads an action map and a touch screen the host hands a script as `Actions` and `Touch`. `down`, `pressed`, `axisX` and `axisY`, shortened to the rim, and `rawAxisX` and `rawAxisY` read actions; `touchX`, `touchY`, `touchHeld`, `touchTap` and `touchSlide` read touch; `canRumble`, `rumble` and `stopRumble` drive the pad. The puck takes whichever device is pushed furthest: ```drs // The stick, the keys or a thumb on the screen, whichever is pushed furthest: a keyboard and a // touch screen at once never add up to more than one stick. fn steer(puck: mut Puck, actions: Actions, touch: Touch, dt: f32) { var sx = input.axisX(actions, "move") var sz = input.axisY(actions, "move") if puck.raw { sx = input.rawAxisX(actions, "move") sz = input.rawAxisY(actions, "move") } if math.abs(input.touchX(touch)) > math.abs(sx) { sx = input.touchX(touch) } if math.abs(input.touchY(touch)) > math.abs(sz) { sz = input.touchY(touch) } if puck.rest > 0 { puck.rest -= dt } let tapped = input.touchTap(touch) if (input.pressed(actions, "boost") || tapped) && puck.rest <= 0 { puck.boost = 0.5 puck.rest = 1.2 } var push = PUSH if puck.boost > 0 { push = PUSH * 2.6 puck.boost -= dt } puck.braking = input.down(actions, "brake") || input.touchHeld(touch) var drag = DRAG if puck.braking { drag = DRAG * 5 } puck.vx += (sx * push - puck.vx * drag) * dt puck.vz += (sz * push - puck.vz * drag) * dt puck.x += puck.vx * dt puck.z += puck.vz * dt } ``` And rumbles on a hit, where the pad has motors: ```drs // Off the walls and the pillars with some of its speed lost, and the pad, where it has motors, // rumbles with how hard the puck hit. fn bounce(puck: mut Puck, actions: Actions, speed: f32) { let hard = math.min(1, speed / 12) puck.bumps += 1 puck.hit = math.max(puck.hit, hard) if puck.shake && input.canRumble(actions) { input.rumble(actions, 60 + 140 * hard, hard, 0.3 * hard) } } ``` A device is outside the [determinism](https://driftengine.dev/docs/concepts/determinism) boundary, so a `@deterministic` system cannot read one: it is handed what the host sampled at the start of the step. Rebinding stays with the host too, since a controls screen is the game's own interface, and a rebind changes what a script's `Actions` answer without the script knowing: ```ts const script = hostScript(puckScript); interface Puck { x: number; z: number; vx: number; vz: number; boost: number; braking: boolean; bumps: number; hit: number; raw: boolean; shake: boolean; } const puck = exported<() => Puck>(script, 'createPuck')(); type Drive = (puck: Puck, actions: ActionMap, touch: TouchControls, dt: number) => void; if (import.meta.hot) { import.meta.hot.accept('./puck.drs', (next) => { if (next !== undefined) patchModule(script, next as Record, { Puck: [puck] }); }); } ``` --- # Cameras and cinematics Interface. https://driftengine.dev/docs/interface/cameras The camera, a rig that cuts between shots for replays and cinematics, cinematics written as data, keyed camera paths, and re-timing a stretch of play. A game usually has one camera that never surprises anybody, following the player so they can read where they are going. A replay, a trailer or a cutscene wants the opposite: a director, whose whole vocabulary is choosing a new angle at the right moment. The engine has both, and a third thing for moves that have no subject at all, a path flown through the world. The example is a buggy lapping a track with a jump, filmed three ways. A DriftScript director watches it and picks the shot, the page cuts to it. A cinematic written as data plays its shots and its lines. A keyed path flies round the track. The jump switch slows the buggy in the air and pays the time back after it lands, so a lap still takes sixteen seconds. (This chapter runs the `cinematic` example at https://driftengine.dev/docs/interface/cameras.) ## The camera `Camera` is a position, a `yaw` and `pitch` and `roll`, a vertical field of view `fovYDeg`, and `near` and `far` planes. Yaw 0 looks down negative z. `lookAt(x, y, z)` turns it toward a point, `updateMatrices(aspect)` builds its `view`, `projection` and `viewProjection`, and `project` and `rayThrough` go from the world to the screen and back, which is what [picking](https://driftengine.dev/docs/rendering/picking) uses. `adoptView` takes matrices made elsewhere, such as a headset's. ## A camera that cuts ```ts /* The shots, as records the page owns, under the names of the director script's `Shot` variants. */ type ShotName = 'Chase' | 'LowWide' | 'Orbit' | 'Flyby' | 'Overhead' | 'LookAt'; const SHOTS: Readonly> = { Chase: { kind: 'chase', distance: 7, height: 2.2, fovDeg: 62 }, LowWide: { kind: 'lowWide', distance: 9, height: 0.7, fovDeg: 48 }, Orbit: { kind: 'orbit', distance: 8, height: 3, fovDeg: 55, orbitRate: 0.7 }, Flyby: { kind: 'flyby', distance: 10, height: 1.6, fovDeg: 45 }, Overhead: { kind: 'overhead', distance: 14, height: 16, fovDeg: 50 }, LookAt: { kind: 'lookAt', distance: 11, height: 3, fovDeg: 42, anchor: TOWER }, }; /* The rig keeps its boom out of the rocks, so it is given them. */ const ROCKS: Vec3[] = [ [6, 0.8, 3], [-5, 0.8, -4], [9, 0.8, -12], ]; const rocks = new ColliderSet(ROCKS.map(([x, y, z]) => boxCollider(x, y, z, 1, 0.8, 1))); const rig = new CinematicCamera(rocks); /* The rig's own clock, which a cut is stamped with: a shot's age, and an orbit's angle, count from it. */ let rigClock = 0; ``` `CinematicCamera` is a rig that moves a camera onto shots. A shot is a placement rule relative to a subject: `chase` behind its heading, `lowWide` across its line of travel and near the ground, the shot that sells a gap, `orbit` circling it at `orbitRate`, `flyby` from a station it passes, `overhead` above, and `lookAt` framing a fixed `anchor` while keeping the subject in frame. Each takes a `distance`, a `height` and a `fovDeg`, and `holdSec` when the caller knows how long the shot will last, so a move inside it arrives instead of being cut off. `cut(shot, atSec)` changes the shot at once. A cut is instantaneous, because a cut that eases is a swoop and loses the edit's sync with the beat, while the motion inside a shot is smoothed by springs, so footage does not judder when somebody steps through it frame by frame. `atSec` is the shot's start on the rig's own clock, which the time passed to `update` counts. A cut keeps the subject's speed, so the new shot opens already moving with it; `snap()` drops it, for a subject that teleported to a checkpoint. `update(dt, x, y, z, yaw)` moves the rig after the subject each frame, `shotAgeSec` is how long the current shot has held, and `camera` is the camera it moves. The colliders it is built with keep its boom out of walls and rocks. ## Directing from a script ```drs // A take-off cuts at once, across the line of travel and low, the shot that sells a gap; a landing // cuts to an orbit round it. Otherwise a shot holds its time, the tower is framed when the buggy // passes it, and a long shot gives way to the next in turn. Answers the shot to cut to, or `none` // to hold the one on screen. fn direct(director: mut Director, cam: Camera, airborne: bool, nearTower: bool) -> Shot? { let age = camera.shotAge(cam) var want = director.shot if airborne && !director.flying { want = Shot.LowWide } else if !airborne && director.flying { want = Shot.Orbit } else if age < director.least { want = director.shot } else if nearTower && director.shot != Shot.LookAt { want = Shot.LookAt } else if age > director.most { want = next(director.shot) } director.flying = airborne if want == director.shot { return none } director.shot = want director.cuts += 1 return some(want) } ``` `drift/camera` gives a script `shotAge`, how long the current shot has held, and `snap`. A script cannot build a shot's record, so `cut` is not bound: the page keeps each shot's record under the name of a variant of the director's `Shot` enum, the director answers with the variant to cut to, and the page makes the cut. ```ts const script = hostScript(directorScript); /* A variant reaches the page as `{ tag }`, and an option as `{ tag: 'some', value }` or `none`. */ interface Director { shot: { tag: ShotName }; cuts: number; } const director = exported<() => Director>(script, 'createDirector')(); type Direct = ( director: Director, camera: CinematicCamera, airborne: boolean, nearTower: boolean, ) => { tag: 'none' } | { tag: 'some'; value: { tag: ShotName } }; if (import.meta.hot) { import.meta.hot.accept('./director.drs', (next) => { if (next !== undefined) { patchModule(script, next as Record, { Director: [director] }); } }); } ``` ```ts caption = ''; if (mode === 'director') { const shot = exported(script, 'direct')(director, rig, airborne, nearTower); if (shot.tag === 'some') rig.cut(SHOTS[shot.value.tag], rigClock); } else if (mode === 'timeline') { player.update(dt); if (player.shotChanged && player.shot !== null) rig.cut(player.shot, rigClock); caption = player.line?.text ?? ''; if (player.finished) player.reset(); } if (mode === 'path') { pathSec += dt; sampleCameraPath(flight, pathSec, along); camera.position[0] = along.eye[0]; camera.position[1] = along.eye[1]; camera.position[2] = along.eye[2]; camera.lookAt(along.target[0], along.target[1], along.target[2]); camera.fovYDeg = along.fovDeg; } else { rigClock += dt; rig.update(dt, position[0], position[1], position[2], yaw); camera.position[0] = rig.camera.position[0] ?? 0; camera.position[1] = rig.camera.position[1] ?? 0; camera.position[2] = rig.camera.position[2] ?? 0; camera.yaw = rig.camera.yaw; camera.pitch = rig.camera.pitch; camera.fovYDeg = rig.camera.fovYDeg; } ``` ## A cinematic as data ```ts /* A cinematic written as data: when the camera cuts, a shot that moves while it holds, and the lines shown under the picture. Checked when it is defined, so a malformed one fails on load. */ const TRAILER = defineCinematic('trailer', { durationSec: 16, shots: [ { atSec: 0, camera: { kind: 'overhead', distance: 16, height: 18, fovDeg: 48 } }, { atSec: 3.5, camera: { kind: 'chase', distance: 6, height: 1.8, fovDeg: 64 } }, { atSec: 7, camera: [ { atSec: 0, camera: { kind: 'lookAt', distance: 14, height: 2, fovDeg: 40, anchor: TOWER }, }, { atSec: 4, camera: { kind: 'lookAt', distance: 8, height: 5, fovDeg: 50, anchor: TOWER } }, ], }, { atSec: 11.5, camera: { kind: 'flyby', distance: 9, height: 1.2, fovDeg: 44 } }, ], lines: [ { atSec: 0.5, holdSec: 2.5, text: 'ONE TRACK', look: 'title' }, { atSec: 4, holdSec: 2.5, text: 'ONE JUMP', look: 'title' }, { atSec: 8, holdSec: 3, text: 'EVERY LAP THE SAME LENGTH', look: 'title' }, { atSec: 12, holdSec: 3, text: 'CUT ON THE MOMENT', look: 'title' }, ], }); const player = new CinematicPlayer(TRAILER, 'trailer'); ``` A cinematic is a file, never a function, so a new trailer or a different cut of the same footage is a change of data. `defineCinematic(name, script)` checks it when it is defined and throws naming the entry and the times, for two lines up at once, an entry out of order, or a keyframe past the end of its shot, so a malformed one fails on load and is never played half right. A script is a duration, its `shots` and its `lines`. A shot cuts at `atSec` to a fixed placement, or to a list of `CameraKeyframe`s it moves through while it holds; keyframes are a move and never a second cut. A line is text shown from `atSec` for `holdSec`, with a `look` your presentation resolves. `CinematicPlayer` plays it: `update(dt)` each frame, `shot` and `shotChanged` for the camera, `line` for what is up, `timeSec` and `finished`, and `skip()` and `reset()`. Everything is derived from accumulated time, so a cinematic plays the same at any frame rate. ## A path through the world ```ts /* A move through the world with no subject: an eye and a point it looks at, keyed in time and passed through smoothly, looping round the track. */ const flight = createCameraPath( [ { atSec: 0, eye: [22, 6, 16], target: [0, 1, 0], fovDeg: 50 }, { atSec: 5, eye: [-8, 3, 14], target: [-15, 1, 0], fovDeg: 45 }, { atSec: 10, eye: [-24, 9, -6], target: [-14, 1, 2], fovDeg: 40 }, { atSec: 15, eye: [0, 20, -22], target: [0, 0, 0], fovDeg: 55 }, ], { loop: true, periodSec: 20 }, ); const along = createCameraPathSample(); ``` A walk through a building has no subject to frame: it is a route and a gaze. `createCameraPath(keys, options)` takes keys of an `eye`, a `target` and a `fovDeg` at a time, and passes through every key with no kink: a cubic through each, Catmull-Rom with the keys' own times as its knots, so an evenly timed straight run is a constant velocity. The eye and the target are interpolated apart, so a pan and a dolly are written as what they are. A looped path wraps back through its first key after `periodSec`. `sampleCameraPath(path, timeSec, out)` fills a sample made once with `createCameraPathSample()`, allocating nothing. ## Re-timing a stretch ```ts /* The stretch of a lap the buggy spends over the jump, found once, and a curve that re-times it: slower in the air, quicker after, the same length in all. */ function lapSecAt(angle: number): number { let low = 0; let high = LAP / 2 + 2; for (let step = 0; step < 40; step += 1) { const mid = (low + high) / 2; if (angleAt(mid) < angle) low = mid; else high = mid; } return low; } const flightStart = lapSecAt(JUMP[0] - RAMP); const flightEnd = lapSecAt(JUMP[1] + RAMP); const slowMotion = timeCurve('ramp', flightEnd - flightStart, { amount: 0.75 }); let retimed = flag('time', 'real') === 'slow'; /** Where in its lap the buggy is, from the lap's clock, through the curve where it applies. */ function sourceSec(lapClock: number): number { if (!retimed || lapClock < flightStart || lapClock > flightEnd) return lapClock; return flightStart + curveOffsetSec(slowMotion, lapClock - flightStart); } ``` A `TimeCurve` re-times a segment: given a time into it, how far the source has moved. `timeCurve(kind, durationSec, options)` makes one, and `curveOffsetSec(curve, localSec)` reads it. `hold` freezes part of the segment, `ramp` slows and then speeds, `stutter` freezes and catches up in steps of `stepSec`, and `reverse` runs part of it backwards, as far as the `reversibleSec` the caller can actually rewind. `amount` is how much of the segment the effect takes, at most `MAX_TIME_CURVE_AMOUNT`, and every kind is speed-neutral: whatever it takes it pays back, so `curveSpanSec` is always the segment's own length and a re-timed clip is as long as the one asked for. `linearCurve` is a segment played straight. One curve drives a fixed-step simulation, a recorded stream or a video alike. --- # Sprites and tilemaps Interface. https://driftengine.dev/docs/interface/sprites The 2D layer: textured quads batched in the order drawn, sheets cut into frames, tilemaps that cost the view, and a camera for a 2D world. `@driftengine/ui2d` is the engine's 2D layer: quads with a texture on them, batched, drawn in the order you submitted them. It draws a whole 2D game, a heads-up display over a 3D one, or the interface tree in the [next chapter](https://driftengine.dev/docs/interface/interface), and it is 10.5 KB gzipped on top of core. The example is a garden, all of it one sprite pass over one sheet painted when the page loads: a tilemap, a gardener walking it, and flowers to pick. `garden.drs` walks the gardener, keeps it out of the pond, picks a flower by rewriting its tile, and draws both. The switches zoom the camera, change how the sheet is filtered, and repaint it at dusk. (This chapter runs the `sprites` example at https://driftengine.dev/docs/interface/sprites.) ## A sprite pass ```ts /* One pass of sprites, drawn wherever in the frame it is asked for, over one sheet. A sheet of pixel art is filtered nearest, so its texels stay square at any zoom. */ const pass = createSpritePass({ capacity: 4096, slots: 1, label: 'garden' }); /** The ground behind the tiles at each hour, picked by eye and so stated through `srgbColor`. */ const DUSK_CLEAR = srgbColor(0.08, 0.1, 0.14); const DAY_CLEAR = srgbColor(0.3, 0.45, 0.25); const handle = renderer.registerPass(pass); const painted = new OffscreenCanvas(SHEET_WIDTH, SHEET_HEIGHT); let palette = flag('light', 'day') === 'dusk' ? DUSK : DAY; let filter: 'nearest' | 'linear' = flag('filter', 'nearest') === 'linear' ? 'linear' : 'nearest'; function upload(): void { pass.setTexture(0, paintSheet(painted, palette), { filter }); } upload(); const sheet = namedSheet(0, SHEET_WIDTH, SHEET_HEIGHT, ENTRIES); ``` `createSpritePass({ capacity, slots, label })` makes the pass, and `renderer.registerPass(pass)` hands it to the renderer. It draws through that seam rather than through a verb on the renderer, which is what lets it be a package a game that never draws a sprite does not carry, and `renderer.drawPass(handle)` draws it wherever in the frame you call it: after the scene for a heads-up display, or alone for a 2D game. `setTexture(slot, source, options)` uploads a picture to a slot, from an `ImageBitmap`, a canvas or an `OffscreenCanvas`, and `white` is a slot of its own holding one white texel, so a solid rectangle needs no sheet. An atlas painted a picture at a time does not have to go up whole each time. `updateTexture(slot, source, region)` copies one rectangle of the image into the slot's texture at the same place and keeps the rest, so an upload grows with what was painted rather than with the atlas; the slot keeps the options it was given, and a slot that is empty or was made from an image of another size gets the whole image instead. **Paint such an atlas into a 2D context made with `willReadFrequently: true`.** That keeps the canvas in memory, and on WebGPU a canvas drawn on the GPU is transferred whole before any part of it is copied: one 256 by 64 rectangle of a 5120-texel atlas measured 66 ms that way and 0.4 ms from memory, against 120 ms for the whole atlas. WebGL2 copies a rectangle quickly from either. What the option gives up is painting on the GPU, which matters for a canvas redrawn whole every frame and not for an atlas painted a picture at a time. Each frame: `reset()`, `setTransform(affine)`, then draw into `batch`. There is no depth, so **the order sprites were submitted in is the order they are layered**. Consecutive sprites on one slot are one run and one draw call; a change of slot starts a run, and going back to the first starts another rather than reordering the picture. A batch has a fixed `capacity` and never grows: past it, a draw counts into `dropped` instead of allocating in the frame. `drawSprite(batch, slot, placement, frame, tint)` places one. The placement is a corner, a width and a height, and an optional `rotation`; a negative width mirrors it, which is a character facing the other way. The frame is the part of the texture it shows, or the whole texture for null, and the tint multiplies its colour. ## Two spaces `screenToNdc(width, height, out)` is CSS pixels from the top-left, the space of an overlay: y counts down, and a placement's corner is its top-left. `worldToNdc(camera, width, height, out)` is a 2D world seen through a `Camera2D`: y counts up, a placement's corner is its bottom-left, and a platform above a floor has a larger y. A camera is where it looks, `x` and `y`, how far in, `zoom` in pixels per world unit, and `rotation`. A picture keeps its top up in both: a frame's top row is drawn at the top of the sprite whichever way y counts. Both functions fill an affine made once with `createAffine2D()`. ## Sheets A sheet is the rectangles of one texture that each hold a picture. `gridSheet(slot, width, height, cellWidth, cellHeight)` cuts a texture into equal cells, row by row, and `namedSheet(slot, width, height, entries)` takes whatever rectangles a packer put where, by name. `frameOf(sheet, name)` is a frame's index, and `sheetFrame(sheet, index, out)` writes its texture rectangle into a frame made once with `createSpriteFrame()`, so drawing one allocates nothing. `sheetFrameWidth` and `sheetFrameHeight` are its size in texels. A cell that would run off the texture's edge is not cut, and a frame index the sheet does not have draws the whole texture: nothing may throw in the frame loop, and a whole atlas where one picture should be is impossible to miss. ## Tilemaps ```ts /* The garden, a tile a world unit: grass and clover, a path, a pond, a fenced patch of soil, some stones, and flowers scattered over the grass. Row 0 is the bottom, because the world's y is up. */ const COLUMNS = 48; const ROWS = 36; const map = createTilemap(COLUMNS, ROWS, 1, 1); const tileOf = (name: string): number => frameOf(sheet, name); let seed = 7; const random = (): number => { seed = (Math.imul(seed, 1103515245) + 12345) >>> 0; return seed / 0x100000000; }; for (let row = 0; row < ROWS; row += 1) { for (let column = 0; column < COLUMNS; column += 1) { const pond = ((column - 34) / 7) ** 2 + ((row - 24) / 5) ** 2 < 1; const patch = column >= 8 && column <= 17 && row >= 6 && row <= 13; const edge = patch && (column === 8 || column === 17 || row === 6 || row === 13); const path = Math.abs(row - (17 + Math.sin(column / 5) * 3)) < 1; let name = random() < 0.2 ? 'clover' : 'grass'; if (path) name = 'path'; if (pond) name = 'water'; if (patch) name = edge && !(row === 13 && column === 12) ? 'fence' : 'soil'; if (name === 'grass' && random() < 0.05) name = 'flower'; if (name === 'grass' && random() < 0.015) name = 'stone'; setTile(map, column, row, tileOf(name)); } } const flowers = (): number => { let count = 0; for (const tile of map.tiles) if (tile === tileOf('flower')) count += 1; return count; }; const planted = flowers(); ``` `createTilemap(columns, rows, tileWidth, tileHeight)` is a grid of frames of one sheet, from `map.x` and `map.y`. `setTile` and `tileAt` write and read a cell, and `TILE_EMPTY` is a cell with nothing in it. `drawTilemap(batch, map, sheet, view, tint)` draws the cells the view rectangle covers and no others: the span is arithmetic on four numbers, so a million-cell map costs the few hundred on screen. Which way the rows run is the space's business: row 0 is the top row on the screen and the bottom row of a world. ## Filtering `filter` is `nearest` by default, because a sheet is usually pixel art and filtering is what makes pixel art look smeared. Switch the example to `linear` and every tile shows a seam: a texel on a cell's edge is blended with the cell beside it on the sheet. `colorSpace` is `srgb` by default, which is right for anything painted to be looked at. A sheet of glyphs drawn smaller than it was made wants `mipmap: true`, and then the cells want padding, since a smaller level blends neighbours the packer put side by side. ## From DriftScript `drift/2d` is imported under a name, because a module's namespace is the last part of its path and `2d` is not a name a script can write: `import { tilemap } from "drift/2d" as sprites`. It has `sprite`, `tinted` and `frame` to draw, `named` and `frames` to read a sheet, `tilemap`, `tile`, `setTile`, `columns` and `rows` for a map, and `count` and `dropped` for the batch, over the `SpriteBatch`, `SpriteSheet` and `Tilemap` the host hands in. Reading a sheet or a cell is a read of the scene a `@deterministic` system may make, and drawing is not. ```drs // Steered by the move action, an axis at a time, so it slides along a fence it walks into. fn walk(g: mut Gardener, actions: Actions, map: Tilemap, sheet: SpriteSheet, dt: f32) { let dx = input.axisX(actions, "move") // A stick's up is negative, and the garden's is positive. let dy = -input.axisY(actions, "move") if math.abs(dx) > math.abs(dy) { if dx > 0 { g.facing = Facing.Right } else { g.facing = Facing.Left } } else if dy > 0 { g.facing = Facing.Up } else if dy < 0 { g.facing = Facing.Down } let nx = g.x + dx * g.speed * dt let ny = g.y + dy * g.speed * dt if open(map, sheet, nx, g.y) { g.x = nx } if open(map, sheet, g.x, ny) { g.y = ny } g.stride += (math.abs(dx) + math.abs(dy)) * g.speed * dt pick(g, map, sheet) } ``` ```drs // A flower underfoot is picked: its tile becomes plain grass, and the count goes up. fn pick(g: mut Gardener, map: Tilemap, sheet: SpriteSheet) { let column = cell(g.x) let row = cell(g.y) if sprites.tile(map, column, row) == sprites.named(sheet, "flower") { sprites.setTile(map, column, row, sprites.named(sheet, "grass")) g.picked += 1 } } ``` ```drs // The tilemap, only what the view holds, then the gardener over it: its row by the way it faces, // and one of two steps by how far it has walked. fn draw(g: Gardener, batch: SpriteBatch, map: Tilemap, sheet: SpriteSheet, viewX: f32, viewY: f32, viewW: f32, viewH: f32) { sprites.tilemap(batch, map, sheet, viewX, viewY, viewW, viewH) // Three steps a tile, alternating feet. let pace = g.stride * 3 var step: i32 = 0 if pace - math.floor(pace / 2) * 2 >= 1 { step = 1 } let first = sprites.named(sheet, "down0") sprites.frame(batch, sheet, first + row(g.facing) + step, g.x - 0.5, g.y - 0.15, 1, 1) } ``` The page hosts the script with the actions it reads, and each frame works out the view the camera sees and asks the script to draw it: ```ts const input = new InputSource(canvas, ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']); const actions = new ActionMap(input, { move: { stick: 'left', up: ['KeyW', 'ArrowUp'], down: ['KeyS', 'ArrowDown'], left: ['KeyA', 'ArrowLeft'], right: ['KeyD', 'ArrowRight'], }, }); const script = hostScript(gardenScript); interface Gardener { x: number; y: number; picked: number; } const gardener = exported<() => Gardener>(script, 'createGardener')(); type Walk = ( gardener: Gardener, actions: ActionMap, map: Tilemap, sheet: SpriteSheet, dt: number, ) => void; type Draw = ( gardener: Gardener, batch: SpriteBatch, map: Tilemap, sheet: SpriteSheet, x: number, y: number, w: number, h: number, ) => void; if (import.meta.hot) { import.meta.hot.accept('./garden.drs', (next) => { if (next !== undefined) { patchModule(script, next as Record, { Gardener: [gardener] }); } }); } ``` ```ts /* The camera follows the gardener, and the view it sees, in tiles, is what the tilemap draws. */ const width = canvas.clientWidth; const height = canvas.clientHeight; const seenW = width / zoom; const seenH = height / zoom; /* Kept inside the garden, so its edge is never in view. */ view.x = Math.min(Math.max(gardener.x, seenW / 2), COLUMNS - seenW / 2); view.y = Math.min(Math.max(gardener.y, seenH / 2), ROWS - seenH / 2); view.zoom = zoom; pass.reset(); pass.setTransform(worldToNdc(view, width, height, affine)); exported(script, 'draw')( gardener, pass.batch, map, sheet, view.x - seenW / 2, view.y - seenH / 2, seenW, seenH, ); renderer.beginFrame(palette === DUSK ? DUSK_CLEAR : DAY_CLEAR); renderer.drawPass(handle); ``` --- # Interfaces Interface. https://driftengine.dev/docs/interface/interface Menus and heads-up displays as a retained tree: layout without coordinates, focus, routing, clipping and scrolling, themes, text, and scripts. A menu, a heads-up display or a settings screen in `@driftengine/ui2d` is a tree of nodes built once and changed as the game runs. The tree is laid out, pointed at and drawn by the engine, as one [sprite pass](https://driftengine.dev/docs/interface/sprites), and the text on it is drawn by the pixel font or by distance-field text, whichever the game uses. The example is a pause menu and an options screen over a scene that keeps running behind them. `menu.drs` routes the pointer and the keys to the tree, answers what was activated and paints each button from its own state. Options opens a second panel whose toggles change the scene, and its list scrolls inside its own box. The mouse, the keyboard and a gamepad all reach it, and the switches move the menu and change its theme. (This chapter runs the `interface` example at https://driftengine.dev/docs/interface/interface.) ## A tree of nodes ```ts /* The interface as nodes: a root that fills the screen, the pause menu, and the options panel with its toggles and a list that clips and scrolls. Sizes are numbers, `fit` or `grow`; nothing is placed by hand. */ const BUTTON: UiNodeOptions = { width: 260, height: 34, interactive: true, focusable: true }; const root = createUiNode({ direction: 'column', width: 'grow', height: 'grow', justify: 'center', padding: 40, }); const add = (parent: UiNode, options: UiNodeOptions): UiNode => addUiChild(parent, createUiNode(options)); const menu = add(root, { direction: 'column', padding: 18, gap: 8, name: 'menu', background: [0, 0, 0, 1], }); add(menu, { width: 260, height: 36, text: 'PAUSED', name: 'title' }); add(menu, { ...BUTTON, text: 'RESUME', name: 'resume' }); add(menu, { ...BUTTON, text: 'OPTIONS', name: 'options' }); add(menu, { ...BUTTON, text: 'RESTART', name: 'restart' }); const options = add(root, { direction: 'column', padding: 18, gap: 8, name: 'optionsPanel', hidden: true, background: [0, 0, 0, 1], }); add(options, { width: 260, height: 36, text: 'OPTIONS', name: 'optionsTitle' }); add(options, { ...BUTTON, text: 'SPIN ON', name: 'spin' }); add(options, { ...BUTTON, text: 'SHADOWS ON', name: 'shadows' }); const help = add(options, { direction: 'column', width: 260, height: 112, padding: 8, gap: 6, clip: true, name: 'help', background: [0, 0, 0, 1], }); for (const line of [ 'THE WHEEL SCROLLS IT', 'TAB OR ARROWS MOVE', 'ENTER OR SPACE PRESS', 'ESCAPE GOES BACK', 'A PAD: D-PAD AND A', 'START PAUSES', 'THE LIST CLIPS ROWS', 'AND SCROLLS IN PLACE', ]) { add(help, { width: 'grow', height: 16, text: line }); } add(options, { ...BUTTON, text: 'BACK', name: 'back' }); ``` `createUiNode(options)` makes a node and `addUiChild(parent, child)` hangs it under another; `removeUiChild` takes one off and `uiNodeNamed(root, name)` finds one. A node has a `direction`, row or column, for its children, a `width` and `height`, `padding` and a `gap` between children, and `align` and `justify` for where they sit across and along. It can be `hidden`, `interactive` to take the pointer, `focusable` to take the keyboard, and carry a `background` colour, an image from a `texture` slot and `frame`, a `tint`, and `text`. `absolute` with `x` and `y` takes a node out of the flow, for a badge in a corner. A size is one of three things: a number of CSS pixels, `fit`, the size of what is inside, or `grow`, a share of what the parent has left. There are no percentages, because a percentage of a parent sized to fit its children is a cycle. `layoutUiTree(root, x, y, width, height)` lays the whole tree out in two passes, measuring every node bottom-up and then placing it top-down, into the `rect` each node already owns, so it allocates nothing and can run every frame. The box it is given is what is available, so the same call lays out a full-screen menu and a tooltip. ## Pointing, focus and keys `routeUiPointer(input, root, x, y, down)` hit tests the tree, last drawn first so it agrees with the picture, sets `hovered` and `pressed` on the nodes, and answers the node activated, which is a press and a release on the same node, so somebody who pressed the wrong button can slide off it. A node that is not interactive does not block what is behind it: a backdrop that swallowed clicks would make every button under it dead. `routeUiKey(input, root, key, shift)` moves the focus with Tab and activates with Enter and Space, and leaves every other key to you. Focus follows tree order, and `uiFocusNext`, `uiFocusPrevious`, `uiFocusOrder` and `setUiFocus` move it directly. `createUiInput()` is the routing state and `uiHitTest` the bare hit test. Dragging and pointer capture, so a slider keeps the pointer when it leaves the track, are `capturePointer`, `pointerTarget`, `beginDrag`, `dropTarget` and `endDrag`. ## Clipping and scrolling A node made with `clip: true` bounds its descendants: they draw and take the pointer only inside it. Its `scrollX` and `scrollY` move them under it at layout, so hit testing and focus need no notion of scrolling, and `routeScrollWheel(root, x, y, dx, dy)` scrolls the clipping node under the pointer, `scrollBy` and `clampScroll` within its `scrollExtent`. `clipRectFor(root, node, out)` answers how much of a node a clip leaves. A list of thousands of rows builds only the ones in view: `visibleRange` and `visibleRangeVariable` give the window of rows a scroll position shows. ## Themes ```ts /* Colours by name, packed as 0xRRGGBBAA. The light theme is the dark one with four overrides. */ const DARK = createTheme({ panel: 0x14161dee, well: 0x0b0c10ff, text: 0xe6e8eeff, title: 0xf0b45cff, }); const LIGHT = deriveTheme(DARK, { panel: 0xf2f3f6ee, well: 0xdfe2e8ff, text: 0x1a1c22ff, title: 0xb4602aff, }); let theme = flag('theme', 'dark') === 'light' ? LIGHT : DARK; const textColour = new Float32Array(4); let bodyStyle: TextStyle = DEFAULT_TEXT_STYLE; let titleStyle: TextStyle = DEFAULT_TEXT_STYLE; /* Written into the nodes' own colours, and the label styles built here, once a change of theme. */ function applyTheme(): void { themeRgba(theme, 'panel', 0x000000ff, menu.background as Float32Array); themeRgba(theme, 'panel', 0x000000ff, options.background as Float32Array); themeRgba(theme, 'well', 0x000000ff, help.background as Float32Array); themeRgba(theme, 'text', 0xffffffff, textColour); bodyStyle = { ...DEFAULT_TEXT_STYLE, cellSize: 2, color: [textColour[0] ?? 1, textColour[1] ?? 1, textColour[2] ?? 1], }; themeRgba(theme, 'title', 0xffffffff, textColour); titleStyle = { ...DEFAULT_TEXT_STYLE, cellSize: 3, color: [textColour[0] ?? 1, textColour[1] ?? 1, textColour[2] ?? 1], }; } applyTheme(); ``` A theme is colours and sizes by name. `createTheme(values)` makes one and `deriveTheme(base, overrides)` another from it, flattened when it is derived so a lookup is one property access. `themeColour` and `themeSize` read a token, and `themeRgba` unpacks a colour token straight into a node's `background` or `tint`, decoded from the sRGB a hex colour is written in to the linear light a node holds, so a token comes out on screen exactly as written. The example's light theme is the dark one with four colours changed. ## Drawing it ```ts /* One sprite pass for the panels and buttons, and the pixel font over them: the tree says where each label goes and how much of it a clip leaves, and the page draws it. */ const pass = createSpritePass({ capacity: 256, slots: 1, label: 'interface' }); const handle = renderer.registerPass(pass); const affine = createAffine2D(); const labels = new Map(); const queued: UiNode[] = []; const sink = { content(node: UiNode, visible: UiRect): void { /* A label in a row a clip has cut is left out, rather than drawn over the list's edge. */ if (visible.h < node.rect.h) return; queued.push(node); }, }; function drawLabels(width: number, height: number, time: number): void { for (const node of queued) { let label = labels.get(node); if (label === undefined) { label = renderer.createText(); labels.set(node, label); } renderer.setText(label, node.text); const big = node.name === 'title' || node.name === 'optionsTitle'; const style = big ? titleStyle : bodyStyle; const cell = big ? 3 : 2; const x = node.rect.x + (node.interactive ? 12 : 4); const baseline = node.rect.y + node.rect.h / 2 + (cell * 7) / 2; renderer.drawText(label, width, height, x, baseline, style, time); } queued.length = 0; } ``` `drawUiTree(batch, root, white, sink)` draws the tree into a sprite batch, parents before children so a child lands on top, a background on the white slot and an image over it. Under a clip each quad is cut to what the clip leaves. Text is yours: the sink is handed every node with text, at its laid-out box and with the part of it visible, and draws it with core's `drawText` or `drawSdfText`. The example leaves out a label its clip has cut, rather than drawing it over the list's edge. Beyond the tree there is more for an interface to need. `sliceInto` cuts a panel image into nine cells so its corners keep their size as it stretches. `createTextModel` is an editable line of text, with `insertText`, `deleteBackward`, `moveCaret`, `selectAll` and the rest, a caret that steps over characters made of two code units, and a `TextHost` for composition and the clipboard where there is a page to have them. `runsFor` splits text into styled runs. `layerOrder` orders a tree by inherited layers, for a dropdown that must cover the panel its control sits in. `createDirtyTracker` and `diffTree` find the region that changed since the last frame, a node that vanished included, so an interface can repaint only that. And `a11yTree` produces the tree's accessibility nodes for an `A11yHost` to publish to a screen reader. ## From DriftScript `drift/ui` reads and changes a tree the host hands a script as a `UiTree`, addressing its nodes by the names they were built with. `layout` lays it out and `draw` draws it; `has`, `left`, `top`, `width`, `height` and `visible` read a node; `show`, `setText` and `tint` change one; `hovered`, `pressed` and `focused` are its state; and `point`, `key`, `activated` and `focus` route input to it. The menu routes the frame's pointer and key, and answers what each activated: ```drs // Lay the tree out in the space it has, then give it the pointer and the key pressed this frame, // and answer whatever either of them activated. Arrow keys move the focus as Tab does. fn update(menu: mut Menu, tree: UiTree, width: f32, height: f32, px: f32, py: f32, down: bool, pressedKey: String) { ui.layout(tree, 0, 0, width, height) if pressedKey == "Escape" { if menu.inOptions { leaveOptions(menu, tree) } else { toggle(menu, tree) } } if !menu.open { return } ui.point(tree, px, py, down) respond(menu, tree) if pressedKey == "ArrowDown" { ui.key(tree, "Tab", false) } else if pressedKey == "ArrowUp" { ui.key(tree, "Tab", true) } else if pressedKey == "Enter" || pressedKey == " " || pressedKey == "Tab" { ui.key(tree, pressedKey, false) } respond(menu, tree) paint(menu, tree, "resume") paint(menu, tree, "options") paint(menu, tree, "restart") paint(menu, tree, "spin") paint(menu, tree, "shadows") paint(menu, tree, "back") } ``` ```drs fn respond(menu: mut Menu, tree: UiTree) { if ui.activated(tree, "resume") { toggle(menu, tree) } if ui.activated(tree, "options") { menu.inOptions = true ui.show(tree, "menu", false) ui.show(tree, "optionsPanel", true) ui.focus(tree, "spin") } if ui.activated(tree, "back") { leaveOptions(menu, tree) } if ui.activated(tree, "restart") { menu.restarts += 1 } if ui.activated(tree, "spin") { menu.spin = !menu.spin label(tree, "spin", menu.spin, "SPIN ON", "SPIN OFF") } if ui.activated(tree, "shadows") { menu.shadows = !menu.shadows label(tree, "shadows", menu.shadows, "SHADOWS ON", "SHADOWS OFF") } } ``` A button paints itself from its own state: ```drs // A button paints itself from its own state: held down, under the pointer or holding the keyboard, // or at rest, in the colours of the theme the page is showing. fn paint(menu: Menu, tree: UiTree, name: String) { if ui.pressed(tree, name) { ui.tint(tree, name, 0.9, 0.5, 0.25, 1) } else if ui.hovered(tree, name) || ui.focused(tree, name) { if menu.light { ui.tint(tree, name, 0.95, 0.75, 0.45, 1) } else { ui.tint(tree, name, 0.85, 0.55, 0.3, 1) } } else if menu.light { ui.tint(tree, name, 0.86, 0.87, 0.9, 1) } else { ui.tint(tree, name, 0.17, 0.19, 0.24, 1) } } ``` Reading a laid-out box is a read of the scene, inside the fixed step; whether a node is hovered or pressed is input, outside it, so a `@deterministic` system cannot ask where the pointer is. The page collects the pointer, the wheel, one key a frame and a pad's buttons, and hands them over: ```ts /* The pointer in CSS pixels, the wheel, the one key pressed this frame, and a pad's buttons named as the keys they stand for. The script is handed all of it and routes it to the tree. */ const pointer = { x: -1, y: -1, down: false }; let pressedKey = ''; const ROUTED = new Set(['Escape', 'ArrowDown', 'ArrowUp', 'Enter', ' ', 'Tab']); canvas.addEventListener('pointermove', (event) => { pointer.x = event.offsetX; pointer.y = event.offsetY; }); canvas.addEventListener('pointerdown', () => { pointer.down = true; }); addEventListener('pointerup', () => { pointer.down = false; }); canvas.addEventListener( 'wheel', (event) => { event.preventDefault(); routeScrollWheel(root, event.offsetX, event.offsetY, event.deltaX, event.deltaY); }, { passive: false }, ); addEventListener('keydown', (event) => { if (!ROUTED.has(event.key)) return; event.preventDefault(); pressedKey = event.key; }); const input = new InputSource(canvas); function padKey(): string { const pad = input.pad(0); if (pad === null) return ''; if (pad.pressed('dpadDown')) return 'ArrowDown'; if (pad.pressed('dpadUp')) return 'ArrowUp'; if (pad.pressed('faceDown')) return 'Enter'; if (pad.pressed('faceRight') || pad.pressed('start')) return 'Escape'; return ''; } ``` ```ts const script = hostScript(menuScript); interface Menu { open: boolean; spin: boolean; shadows: boolean; light: boolean; restarts: number; } const state = exported<() => Menu>(script, 'createMenu')(); state.light = theme === LIGHT; exported<(tree: UiNode) => void>(script, 'begin')(root); type Update = ( menu: Menu, tree: UiNode, width: number, height: number, x: number, y: number, down: boolean, key: string, ) => void; if (import.meta.hot) { import.meta.hot.accept('./menu.drs', (next) => { if (next !== undefined) patchModule(script, next as Record, { Menu: [state] }); }); } ``` ```ts const key = pressedKey !== '' ? pressedKey : padKey(); pressedKey = ''; exported(script, 'update')( state, root, width, height, pointer.x, pointer.y, pointer.down, key, ); pass.reset(); pass.setTransform(screenToNdc(width, height, affine)); drawUiTree(pass.batch, root, pass.white, sink); ``` --- # XR Interface. https://driftengine.dev/docs/interface/xr Asking a browser what it can present, entering a WebXR session, and reading the head, controllers and hands each frame. Drawing into a headset is not built yet. `@driftengine/xr` is the engine's WebXR. It asks a browser what it can present, enters a session, and reads where the head is, what each controller is doing and where every joint of a tracked hand is, every frame. It is a package of its own, so a game that never enters a session carries none of it. One part is missing, and it is the part a headset needs most. The renderer draws into its canvas and into nothing else, so a session can be entered and read, and nothing appears inside the headset. Everything on this page works against a real session; drawing into one is recorded in the engine's `docs/IMPROVEMENTS.md`, and it is the next thing XR needs. The example is a headset seen from across a room: its head, its two controllers and the joints of its left hand, read every frame from a session, and a lamp over the table that the right trigger turns up. The session is a simulated one, because almost nobody reading this has a headset on, and what your own browser answers is written under the readout. A DriftScript module reads the trigger and the hand. The strip pulls the trigger, hides a fingertip from the tracker, takes the headset off, or asks your browser for a real session. (This chapter runs the `xr` example at https://driftengine.dev/docs/interface/xr.) ## Asking the browser ```ts /* Asked by doing: a context of its own is offered to be made XR compatible, which is the step that fails on a machine with no headset attached even where every mode reports supported. */ const here = await probeXrSupport(document.createElement('canvas').getContext('webgl2')); function said(support: XrSupport): string { if (!support.present) return 'this browser has no WebXR'; const modes = [ support.immersiveVr ? 'immersive-vr' : '', support.immersiveAr ? 'immersive-ar' : '', support.inline ? 'inline' : '', ].filter((mode) => mode !== ''); const reason = support.reason.charAt(0).toUpperCase() + support.reason.slice(1); return `${modes.length === 0 ? 'no session mode' : modes.join(', ')}. ${reason}`; } ``` `probeXrSupport(context)` answers with `present`, whether the browser has WebXR at all; `immersiveVr`, `immersiveAr` and `inline` for the three session modes; `compatible`; and `reason`, a whole sentence whenever something is missing. It asks by doing. A browser's own answer about a mode is a promise about the mode only: on a machine with no headset it can call `inline` supported, start the session and grant a reference space, and then refuse to make the rendering context XR compatible. Without a compatible context there is no layer and so no frame, which is why the probe offers the context it is given and reports what happened. Offer the context the game draws with; the example offers one of its own, since it draws nothing into a session. `bestMode(support)` picks the mode to ask for, immersive first. ## Entering a session ```ts /* A real session, from a click: `requestSession` needs a user gesture. The answer is a whole sentence either way, and a session that does start is ended, since nothing can be drawn into it. */ let real = ''; async function tryReal(): Promise { real = 'asking…'; tell(); const entered = await enterXr({ sources: { gl: document.createElement('canvas').getContext('webgl2', { xrCompatible: true }) }, }); if (!entered.ok) { real = entered.reason; } else { real = `entered on ${entered.run.referenceSpaceType} through ${entered.run.backend}, and ended, since nothing draws into it yet.`; await entered.run.end(); } tell(); } /* What this browser answered, and what a real session said when one was asked for. */ function tell(): void { if (answer === null) return; answer.textContent = `This browser: ${said(here)}` + (real === '' ? '' : ` A real session: ${real}`); } tell(); ``` `enterXr` requests a session, builds the layer the session composites, and asks for a reference space. It answers with `ok` and a `run`, or with `ok: false` and a `reason`. Call it from a click: a browser grants a session only to a user gesture, and refuses one otherwise with the same error a machine with no headset gives, which the reason says. The options are the `mode`, `immersive-vr` unless asked otherwise; `optionalFeatures`, such as `hand-tracking`; the `sources` a layer is built from, a WebGL2 context as `gl` or a GPU device as `device`; and a `system` to use in place of the browser's. The layer is chosen from what the session offers. Where the browser has a WebGPU binding and a device was offered it is a projection layer, and otherwise a WebGL layer; a WebGPU layer that cannot be built falls back to WebGL2 and says so in `run.layer.reason`. The reference space is the first of `local-floor`, `local` and `viewer` that the session grants, and `run.referenceSpaceType` says which. `run.frameSource` is the session's own frame clock. Hand it to `startLoop` as `{ frameSource: run.frameSource }` and the loop runs at the headset's rate, passing the session's frame to `render` as its fourth argument, which is where every pose is read from. `run.onEnd` hears the session end, through `run.end()` or because the headset came off. `eyeViews(pose, layer)` turns a viewer pose into each eye's `view`, `projection` and `viewport`, and `aimCameraAtEye(camera, eye)` gives one eye to a `Camera` through `adoptView`: an eye's projection is off to one side, which a camera's own field of view cannot describe. That is as far as a frame goes today, since nothing draws the camera into the eye's viewport. ## A simulated headset ```ts /* A runtime that answers: two controllers, the left one with a hand, and a frame only when asked for one. `probeXrSupport` takes it in place of the browser's. */ const system = syntheticXr({ controllers: [{ handedness: 'left', hand: true }, { handedness: 'right' }], }); const simulated = await probeXrSupport(null, system); ``` `syntheticXr` is a runtime that answers. It grants sessions and reports two eyes 64 mm apart with off-axis projections that differ, controllers with buttons, and hands with twenty-five joints. It is the runtime the package's own tests run against, published with it as `@driftengine/xr/src/testing/synthetic.ts`, and it produces a frame only when `advance` is called, so a test asserting about a frame asserts about one it caused. `setButton` sets a controller's button, `setJointTracked` stops reporting a joint the way a finger behind the other hand stops being tracked, and `endLatest` ends a session the way taking a headset off does. It stands in for the browser, and it proves nothing about a real device. ```ts let session: SyntheticSession | null = null; let space: unknown = null; /* The steps `enterXr` takes, without the layer: a simulated session has nothing to draw into. */ async function putOn(): Promise { const started = (await system.requestSession('immersive-vr', { optionalFeatures: ['hand-tracking'], })) as SyntheticSession; space = await started.requestReferenceSpace('local-floor'); leftHand.clear(); started.addEventListener('end', () => { if (session === started) session = null; }); session = started; session.requestAnimationFrame(onFrame); } ``` A simulated session has no layer to build, so the example takes the steps `enterXr` takes without that one: request the session, ask for a reference space, listen for the end, ask for a frame. The page's own loop calls `advance` once a frame. ## Reading a frame ```ts /* What the frame said, kept where the script and the drawing both read it. */ const head = new Float32Array(3); let presenting = false; const states: ControllerState[] = []; const leftHand = new HandSkeleton(); function onFrame(_time: number, frame: XrFrame): void { const current = frame.session as XrSession; /* A session that has ended asks for no more frames. */ if (current !== session) return; const pose = frame.getViewerPose(space) ?? null; presenting = pose !== null; if (pose !== null) head.set(pose.transform.matrix.subarray(12, 15)); readControllers(current, frame, space, states); let sawLeft = false; for (const source of current.inputSources) { if (source.handedness !== 'left' || source.hand === undefined) continue; readHand(source, frame, space, leftHand); sawLeft = true; } /* A hand that is not there at all is forgotten; one merely out of view keeps its last poses. */ if (!sawLeft) leftHand.clear(); current.requestAnimationFrame(onFrame); } ``` Everything is read from the frame the session hands over, against the reference space. `getViewerPose` is the head, or nothing while tracking is lost. `readControllers(session, frame, space, out)` fills one `ControllerState` for each input source: its `handedness`, whether it is `tracked`, the `gripMatrix` where the hand holds it and the `rayMatrix` it points along, `buttons` and `pressed` in the standard gamepad order, and `axes`. `controllerFor(states, 'right')` finds one by hand, and `buttonValue` and `buttonPressed` read a button by its name in `XR_BUTTON`: `trigger`, `squeeze`, `touchpad` or `thumbstick`. `readHand(source, frame, space, skeleton)` fills a `HandSkeleton`, allocated once: a transform for each of the `JOINT_COUNT` joints in `matrices`, their `radii`, and `tracked`, a flag for each. A joint the runtime stops reporting keeps its last pose with its flag down. A tracker loses fingers constantly as they pass behind each other, and zeroing one would throw that finger onto the wrist for a frame; what to do with a stale joint is the game's, and the example draws it amber where it was last seen. `clear` is for a hand that has gone away altogether. `HAND_JOINTS` names the joints in order, `JOINT_INDEX` gives a name's place, and `jointPosition` reads one joint's position without allocating. ## From a script ```drs // The lamp follows the right trigger while a session is running and the controller is tracked. A // headset taken off ends the session, and the lamp goes out with it. fn light(lamp: mut Lamp, dt: f32) { var want: f32 = 0 if xr.presenting() && xr.holding(Hand.Right) { want = xr.trigger(Hand.Right) } lamp.level = lamp.level + (want - lamp.level) * math.min(1, lamp.ease * dt) } ``` `drift/xr` gives a script twelve reads. `presenting` says a session is running and `supported` that the device could present at all. `headX`, `headY` and `headZ` are where the head is, in metres. For a hand named `"left"` or `"right"`, `trigger` and `squeeze` are how far each is pulled, `holding` says its controller is tracked, `jointX`, `jointY` and `jointZ` place a joint named as in `HAND_JOINTS`, and `pinching` says the thumb and index tips are within 25 mm. None of them is deterministic, because a head moves when somebody moves it: a `@deterministic` system may not read one, and the script reads them in the frame. None of them is a matrix either, since drawing the eyes is the host's. ```drs // A joint the runtime stops reporting reads as zero, the way a fingertip that goes behind the other // hand does on a real headset. The page colours the hand when this says so. fn tipSeen() -> bool { return xr.jointY(Hand.Left, HandJoint.IndexFingerTip) != 0 } ``` A joint the runtime is not reporting reads as zero, so the script tells a lost fingertip from a seen one by its height. ```ts /* What `drift/xr` reads, from the state the frame left. Nothing here is deterministic, so the script reads it in the frame and never in the fixed step. */ const xr: XrRuntime = { get support() { return simulated; }, get headPosition() { return session !== null && presenting ? head : null; }, controller: (hand) => (session === null ? null : controllerFor(states, hand)), hand: (hand) => (session !== null && hand === 'left' && leftHand.visible ? leftHand : null), }; const script = hostScript(headsetScript, { xr }); interface Lamp { level: number; ease: number; } const lamp = exported<() => Lamp>(script, 'createLamp')(); if (import.meta.hot) { import.meta.hot.accept('./headset.drs', (next) => { if (next !== undefined) patchModule(script, next as Record, { Lamp: [lamp] }); }); } const light = (dt: number): void => exported<(l: Lamp, dt: number) => void>(script, 'light')(lamp, dt); const tipSeen = (): boolean => exported<() => boolean>(script, 'tipSeen')(); ``` The host hands the binding four things: `support`, the probe's answer; `headPosition`, three numbers or `null` outside a session; `controller(hand)`; and `hand(hand)`, a skeleton or `null`. The example builds them from what the frame left and answers `null` for all of them once the headset is off, so the lamp goes out with the session. --- # Saves and preferences Systems. https://driftengine.dev/docs/systems/saves The store a game saves to, preferences checked field by field, saves to a server that answers later, and a world written out and read back across a change. A game keeps two kinds of thing between sessions. Preferences are small and are read before the first frame: the volume, the controls, how fast the game runs. A save is the game itself, written when the player asks or on a timer, and read back when they return, sometimes by a version of the game that has changed since. The engine gives both one synchronous store to write to, a record of preferences that checks what it reads, a store that saves to a server behind that same seam, and a way to write an entity world out and read it back. The example is a garden bed that sows a seed a second until it is full, with the sowing and the growing in DriftScript. Save, Load and Clear are on the right. The saves go to a server that is the page pretending, a moment away, which keeps what it is sent in your browser's storage so a reload finds it; the strip makes it slow or takes it offline. The pace and the season are preferences: change one and reload, and it stays. (This chapter runs the `saves` example at https://driftengine.dev/docs/systems/saves.) ## One store, read at once `KeyValueStore` is three calls: `read(key)`, which answers a string or `null`, `write(key, value)` and `remove(key)`. It is synchronous on purpose. Preferences are read while the game boots, before the first frame, and a store that answered later would draw that frame with the wrong settings and correct it in front of the player. `BrowserStore` keeps its values in the page's local storage and in memory beside it, so a browser that blocks storage or runs out of room still has them until the page closes. `MemoryStore` keeps them only in memory, for a test or a game that saves nothing, and `hydrate` fills it from entries read elsewhere. `defaultStore()` is one `BrowserStore` shared by everything that asks for it, so give every key a prefix of your own. ## Preferences ```ts /* What the player chose, validated field by field: a pace outside its range is clamped, and a season that is not one of the two falls back to summer. */ interface GardenPreferences { pace: number; season: string; } const SCHEMA: PreferenceSchema = { key: 'driftengine.examples.saves.preferences', defaults: { pace: 1, season: 'summer' }, ranges: { pace: [0.25, 4] }, options: { season: ['summer', 'autumn'] }, }; const preferences = new PreferenceStore(SCHEMA); ``` A `PreferenceSchema` names the storage `key`, every field and the value it falls back to in `defaults`, an inclusive range for a number in `ranges`, and the allowed strings for a string in `options`. A field may be a number, a boolean or a string. A schema with any other kind of field is refused the first time it is used, since such a value would be written and never read back. `PreferenceStore` loads the record when it is made and checks it field by field. A number outside its range is clamped, a string that is not one of its options falls back to its default, and a field of the wrong type, or one the stored record does not have, takes its default too. A stored record always lags the code that reads it, so one field gone wrong keeps its default and the rest are still what the player chose. `value` is the record. `update(patch)` checks the fields it is given and, if any changed, saves the record and tells every `subscribe` listener; nothing changed means nothing is written and nobody is told, which keeps a listener that writes back from looping. `reset()` puts the defaults back. `loadPreferences` and `savePreferences` do the reading and the writing without a live record. A `PreferenceStore` writes to the default store unless it is given another. Preferences that should follow a player from one machine to the next go to a store like the one below. ## A server that answers later ```ts /* A server that is this page pretending. It answers after a delay, keeps what it is sent in the browser's own storage so that a reload finds it, and fails when the strip says it is down. */ type Server = 'online' | 'slow' | 'offline'; let server = flag('server', 'online') as Server; const HELD = 'driftengine.examples.saves.server'; const local = defaultStore(); const answer = (): Promise => new Promise((done) => setTimeout(done, server === 'slow' ? 2500 : 300)); const backend: SaveBackend = { async load() { await answer(); if (server === 'offline') throw new Error('the server did not answer'); return JSON.parse(local.read(HELD) ?? '[]') as [string, string][]; }, async save(changes) { await answer(); if (server === 'offline') throw new Error('the server did not answer'); const held = new Map(JSON.parse(local.read(HELD) ?? '[]') as [string, string][]); for (const [key, value] of changes) { if (value === null) held.delete(key); else held.set(key, value); } local.write(HELD, JSON.stringify([...held])); }, }; ``` A save kept on a server, in a desktop shell's file or in a platform's cloud is behind a call that answers later. `SaveBackend` is what a game writes for one. `load()` answers every entry it holds, and is called once. `save(changes)` takes a batch: a map from each key to its new value, or to `null` for a key removed. A backend whose API takes one key at a time loops inside `save`, and one that stores a whole document writes it in one request. `save` resolves when the batch has landed and rejects to have it tried again, so a backend that resolved before it knew would turn the store's status into decoration. ```ts /* The synchronous seam over the server: reads come from a copy loaded once, and writes are batched, sent after a quiet quarter second, and retried with a growing delay when the server fails. */ const saves = new RemoteSaveStore(backend, defaultSaveTimer(), { flushDelayMs: 250, maxAttempts: 3, retryDelayMs: 1000, }); await saves.load(); /* A write is durable once the server has it. Leaving the page is the last chance to send one. */ addEventListener('pagehide', () => void saves.flush()); ``` `RemoteSaveStore` puts that backend behind `KeyValueStore`, so everything that reads and writes a store uses it unchanged. `load()` is awaited once at boot and fills a copy that every `read` answers from. A `write` changes that copy at once and queues the key. Writes made close together go out as one batch after `flushDelayMs` of quiet, which is how a slider dragged across sixty frames becomes one request. A batch that fails is tried again after `retryDelayMs`, then after twice that, up to `maxAttempts` tries. Giving up on the attempt does not give up the changes: they stay queued and go out with the next write or `flush()`, and a key written again in the meantime goes with its newer value. Nothing throws. `status` is `idle`, `pending` while changes wait, `saving` while a batch is out, or `failed` once the tries are spent, with `pending` the number of keys waiting and `lastError` what the backend said. Show it: a game that says it saved over a queue that has been failing for ten minutes is worse than one that says nothing. A write is safe once the server has it, so a player who closes the page inside the quiet period loses it unless something calls `flush()`. The engine does not listen for the page going away, because which event means that depends on the platform; the example flushes on `pagehide`, and a desktop shell's close hook makes the same call. `defaultSaveTimer()` is the browser's timer, and a `SaveTimer` of your own replaces it in a test or on a platform without one. Take the example's server offline and press Save: the status goes to saving, then to failing with one change kept, and the script stops writing autosaves while that one waits. Put the server back online and the kept save goes out at once. ## Writing a world out ```drs component Plant { x: f32 = 0 z: f32 = 0 // Seconds grown, and how tall the plant stands once it is grown, in metres. age: f32 = 0 tall: f32 = 1 } // The bed: its own seed, how many seeds have gone in, and how fast it grows, which the page writes // from the player's preference. component Bed { seed: u32 = 7 sown: u32 = 0 pace: f32 = 1 } ``` ```ts /* The bed and every plant, written out with each component's schema beside it. */ const SLOT = 'driftengine.examples.saves.slot'; const written = (): string => JSON.stringify(serializeWorld(world, [type('Bed'), type('Plant')])); function save(): string { saves.write(SLOT, written()); return `saved ${world.count(type('Plant'))} plants; the store sends them`; } /* Into a fresh world, which replaces the running one only if every entity loaded. */ function load(key: string): string { const text = saves.read(key); if (text === null) return 'nothing is saved there yet'; const fresh = new World(); const result = deserializeWorld(fresh, JSON.parse(text) as SerializedScene, [ type('Bed'), type('Plant'), ]); if (!result.loaded) return result.reason; const found = result.entities.find((entity) => fresh.has(entity, type('Bed'))); if (found === undefined) return 'that save holds no bed'; world = fresh; bed = found; return `loaded ${fresh.count(type('Plant'))} plants`; } ``` `serializeWorld(world, types)` writes every entity that holds any of the given component types, each component's values under a stable field id, with each component's schema beside them. It is handed the types to save, not every store the world has, since a world keeps a store for anything that was ever asked about and a save is a decision about what matters. The result is plain data, which the example writes as JSON through the store. `deserializeWorld(world, scene, types)` reads one back. It answers `loaded: true` with the entities it made, or `loaded: false` with a sentence, having written nothing: it checks every entity before it touches the world, so a refusal at the fifth leaves no four behind. Every entity is made fresh, and a field declared `Entity` is pointed at the new handle; a number that happens to hold a handle is a number, and is left alone. The example loads into a new world and swaps it in only once the load has succeeded. The file carries the schema each component had when it was written, so a save loads across a change to the game. A field added since takes the value the component declares for it: with `water: f32 = 0.5` added to `Plant`, every plant in a garden saved before has a `water` of 0.5. A field declared without a value starts at zero, `false` or empty. A field removed since is dropped, and one whose type changed is refused by name instead of guessed at. Renaming a field gives it a new id, which drops the old value; `@id("old")` on the renamed field keeps the old one. Try it with the example running: save, add a field to `Plant` in `garden.drs`, reload the page, and press Load. A random sequence that a save should continue is saved the same way: `savableMulberry32` answers its position from `save` and goes back to it on `restore`, as [Determinism](https://driftengine.dev/docs/concepts/determinism) shows. The garden needs no generator, because the bed seeds each plant from its own count of seeds sown, and that count is in the save. ## From a script ```drs data Autosave { // Seconds between autosaves, and since the last one. every: f32 = 5 since: f32 = 0 written: u32 = 0 // How many were held back because the one before had not landed. held: u32 = 0 } // The page offers the garden once a second and the script decides whether it is written. An // autosave waits while the last one is still on its way, so a slow server is never handed a queue. fn autosave(auto: mut Autosave, store: Store, garden: String, dt: f32) -> bool { auto.since = auto.since + dt if auto.since < auto.every { return false } if persistence.pendingSaves(store) > 0 { auto.held = auto.held + 1 return false } persistence.write(store, "driftengine.examples.saves.auto", garden) auto.since = 0 auto.written = auto.written + 1 return true } ``` `drift/persistence` gives a script the store its host handed it: `read`, `write` and `remove` by key, and `saveStatus` and `pendingSaves` to ask how the saving is going. A script cannot make a store, so the host passes one in as an argument, the way it passes an input map. None of these is deterministic, since what a store holds depends on what the player did in another session. The example's page offers the garden to the script once a second, and the script decides whether it is written: every five seconds, and never while the last save is still waiting, so a slow server is not handed a queue of autosaves. [Input](https://driftengine.dev/docs/interface/input) saves a player's rebound controls through the same store, and only the bindings they changed. --- # Networking and rollback Systems. https://driftengine.dev/docs/systems/networking Two peers simulating one match over a lossy link, inputs as bytes, a rewind that replays a wrong guess, and an authority with clients that predict. `@driftengine/network` keeps several copies of one game in agreement over a link that is late and loses things. It has two ways of doing it. In lockstep, every peer simulates the whole match from everybody's inputs, and only inputs cross the wire. With an authority, one world is the truth and publishes its state, and each client predicts its own player until the truth arrives. Both rest on one mechanism: put the world back to an earlier tick, correct what was wrong about it, and step forward to now. (This chapter runs the `netplay` example at https://driftengine.dev/docs/systems/networking.) The example runs both peers of a lockstep match in one page. The left pitch is your screen, where you steer cyan with WASD, the arrows or a stick; the right pitch is the other player's screen, where a bot steers magenta. Each peer has its own world and its own session, and the only thing they share is the messages they send each other over a link the strip makes worse: latency, lost packets, how many recent inputs each packet repeats, and how many ticks of input delay the match runs with. The readout says how far each peer has confirmed the match, and how often and how far it has rewound. ## The rules both peers run ```drs // Every craft turns its pilot's input into speed, and stays on the pitch. system Fly { reads Pilot writes Craft update { for e in query() { e.Craft.vx = e.Craft.vx + (e.Pilot.x * THRUST - e.Craft.vx * DRAG) / 60 e.Craft.vz = e.Craft.vz + (e.Pilot.z * THRUST - e.Craft.vz * DRAG) / 60 e.Craft.x = math.clamp(e.Craft.x + e.Craft.vx / 60, 0 - HALF_WIDTH, HALF_WIDTH) e.Craft.z = math.clamp(e.Craft.z + e.Craft.vz / 60, 0 - HALF_LENGTH, HALF_LENGTH) } } } ``` The match is a DriftScript module: craft, a ball and a score as components, and two systems that move them. Both peers run every rule, and a rewind runs them again over ticks already played, so a rule has to give the same answer from the same world and the same inputs every time it runs. These read nothing but components. The controls reach them as a `Pilot` component the page fills in from the session before each step, never as a read of the keyboard, which would differ between the two machines and between a tick and its replay. ```drs // A craft that touches the ball sends it off the way it was hit; the ball rolls, slows, bounces off // the sides, and a goal puts it back on the spot. system Kick { reads Craft writes Ball writes Score update { for ball in query() { for craft in query() { let dx = ball.Ball.x - craft.Craft.x let dz = ball.Ball.z - craft.Craft.z let reach = dx * dx + dz * dz if reach < TOUCH * TOUCH && reach > 0.0001 { let d = math.sqrt(reach) ball.Ball.x = craft.Craft.x + dx / d * TOUCH ball.Ball.z = craft.Craft.z + dz / d * TOUCH ball.Ball.vx = dx / d * 5 + craft.Craft.vx * 0.6 ball.Ball.vz = dz / d * 5 + craft.Craft.vz * 0.6 } } let keep = 1 - (1 - ROLL) / 60 ball.Ball.vx = ball.Ball.vx * keep ball.Ball.vz = ball.Ball.vz * keep ball.Ball.x = ball.Ball.x + ball.Ball.vx / 60 ball.Ball.z = ball.Ball.z + ball.Ball.vz / 60 if math.abs(ball.Ball.x) > HALF_WIDTH { ball.Ball.x = math.clamp(ball.Ball.x, 0 - HALF_WIDTH, HALF_WIDTH) ball.Ball.vx = 0 - ball.Ball.vx } if math.abs(ball.Ball.z) > HALF_LENGTH { if math.abs(ball.Ball.x) < GOAL { for score in query() { if ball.Ball.z < 0 { score.Score.cyan = score.Score.cyan + 1 } else { score.Score.magenta = score.Score.magenta + 1 } } ball.Ball.x = 0 ball.Ball.z = 0 ball.Ball.vx = 0 ball.Ball.vz = 0 } else { ball.Ball.z = math.clamp(ball.Ball.z, 0 - HALF_LENGTH, HALF_LENGTH) ball.Ball.vz = 0 - ball.Ball.vz } } } } } ``` Save the file during a match and both peers take the new rule from the next tick, and the match carries on. [Entities](https://driftengine.dev/docs/simulation/entities) covers components and systems, and [Determinism](https://driftengine.dev/docs/concepts/determinism) what a simulation may compute and stay identical on every machine. ## An input is bytes ```ts /* An input is bytes the game chooses. This one is a single byte, a bit for each of four keys. */ const LEFT = 1; const RIGHT = 2; const UP = 4; const DOWN = 8; function decode(bits: number): { x: number; z: number } { return { x: (bits & RIGHT ? 1 : 0) - (bits & LEFT ? 1 : 0), z: (bits & DOWN ? 1 : 0) - (bits & UP ? 1 : 0), }; } ``` The package does not know what an input is. A game decides, and encodes each tick's input into a fixed number of bytes; here one byte, a bit per direction. Fixed so the log of every participant's inputs is one array for the whole session, and neither recording an input nor reading one back in a replay allocates. The step decodes it into the `Pilot` component. ## A peer ```ts /* One peer: its own world, the inputs every participant sent it, and a rewind loop that can put the world back to any of the last `depth` ticks and step it forward again. */ const FIXED_DT = 1 / 60; const PARTICIPANTS = 2; interface Peer { readonly world: World; readonly crafts: readonly Entity[]; readonly ball: Entity; readonly score: Entity; readonly inputs: InputLog; readonly loop: RewindLoop; } function makePeer(): Peer { const world = new World(); const crafts = [world.create(), world.create()]; world.add(crafts[0] as Entity, Craft, { z: 3 }); world.add(crafts[1] as Entity, Craft, { z: -3 }); for (const craft of crafts) world.add(craft, Pilot, {}); const ball = world.create(); world.add(ball, Ball, {}); const score = world.create(); world.add(score, Score, {}); const inputs = new InputLog({ participants: PARTICIPANTS, depth: 64, inputBytes: 1 }); const held = new Uint8Array(1); /* One tick: each participant's input for it, from the log, into its pilot, then the rules. A rewind calls this again for every tick it replays, with the inputs it now knows. */ const step = (_dt: number, tick: number): void => { for (let participant = 0; participant < PARTICIPANTS; participant += 1) { inputs.into(participant, tick, held); const { x, z } = decode(held[0] ?? 0); const pilot = crafts[participant] as Entity; world.write(pilot, Pilot, 'x', x); world.write(pilot, Pilot, 'z', z); } runSchedule(world, schedule, tick); }; const loop = new RewindLoop({ step, snapshotter: worldSnapshotter(world), inputs, fixedDt: FIXED_DT, depth: 24, }); return { world, crafts, ball, score, inputs, loop }; } ``` A peer is a world, an `InputLog` of every participant's inputs, and a `RewindLoop`. The loop calls `step(dt, tick)` once a tick, and before each step it saves the world into a ring `depth` ticks long, so slot _T_ holds the world as tick _T_ began. When an input arrives for a tick already played and it differs from what the peer guessed, the loop puts the world back to that tick's slot and replays every tick since with the inputs it now has. Here that is twenty-four ticks, 400 ms at 60 Hz. `worldSnapshotter(world)` is what the loop saves and restores: the whole entity world, every store, with nothing allocated per tick once the ring has gone round. A game whose state lives somewhere else writes its own `Snapshotter`, and `combineSnapshotters` puts several together, such as a world and a seeded random generator's position. ## A lockstep session ```ts /* A match: a network, two peers and a lockstep session each. Changing the link starts a new one. */ interface Match { readonly net: LoopbackNetwork; readonly peers: readonly [Peer, Peer]; readonly sessions: readonly [LockstepSession, LockstepSession]; tick: number; } function startMatch(): Match { const net = new LoopbackNetwork(); const peers = [makePeer(), makePeer()] as const; const sessions = peers.map( (peer, self) => new LockstepSession({ transport: net.open({ self, seed: 11 + self, impairment: impairment() }), loop: peer.loop, inputs: peer.inputs, self, participants: PARTICIPANTS, inputDelay, redundancy, }), ) as unknown as Match['sessions']; return { net, peers, sessions, tick: 0 }; } let match = startMatch(); ``` ```ts /* One fixed step of the whole match: each peer reads what has arrived, publishes this tick's input, and advances, rewinding first if something it guessed turned out wrong. */ const yours = new Uint8Array(1); const theirs = new Uint8Array(1); function tick(): void { const [a, b] = match.sessions; a.poll(); b.poll(); yours[0] = yourInput(); theirs[0] = botInput(match.peers[1]); a.submit(match.tick, yours); b.submit(match.tick, theirs); if (a.status === 'running') a.advance(FIXED_DT, match.tick); if (b.status === 'running') b.advance(FIXED_DT, match.tick); match.net.advance(1000 * FIXED_DT); match.tick += 1; } ``` Each tick, every peer does the same three things: `poll` applies whatever has arrived, `submit` publishes this tick's local input, and `advance` steps, rewinding first when an arrival changed a tick already played. Missing inputs are guessed by repeating the participant's last one, so a peer never waits for the network, and it rewinds only when a guess was wrong. Leave the keys alone and the other player's screen never rewinds, since it keeps guessing you hold nothing and is right; yours rewinds whenever the bot turns. Three settings decide how it behaves on a bad link: - **`inputDelay`** publishes a local input for a later tick: two ticks is 33 ms at 60 Hz. A link faster than that delivers every input before anybody needs it, so on that link no peer guesses and none rewinds. The cost is that your own control is that late on your own screen. Set it to six ticks on the strip and the rewinds stop at 60 ms; set it to none and they climb. - **`redundancy`** repeats the last few inputs in every packet, four by default. An input is only useful for its own tick, so asking for a lost one again would bring it after its tick had gone. With one input a packet and 20% loss, an input lost for good leaves a guess that is never corrected, and the two worlds part within two seconds; with four, the same link keeps the match in step. - **Fingerprints** are a hash of each peer's world at a tick every input has confirmed, sent every eight ticks. When two disagree, the session halts and names the tick: two peers computed different worlds from the same inputs, which is a determinism defect, and carrying on would give each player a plausible match unrelated to the other's. An input that arrives for a tick older than the rewind can reach halts it too. `status` is `running` or `halted`, and `reason` is the sentence the readout shows. Restarting is a new session, as `R` does here. ## The link ```ts /* The link both peers share. Everything about it is decided by the strip: how late a packet is, how much later some are than others, and how many never arrive. It runs on the simulation's clock, so one setting gives the same match every time it is played the same way. */ let latency = Number(flag('latency', '60')); let loss = Number(flag('loss', '5')); let redundancy = Number(flag('redundancy', '4')); let inputDelay = Number(flag('delay', '2')); function impairment(): Impairment { return { latencyMs: latency, jitterMs: latency / 3, loss: loss / 100 }; } ``` `LoopbackNetwork` connects transports inside one page, and an `Impairment` makes the connection as bad as asked: latency, jitter, loss, reordering and duplication, all drawn from a seed. It delivers on the clock `advance(ms)` gives it, which the example moves by one fixed step a tick, so a setting plays the same match every time it is played the same way. Tests and examples run on it. Between machines a session takes a real transport. Both send binary frames and neither queues inputs while connecting, since an input addressed to a tick that has passed is no use to anyone. A **text** frame from a server that speaks text arrives as its UTF-8 bytes, which is exactly what the server wrote, and a frame that cannot be read at all is counted in `dropped` rather than lost in silence: ```ts /** A relay over a WebSocket, which every browser and server has. Messages are binary frames. */ export function overWebSocket(url: string): WebSocketTransport { return new WebSocketTransport({ socket: new WebSocket(url) }); } /** * Peer to peer over WebRTC, on a channel that neither orders nor retransmits: a late input is * worth nothing, and the session's redundancy already covers a lost one. Signalling, the offer and * answer exchange, is the page's, since every game does it through its own server. */ export function overWebRtc(connection: RTCPeerConnection, self: number): WebRtcTransport { return new WebRtcTransport({ channel: unreliableChannel(connection), self }); } ``` ## One world as the truth ```ts /** * One world is the truth. The host steps it and publishes what it holds; a client predicts its own * player, and when the host's state arrives for a tick it already ran, rewinds to it and replays its * own inputs over the top. */ export function authority(transport: WebSocketTransport, world: World, bodies: readonly Entity[]) { const inputs = new InputLog({ participants: bodies.length, depth: 64, inputBytes: 1 }); const loop = new RewindLoop({ step: (dt) => { for (const body of bodies) { world.write(body, Body, 'x', (world.read(body, Body, 'x') as number) + dt); } }, snapshotter: worldSnapshotter(world), inputs, fixedDt: 1 / 60, depth: 16, }); /* What crosses the wire is the game's to choose: here each body's position as two doubles. */ const view = new DataView(new ArrayBuffer(16 * bodies.length)); const replicator: Replicator = { encode(into) { bodies.forEach((body, i) => { view.setFloat64(i * 16, world.read(body, Body, 'x') as number); view.setFloat64(i * 16 + 8, world.read(body, Body, 'z') as number); }); into.set(new Uint8Array(view.buffer)); return view.byteLength; }, apply(from) { const read = new DataView(from.buffer, from.byteOffset, from.byteLength); bodies.forEach((body, i) => { world.write(body, Body, 'x', read.getFloat64(i * 16)); world.write(body, Body, 'z', read.getFloat64(i * 16 + 8)); }); }, }; return new AuthorityHost({ transport, loop, inputs, replicator, stateEvery: 3 }); } export function client( transport: WebSocketTransport, loop: RewindLoop, inputs: InputLog, replicator: Replicator, self: number, ) { return new PredictingClient({ transport, loop, inputs, replicator, self }); } ``` With an authority, the host's world decides. `AuthorityHost` collects every client's inputs into its own log and steps, and every `stateEvery` ticks publishes its world through a `Replicator`, the game's own encoding of what a client needs. A `PredictingClient` steps its own copy with its own inputs at once, so its player answers at once; when the host's state for a tick arrives, it writes that state in, saves it over its slot, and replays its own inputs since then on top, so the correction keeps what the player did after it. `corrections` counts them. ```ts /** * Another player's body, drawn between the last two states that arrived, four ticks behind, so it * glides where the newest state alone would step every third tick. */ const remote = new StateInterpolator(16, 16, 4); export function received(tick: number, state: Uint8Array): void { remote.push(tick, state); } export function drawnAt(renderTick: number, out: { x: number; z: number }): boolean { const sample = remote.sample(renderTick); if (sample === null) return false; const from = new DataView(sample.from.buffer, sample.from.byteOffset, 16); const to = new DataView(sample.to.buffer, sample.to.byteOffset, 16); out.x = from.getFloat64(0) + (to.getFloat64(0) - from.getFloat64(0)) * sample.alpha; out.z = from.getFloat64(8) + (to.getFloat64(8) - from.getFloat64(8)) * sample.alpha; return true; } ``` A body the client does not predict arrives every few ticks. `StateInterpolator` keeps the last few states and answers two of them and a fraction between, a few ticks behind the newest, so the body glides between the host's states instead of stepping to each. ## What a script can see ```ts /** * What a script sees of a session: who it is, whether it is the authority, how far confirmed the * inputs are, and a few scalars per participant it can publish and read. The page points one at * whichever session it runs and hands it to the script as an argument. */ export function scriptView(session: LockstepSession): ScriptSession { return new ScriptSession({ self: session.self, participants: session.participants }).follow( session, ); } ``` `drift/network` gives a script a `Session`: which participant it is, whether it is the authority, the highest confirmed tick, whether the session halted and why, and a few numbered scalars per participant that it can publish and read, such as a health bar or a lap count. A `ScriptSession` follows whichever session the page runs and is handed to the script as an argument. `drift/rollback` gives it the `RewindLoop` as a `Rewind`: the tick, how far a rewind reaches, and whether this step is a replay, which is what a sound or a particle burst checks so it happens once. Only who a peer is and whether it is the authority may be read by a `@deterministic` function. The rest moves with packet timing, and `replicate` sends, so a replay would send again. [What a script can reach](https://driftengine.dev/docs/scripting/reach#driftnetwork) lists them all. ## Fixed point ```ts /** * Fixed point, 48.16 in a double, for a simulation that wants its arithmetic exact on every * machine whatever anyone argues about floating point. Every operation is a function. */ export function fixedStep(position: number, velocity: number, dt: number): number { const next = simAdd(simFrom(position), simMul(simFrom(velocity), simFrom(dt))); return simTo(next); } ``` `Sim` is a 48.16 fixed-point number held in a double, for a simulation that wants every operation exact on every machine without depending on how a platform rounds. It is opt-in: the arithmetic IEEE 754 fixes exactly is already the same everywhere, and [Determinism](https://driftengine.dev/docs/concepts/determinism) says which operations those are. --- # Recording and clips Systems. https://driftengine.dev/docs/systems/recording Saving a still, recording a clip as it plays with the mix underneath, and rendering one frame by frame with every frame stamped at its own instant. A game can keep what is on screen three ways. A still is one frame as a picture. A recording keeps frames as they play, in real time, with whatever the mix is doing. A render draws each frame at the instant it belongs to and encodes it with that instant, so the file is exact however long the machine took to make it. Core does the first two, and `@driftengine/media` does the third, which carries the encoder and its muxer so a game that never renders a clip never downloads them. (This chapter runs the `recording` example at https://driftengine.dev/docs/systems/recording.) The example's panel saves a still, records four seconds, or renders four seconds, and shows what it made. The strip picks the clip's shape, its rate, and whether it carries a mark. ## A show that is a function of time ```drs // One cycle, in seconds, and how many pillars it lights in turn. let PERIOD: f32 = 4 let PILLARS: f32 = 7 // How long a pillar stays up, as a share of the cycle. let HELD: f32 = 0.35 data Show { time: f32 = 0 } fn step(show: mut Show, dt: f32) { show.time = show.time + dt } // Where pillar `slot` is in its own rise, from 0 just as it lights to 1 as it settles. Below zero // or above one, it is down. @pure fn rise(time: f32, slot: f32) -> f32 { let cycle = time / PERIOD - slot / PILLARS let into = cycle - math.floor(cycle) return into / HELD } ``` ```drs // How tall a pillar stands and how brightly its cap glows. @pure fn height(time: f32, slot: f32) -> f32 { let r = rise(time, slot) if r < 0 || r > 1 { return 0.4 } return 0.4 + 1.6 * math.sin(r * 3.14159265) } @pure fn glow(time: f32, slot: f32) -> f32 { let r = rise(time, slot) if r < 0 || r > 1 { return 0 } return math.max(0, 1 - r) } // Whether pillar `slot` lit between two instants: the moment a chime belongs to. @pure fn lit(from: f32, to: f32, slot: f32) -> bool { let start = math.floor(from / PERIOD - slot / PILLARS) let end = math.floor(to / PERIOD - slot / PILLARS) return end > start } // The plinth turns once a cycle, and the camera goes round the other way, slower. @pure fn turn(time: f32) -> f32 { return time / PERIOD * 6.28318531 } @pure fn orbitX(time: f32) -> f32 { return math.sin(0 - time * 0.25) * 11 } @pure fn orbitZ(time: f32) -> f32 { return math.cos(0 - time * 0.25) * 11 } ``` Every rule in the show takes a time and answers where something is at that time. That is what lets one page play it live and render it for a clip: the live loop steps a record with the frame's time, the render steps a record of its own by exactly one frame each time, and both draw through the same function. A chime belongs to the instant a pillar lights, which `lit` says for any two instants, so the live mix and a rendered score ring at the same moments. ## A still ```ts /* Asked for here, taken inside the next frame: a WebGL drawing buffer is only readable before the page composites it. */ let stillWanted = false; function takeStill(): void { const frame = stillFrame( canvas, marked ? MARK : undefined, clock(() => live.time), ); if (frame === null) return say('This browser cannot copy the frame.'); frame.toBlob((png) => { if (png !== null) present(png, 'still.png', 'image'); say(`A still at ${frame.width} by ${frame.height}, the size of the canvas.`); }, 'image/png'); } ``` `stillFrame(canvas, overlay, drawFrame)` copies the canvas into a new 2D canvas at the canvas's own size, with the mark and the live layer a clip would carry. **Call it inside the render pass**, after `endFrame` and in the same task: a WebGL drawing buffer is only readable until the page composites it, and a copy taken later is black. A button sets a flag and the next frame takes the still. ## A mark and a clock ```ts /* Baked once per frame size: the engine's name in the corner. The clock is drawn live into every frame, after the scene and the mark, because it changes. */ const MARK: FrameOverlay = { texts: [{ text: 'DRIFTENGINE', x: 0.04, y: 0.05, cell: 0.006, color: '#e9edf5', alpha: 0.85 }], }; function clock(time: () => number) { return (ctx: CanvasRenderingContext2D, width: number, height: number): void => { const size = Math.round(Math.min(width, height) * 0.035); ctx.font = `${size}px ui-monospace, monospace`; ctx.textAlign = 'right'; ctx.fillStyle = 'rgba(233, 237, 245, 0.85)'; ctx.fillText(`${time().toFixed(1)} s`, width * 0.96, height * 0.94); }; } ``` A `FrameOverlay` is drawn into the picture rather than over the page, so it is in the file: texts placed as fractions of the frame, sized as a share of its shorter side, baked once per frame size. Anything that changes from frame to frame, a clock or a speedometer, goes in `drawFrame`, which draws straight into each composed frame after the scene and the mark. ## Recording as it plays ```ts /* Real time: the frame is locked to the clip's shape, the mark is composited into every frame, and the recorder keeps every n-th animation frame at the rate asked for, with the live mix. */ let recorder: FrameRecorder | null = null; let recordedFor = 0; async function record(): Promise { const graph = await startSound(); const { width, height } = FORMATS[format]; recorder = new FrameRecorder({ fps: rate, /* Only a mix that is playing. A suspended context's stream is a live track that never carries a sample, and a recorder waiting on it keeps about half a second of picture. */ audio: graph !== null && graph.audible ? graph.captureStream() : null, target: { source: canvas, surface: renderer, width, height, ...(marked ? { overlay: MARK } : {}), drawFrame: clock(() => live.time), presentedFrames: () => renderer.presentedFrames, }, }); const size = recorder.prepare(); recorder.start(); recordedFor = 0; busy(true); say(`Recording ${size?.width ?? width} by ${size?.height ?? height} for ${SECONDS} seconds.`); } async function stopRecording(): Promise { const ending = recorder; if (ending === null) return; recorder = null; /* Read before stopping: `stop` gives the surface back, and the pacing goes with it. */ const pacing = ending.pacing; const mime = describeClipMime(ending.mimeType); const file = await ending.stop(); busy(false); if (file === null) return say('The recording came back empty.'); present(file, `recorded.${mime.container === 'unknown' ? 'webm' : mime.container}`, 'video'); say( `Recorded ${mime.container === 'unknown' ? 'a clip' : `an ${mime.container.toUpperCase()}`}${mime.audio === 'unspecified' ? '' : ` with ${mime.audio === 'aac' ? 'AAC' : 'Opus'} audio`}${mime.shareable ? '' : ', which some share targets will not take'}. ${pacing === null ? '' : `It kept ${pacing.captured} frames, ${pacing.capturedFps.toFixed(1)} a second against ${pacing.targetFps} asked, the worst gap ${pacing.worstGapMs.toFixed(0)} ms.`}`, ); } ``` ```ts stage.run({ simulate(dt) { if (rendering) return; const before = live.time; rules().step(live, dt); if (sound !== null) chime(sound, before, live.time); if (recorder !== null) { recordedFor += dt; if (recordedFor >= SECONDS) void stopRecording(); } }, render() { /* The offline render owns the canvas while it runs. */ if (rendering) return; recorder?.captureDue(performance.now()); draw(live.time, canvas.height > 0 ? canvas.width / canvas.height : 1); renderer.endFrame(); if (stillWanted) { stillWanted = false; takeStill(); } recorder?.frameRendered(); }, }); ``` `FrameRecorder` records a fixed-size frame whatever shape the window is. `prepare` locks the renderer's drawing buffer to the clip's size before the first frame, so the camera composes for the clip's aspect, and `start` begins. Each frame the loop calls `captureDue(now)` before it draws and `frameRendered()` after `endFrame`; the recorder keeps every n-th animation frame, n chosen from the loop's measured rate, so the frames are evenly spaced and so is what they show. `stop` gives the surface back and answers the file. Read `pacing` before stopping: it says how many frames were kept and at what rate, and the example held 30.0 a second against 30 asked. A recording runs in real time and cannot be given more. `MediaRecorder` stamps each frame with the moment it arrived, so a slow machine makes a slower clip. Pass the mix as `audio` only while it is playing: `graph.captureStream()` answers a stream even for a suspended context, and a recording waiting on a track that never carries a sample kept about half a second of picture in a test, with no error. `describeClipMime(recorder.mimeType)` says what the browser chose; only MP4 with AAC is `shareable`, the file every phone's share targets take as it is. ## Rendering frame by frame ```ts /* Offline: no clock at all. Each frame is drawn at the instant it belongs to and stamped with it, and the score is rendered on an offline audio context from the same rules, so the file is exact however long it took to make. */ const nextFrame = (): Promise => new Promise((resolve) => requestAnimationFrame(resolve)); let rendering = false; async function renderClip(): Promise { busy(true); try { /* The round trip first: on some configurations every frame reaches the encoder empty while every call reports success, and the file comes out solid green. */ if ((await framesReachEncoder()) === 'empty') { return say('This browser hands its encoder empty frames, so a rendered clip would be blank.'); } const { width, height } = FORMATS[format]; const fps = rate; const bitrate = clipBitrate(width, height, fps); if (!(await clipEncodingSupported({ width, height, fps, bitrate }))) { return say(`This browser cannot encode ${width} by ${height} at ${fps} fps.`); } const frames = SECONDS * fps; /* The score, scheduled at the instant of each frame on an offline context. */ const offline = new OfflineAudioContext(2, SECONDS * 48000, 48000); const score = await AudioGraph.create({ stemCount: 0, context: offline }); if (score === null) return say('No audio graph on an offline context.'); registerChimes(score); await score.registry.load(offline); for (let i = 1; i < frames; i += 1) { score.at(i / fps); chime(score, (i - 1) / fps, i / fps); } const audio = await offline.startRendering(); const encoder = await ClipEncoder.open({ width, height, fps, bitrate, sampleRate: 48000 }); rendering = true; renderer.lockDrawingBuffer(width, height); const clip = exported<() => Show>(show, 'createShow')(); for (let i = 0; i < frames; i += 1) { await nextFrame(); draw(clip.time, width / height); renderer.endFrame(); const frame = stillFrame( canvas, marked ? MARK : undefined, clock(() => clip.time), ); if (frame !== null) await encoder.addFrame(frame, i); rules().step(clip, 1 / fps); say(`Rendering frame ${i + 1} of ${frames}.`); } await encoder.addAudio(audio); const file = await encoder.finish(); if (file === null) return say(`The encoder gave up: ${encoder.error ?? 'no reason given'}.`); present(file, 'rendered.mp4', 'video'); say( `Rendered ${frames} frames at ${width} by ${height}, H.264 with ${encoder.audioCodec === 'aac' ? 'AAC' : 'Opus'} audio, each frame stamped at its own instant.`, ); } finally { if (rendering) renderer.unlockDrawingBuffer(); rendering = false; busy(false); } } ``` `ClipEncoder` encodes frames and samples into an MP4 on a timeline the page chooses: frame `i` is stamped `frameTimestampUs(i, fps)`, so nothing in the file depends on how busy the machine was. The score is rendered first on an `OfflineAudioContext`, with `graph.at(seconds)` before each frame's chimes so every one lands where its frame is, and handed over whole with `addAudio`. The example's render came out at 120 frames and 4.000 seconds exactly. A recording's audio was measured leading its picture by 51 ms in one run and 85 ms in the next, which is the error this path does not have. Two checks come first. `clipEncodingSupported` asks whether this browser encodes this size at this rate. `framesReachEncoder` encodes a magenta frame, decodes it and reads the colour back, once a session: some configurations hand the encoder empty frames while every call reports success, and the file comes out solid green with its audio intact. It answers `'empty'` only when it saw that happen, and `'unknown'` lets the render through. `audioCodec` says whether the file carries AAC or Opus. AAC where the browser has an encoder for it, and Opus otherwise, which some apps that take a video will not open. ## Before offering a button ```ts /** * What to offer, asked once before anything is built: a still always, a recording where the * browser has a recorder, and a render where it can encode a clip of this size and hands its * encoder real pictures. */ export async function whatToOffer(width: number, height: number, fps: number) { const recordable = supportedClipMimeType(); const renderable = offlineEncodingSupported() && (await clipEncodingSupported({ width, height, fps, bitrate: clipBitrate(width, height, fps), })) && (await framesReachEncoder()) !== 'empty'; return { still: true, record: recordable !== null, /* MP4 with AAC is the one file every phone's share targets take as it is. */ recordShareable: recordable !== null && describeClipMime(recordable).shareable, render: renderable, }; } ``` Ask once, before building anything: `supportedClipMimeType` is null where the browser cannot record, `offlineEncodingSupported` says whether it has the encoders at all, and the size check and the round trip say whether a render would work and come out right. A still needs nothing. ## Sharing a clip ```ts /** A finished clip to the share sheet where there is one, and a download where there is not. */ export async function share(clip: Blob): Promise { await offerClip(clip, clip.type.includes('mp4') ? 'clip.mp4' : 'clip.webm'); } ``` `offerClip(blob, filename)` opens the device's share sheet where there is one and the file can go through it, and downloads the file otherwise. ## A smaller frame on a slower device ```ts /** * The frame to record at, from what the renderer is managing in the window. A device below the * clip's rate records at two thirds the size, which keeps its rate: a slightly softer clip that * holds 30 fps reads better than a sharp one that judders. */ export function recordingSize(window: HTMLCanvasElement, measuredFps: number) { return exportSizeFor(1080, 1920, measuredFps, 30, window.width * window.height); } ``` A recording keeps its rate by recording smaller. `exportSizeFor(width, height, measuredFps, targetFps, windowPixels)` compares what the renderer is managing in the window, scaled to the clip's pixel count, with the rate asked for, and answers two thirds of the size per side when the device would fall short. Pass the measurement as `measuredFps` in `FrameRecorder`'s target and `prepare` does the same. ## The pacer on its own ```ts /** * The pacer alone, for a page that captures frames some other way. It keeps every n-th animation * frame, n chosen from the loop's measured rate, so the frames kept are evenly spaced and so is * what they show; `report` says what it managed. */ const pacer = new FramePacer(30); export function onAnimationFrame(nowMs: number, capture: () => void): void { if (!pacer.due(nowMs)) return; capture(); pacer.offer(nowMs); } export function howItWent(): string { const { capturedFps, worstGapMs, slipped } = pacer.report; return `${capturedFps.toFixed(1)} fps, worst gap ${worstGapMs.toFixed(0)} ms, ${slipped} slipped`; } ``` `FramePacer` is what the recorder keeps frames with, for a page that captures frames some other way. `due(now)` asks before drawing whether this frame will be kept, `offer(now)` commits with the same instant, and `report` says what it managed: frames kept, their rate, the worst gap, and how many slipped. --- # Display and the host Systems. https://driftengine.dev/docs/systems/display The window, the screen and the shell as capabilities a game asks about: window mode and size, orientation, focus and quitting, files, and the boot badge. A game runs in a browser tab, in a desktop shell, or on a phone, and each can do different things with its window. The engine does not guess which it is in. It declares what it needs as a handful of capabilities, a host supplies them, and a game asks them what is possible before it draws a control. A browser host ships with the engine for each, and each answers `false` or `null` where a browser genuinely cannot, instead of doing nothing quietly. (This chapter runs the `display` example at https://driftengine.dev/docs/systems/display.) The example is a video settings screen over a turning test card. Every line is what the host answered, every button is drawn from what it allows, and where the answer is no the panel says why. ## The host ```ts /* The host, as four capabilities. A shell passes its own; a page in a browser uses these. */ const display: DisplayControl = new BrowserDisplay(document.documentElement); const screen: ScreenPresentation = new BrowserScreenPresentation(); const lifecycle: Lifecycle = new BrowserLifecycle(); const files: FileDialogs = new BrowserFileDialogs(); ``` Four capabilities, each an interface with a browser implementation beside it. A desktop shell passes its own, and a game written against the interfaces runs in both without asking which it is in. A packaged game takes all of them from `createHost`, which [Packaging an application](https://driftengine.dev/docs/systems/packaging) covers: | Capability | What it answers | | -------------------- | ------------------------------------------------------------------------------------------ | | `DisplayControl` | The window's mode and size, whether it can be resized, the displays and their refresh rate | | `ScreenPresentation` | Orientation and locking it, the safe area, keeping the screen awake | | `Lifecycle` | Focus, whether the game can quit, and a request to quit from outside | | `FileDialogs` | Opening and saving a file through the platform's picker | ## The window ```ts /* Each control is drawn from the host's own answer, read when it is drawn. */ function drawWindow(): void { const { width, height } = display.size(); say('mode', display.mode()); say('size', `${Math.round(width)} by ${Math.round(height)}`); /* A browser never sizes its own window; a shell will, except while it covers a display. */ $('smaller').disabled = !display.canSetSize(); say('size-note', display.canSetSize() ? '' : 'The window is sized by whoever holds it.'); const shown = display.displays(); say( 'displays', shown .map( (d) => `${d.label} at ${d.scale}x, ${d.refreshHz === null ? 'rate not said' : `${d.refreshHz} Hz`}`, ) .join('; '), ); } $('fullscreen').addEventListener('click', () => { /* Fullscreen needs a gesture, which this click is. `false` means refused, never an error. */ void display .setMode(display.mode() === 'fullscreen' ? 'windowed' : 'fullscreen') .then(drawWindow); }); $('smaller').addEventListener('click', () => { const { width, height } = display.size(); void display.setSize(Math.round(width * 0.8), Math.round(height * 0.8)).then(drawWindow); }); addEventListener('resize', drawWindow); document.addEventListener('fullscreenchange', drawWindow); ``` `mode()` is `'windowed'` or `'fullscreen'`, read each time and never remembered, and `setMode` answers `false` when the platform refused, which a browser does outside a gesture. There are two modes and not three, because Chromium never takes an exclusive fullscreen. `canSetSize()` asks whether `setSize` would work, without performing one. A browser never resizes its own window, and a shell will not while the window covers a display, so a settings screen reads it each time it draws and greys its resolution control. `displays()` lists what the platform admits to: a browser knows the screen it is on and nothing about any other, and leaves `refreshHz` null because it will not say. ## The screen ```ts /* What a phone has instead of a window. The safe area is drawn as an outline, so a notch shows. */ function drawScreen(): void { say('orientation', screen.orientation()); const inset = screen.safeArea(); const frame = $('safe-area'); frame.style.inset = `${inset.top}px ${inset.right}px ${inset.bottom}px ${inset.left}px`; say('insets', `${inset.top}, ${inset.right}, ${inset.bottom}, ${inset.left}`); } for (const choice of ['portrait', 'landscape', 'free'] as const) { $(`lock-${choice}`).addEventListener('click', () => { const wanted: ScreenOrientation | null = choice === 'free' ? null : choice; void screen.lockOrientation(wanted).then((done) => { say('lock-note', done ? `Locked to ${choice}.` : 'This platform will not lock it.'); drawScreen(); }); }); } let awake = false; $('awake').addEventListener('click', () => { awake = !awake; void screen.keepAwake(awake).then((held) => { say( 'awake-note', awake ? held ? 'The screen stays on.' : 'There is no wake lock here.' : 'The screen may sleep.', ); }); }); ``` What a phone has instead of a window. `lockOrientation` answers `false` where the platform refuses, which iOS always does and a desktop browser does too. `safeArea()` is the logical pixels the platform has taken from each edge for a notch or a home bar, zero on a plain window; the example outlines it. `keepAwake` holds a wake lock while a game is being watched and not touched, and answers whether it got one. ## Focus and quitting ```ts /* The test card stops while the page is not in front, and Quit exists only where it works. */ let focused = true; lifecycle.onFocusChange((now) => { focused = now; say('focus', now ? 'in front' : 'behind something'); }); lifecycle.onQuitRequest(() => { /* A shell waits for this before it closes; a browser never calls it. */ saveSettings(); }); $('quit').hidden = !lifecycle.canQuit; say( 'quit-note', lifecycle.canQuit ? '' : 'A page cannot close its own tab, so there is no Quit button here.', ); $('quit').addEventListener('click', () => lifecycle.requestQuit()); ``` `onFocusChange` tells a game when it goes behind something, which is when to pause. `canQuit` is what an exit button is drawn from: a page cannot close its own tab and an iOS app does not exit, so a menu that always shows Quit has a button that does nothing on two platforms, and a game that branches on whether it is in a shell has written down an assumption that stops being true. A shell calls `onQuitRequest` when its window is asked to close and waits for the game; a browser never calls it. ## Files ```ts /* The settings as a file the player keeps. A shell's picker is a native dialog; a browser's is the File System Access picker where it has one, and throws where it has none. */ interface Settings { mode: string; cursor: string; } let cursorColor = flag('cursor', 'amber'); function saveSettings(): void { const settings: Settings = { mode: display.mode(), cursor: cursorColor }; const bytes = new TextEncoder().encode(JSON.stringify(settings, null, 2)); files.saveFile('settings.json', bytes).then( (saved) => say('file-note', saved ? 'Saved.' : 'Not saved.'), () => say('file-note', 'There is no file picker in this browser.'), ); } $('save').addEventListener('click', saveSettings); $('open').addEventListener('click', () => { files.openFile(['.json']).then( (opened) => { if (opened === null) return say('file-note', 'Nothing opened.'); const settings = JSON.parse(new TextDecoder().decode(opened.bytes)) as Partial; if (typeof settings.cursor === 'string') applyCursor(settings.cursor); say('file-note', `Opened ${opened.name}.`); }, () => say('file-note', 'There is no file picker in this browser.'), ); }); ``` `openFile(accept)` answers the file's name and bytes, or `null` when the player cancelled, and `saveFile(name, bytes)` answers whether it was saved. Both throw where there is no picker at all: a shell supplies a native dialog, and a browser uses the File System Access picker where it has one. ## Store features ```ts /** * Achievements and presence, from whatever store the shell is built for. The engine never calls * these on its own and ships nothing for them, so a game that never asks for an achievement * carries no store SDK. Neither may throw: a store that is offline is an ordinary state. */ export function storeServices(store: { unlock(id: string): Promise; presence(text: string): void; }): PlatformServices { return { unlockAchievement(id) { store .unlock(id) .catch((error: unknown) => console.warn('achievement not unlocked', id, error)); }, setRichPresence(text) { store.presence(text); }, }; } ``` Achievements and presence are `PlatformServices`, and there is no browser version of it: there is nothing honest a page can do with an achievement. A shell built for a store supplies one, the engine never calls it on its own, and a game that never asks for an achievement ships no store SDK. Neither method may throw. ## A cursor of its own ```ts /* A cursor drawn from a grid of characters, at the device pixel ratio, recoloured at will. */ const ARROW = [ 'x.......', 'xx......', 'xox.....', 'xoox....', 'xooox...', 'xoooox..', 'xooxxxx.', 'xx......', ]; const INKS: Record = { amber: '#f0a437', cyan: '#4fd6e0', white: '#f2f4f8' }; function applyCursor(name: string): void { cursorColor = name in INKS ? name : 'amber'; canvas.style.cursor = pixelCursor( ARROW, { x: '#0b0d12', o: INKS[cursorColor] as string }, { scale: 3, hotspotX: 0, hotspotY: 0, }, ); } applyCursor(cursorColor); controls([ { key: 'cursor', label: 'cursor', value: cursorColor, options: Object.keys(INKS).map((ink) => ({ text: ink, value: ink })), change: (value) => applyCursor(value), }, ]); ``` `pixelCursor(rows, palette, options)` builds a CSS cursor from a grid of characters, each mapped to a colour and absent ones transparent. It is drawn at the device pixel ratio so it stays sharp, costs no image file, and can be recoloured to match whatever the game is wearing. ## Filling a phone's screen ```ts /* On a phone, the first tap anywhere fills the screen, once. On a desktop this does nothing. */ requestFullscreenOnGesture(document.documentElement); ``` A phone's browser keeps its address bar, and a page fills the screen only by being an installed app that asks for it in its manifest, or by calling fullscreen from a gesture. `requestFullscreenOnGesture(element)` does the second, on the first tap anywhere, once per page load, and only where the pointer is coarse. A desktop player chose their window's size and is never asked, and a player who leaves fullscreen is not asked again. iPhone Safari has no element fullscreen, so there only the installed route works. ## The badge a game boots behind ```ts /** * The badge is on unless a page declines it: a canvas that is one part of a page, or a tool that * opens into its own interface, is not a game booting. */ export async function toolRenderer(canvas: HTMLCanvasElement) { return createRenderer(canvas, {}, { splash: false }); } /** Or held longer, for a game whose first frame comes before it has anything to show. */ export async function gameRenderer(canvas: HTMLCanvasElement) { return createRenderer(canvas, {}, { splash: { minMs: 4000 } }); } ``` `createRenderer` shows the engine badge over the page until the first frame reaches the screen, before it even probes for a device, so a web game has a cover while it loads without writing one. It stays at least three seconds, lifts at the first frame after that, and never stays more than twenty; the loop is held while it shows, so the first seconds of a game are not spent behind it. `splash: false` declines it, which is right for a canvas that is one part of a page or a tool that opens into its own interface, and `{ minMs }` holds it longer. `?splash=0` and `?splash=1` in the address override it either way on a deployed build. A packaged shell shows its own and suppresses this one. A game whose first screen takes longer to load than its first frame can hold the badge for it: `holdSplash(promise, { capMs })` keeps it up until the promise settles, either way, as well as until the first frame. Frames run while the game loads behind it, since a load may need them, and are held for whatever is left of the three seconds once it has settled. `capMs` is the game's own ceiling in place of the twenty seconds. It returns whether there was a badge to hold. --- # Packaging an application Systems. https://driftengine.dev/docs/systems/packaging Turning a web build into a desktop, mobile or native application with drift-package, and the one host a game writes its settings and its exit against. A DriftEngine game is a web page, and [Shipping to the web](https://driftengine.dev/docs/start/shipping-to-the-web) puts it on a server. `@driftengine/package` turns the same build into an installable application: a desktop app for Linux, Windows and macOS, an Android APK, an iOS project, and on Linux a native build that runs the engine on Node, Dawn and SDL with no browser at all. The engine never learns which it is in. The game asks one host what it can do, and the packager supplies the right one. ## The commands ```sh npx drift-package init # the two scripts a project has to own npx drift-package doctor # is this packageable, and how would it be signed npx drift-package run # the real shell, from source, no installer npx drift-package build --target=native-linux-x64 # an artifact npx drift-package verify --contains= ``` `init` writes `scripts/package.mjs`, a stable entry point, and `scripts/build-windows.ps1`, which starts Node on a Windows machine, and refuses to overwrite either once it is yours. `doctor` says what this machine can build, how each build would be signed and what is missing, with the command that fixes each. `verify` looks inside a finished artifact for a string you just changed, which is how to know the build carries your edit. ## The manifest `drift.package.json`, beside `package.json` in the project that makes the web build: ```json { "id": "dev.example.title", "name": "Title", "entry": "dist/index.html", "publisher": "Example", "icon": "art/icon.png", "window": { "width": 1280, "height": 720, "mode": "windowed", "resizable": true }, "backend": { "webgpu": "prefer", "allowSoftwareRenderer": false }, "features": { "clipExport": false, "gamepad": true }, "splash": { "show": true, "minMs": 1400 }, "targets": ["linux-x64", "win-x64", "mac-arm64"], "steam": { "appId": null }, "android": { "permissions": [], "cleartextTraffic": false, "orientation": "unspecified" } } ``` `id`, `name`, `entry` and `targets` are required, and a refusal names the field it is about. `icon` is a 1024 by 1024 PNG and defaults to the engine's mark. `window.mode` is what the window is created as, `borderless` for a frameless one, and is not the mode a settings screen changes later. ## One host on every platform ```ts /** * Every capability, picked for wherever the build is running: the browser's in a tab, the shell's * in a desktop or mobile build. A game writes one settings screen against it and ships it to all. */ export async function settings(canvas: HTMLCanvasElement) { const host = createHost(canvas); await host.display.setMode('fullscreen'); if (host.display.canSetSize()) await host.display.setSize(1920, 1080); /* A file beside the application in a shell, localStorage in a tab, Steam Cloud where the manifest names an app. The game writes the same line in all three. */ host.store.write('settings.volume', '0.8'); return host; } ``` `createHost(canvas)` answers every capability [Display and the host](https://driftengine.dev/docs/systems/display) describes, picked for wherever the build is running: the browser's own in a tab, and the shell's in a packaged build, where `setSize` works, `displays()` lists the screens the shell can see, and `store` is a file beside the application. A game writes one settings screen against it. `host.native` says which it got, for the rare decision that needs to know. Render resolution is not the window's: a game that wants fewer pixels lowers `resolutionScale` in its [quality](https://driftengine.dev/docs/concepts/quality) settings. ## Leaving the game ```ts /** An exit button only where one does something, and a chance to keep the player first. */ export function leaving(canvas: HTMLCanvasElement, menu: { addExit(leave: () => void): void }) { const host = createHost(canvas); if (host.lifecycle.canQuit) menu.addExit(() => host.lifecycle.requestQuit()); host.lifecycle.onQuitRequest(() => { /* A window's close button, or Android's back gesture: pause, ask, then go. */ if (confirm('Leave the run?')) host.lifecycle.requestQuit(); }); } ``` `canQuit` is false in a tab and on iOS, true in a desktop or Android build, and an exit button is drawn from it. `onQuitRequest` is called before the shell closes anything. On Android the back gesture goes to the game first: to a quit handler if there is one, otherwise as an Escape key, since a game with no handler usually has a pause menu on Escape, and only then to closing, which takes two presses within two seconds. A single gesture never ends a run. ## Where each artifact is built | Target | Built on | How | | ---------------------- | ---------------------------------- | ------------------------------------------------- | | `native-linux-x64` | Linux on x64 | `build --target=native-linux-x64` | | `linux-x64` | Linux | `build --target=linux-x64` | | `win-x64` | Windows, a virtual machine is fine | the `scripts/build-windows.ps1` that `init` wrote | | `mac-arm64`, `mac-x64` | macOS, or Linux | `build --target=mac-arm64` | | `android` | anywhere | `build --target=android` | | `ios` | macOS with Xcode | `build --target=ios` | `build` refuses a target this machine cannot honestly produce. A Mac build from Linux is file copying and an ad-hoc signature, since Apple Silicon refuses an unsigned binary outright, and comes out as a `.zip` that should be opened on a Mac before anyone else gets it. `npx drift-package bootstrap` fetches each target's toolchain into `~/.cache/driftengine/toolchain`, installing nothing system-wide. ## Signing | Mode | When | What the player sees | | ------- | ---------------------------------------------------- | ------------------------------------------------------------- | | `none` | no identity, and the target does not need one | Linux nothing; Windows warns on first run | | `adhoc` | no identity, and the target needs a signature to run | macOS runs locally; a download is refused until unquarantined | | `real` | an identity is in the environment | nothing: the artifact is trusted | Signing material comes from the environment, never from the manifest, which is committed: `CSC_LINK` and `CSC_KEY_PASSWORD`, `WIN_CSC_LINK` and `WIN_CSC_KEY_PASSWORD`, and `APPLE_ID`, `APPLE_APP_SPECIFIC_PASSWORD` and `APPLE_TEAM_ID` for notarisation. A Steam depot needs none of it, because the client that delivers it is signed. ## The native target ```ts /** * The native host has no page to find a canvas in, so the manifest's `native.entry` names a module * that exports `mount`, and the host calls it with the canvas it made. A game that already mounts * onto a canvas it is given needs nothing more than this. */ export function mount(canvas: HTMLCanvasElement): void { void settings(canvas); } ``` On Linux x64, `native-linux-x64` runs the game on `@driftengine/native-host`: Node, Dawn (the WebGPU implementation Chrome uses) and SDL for the window, input and controllers, with the browser's events, animation frames, pointer lock, fullscreen and gamepads supplied around the canvas. A game installs the host at the engine's version and names a module exporting `mount(canvas)` as `native.entry`, since there is no page to find a canvas in. The archive carries its own Node, the bundled game, its web build for the game's own `fetch`, and every package's licence. Measured on one machine with the starter packaged both ways, the native archive was 61 MB against Electron's 122, built in 7 seconds against 3 minutes, and reached its first frame in 750 ms on WebGPU, most of it compiling pipelines, which the binding cannot cache. It leaves out what a browser adds around the canvas: the rest of the DOM, WebGL2, clip export, WebXR, the badge and a store. Every published scene is drawn by the host and by Chrome and compared pixel for pixel by `npm run native:gate`. The Electron targets stay as the compatibility build: on Windows and macOS, where there is no native host yet, and on Linux for a game that needs what the host lacks. ## Steam ```jsonc "steam": { "appId": 480 } ``` ```sh npm install steamworks.js npx drift-package build --target=linux-x64 npx drift-package steam --target=linux-x64 # the two files steamcmd uploads with ``` ```ts /** Achievements, where a store build was launched by its store; null everywhere else. */ export function finishedTheGame(canvas: HTMLCanvasElement): void { const host = createHost(canvas); host.services?.unlockAchievement('FINISHED'); host.services?.setRichPresence('Watching the credits'); } ``` With an app id in the manifest, saves go to Steam Cloud through the same `host.store`, read from the cloud first at boot so a player on a new machine finds their settings. `host.services` carries achievements and presence, and is `null` in a browser, where no app is named, and when the build was started outside Steam, which is every run during development. `steamworks.js` is installed in the game, so a game that never ships on Steam carries no SDK. The upload files set nothing live: a build waits in Steam's admin for a person. ## Android ```sh npx drift-package bootstrap --target=android npx drift-package build --target=android adb install "out/android/-.apk" ``` One activity holding the platform's WebView, serving the game from an https origin so modules, workers and `crossOriginIsolated` work, with the same host bridge the desktop has. The renderer is the device's WebView, which is why the APK is about 20 MB, and why WebGL2 is the baseline there. An APK asks for no permissions until the manifest does. A game that talks to a server needs `"permissions": ["INTERNET"]`: without it every connection fails and neither end says why. `cleartextTraffic` allows a `ws://` relay on a LAN, which cannot hold a certificate, and should stay false for a public one. `orientation` is the activity's `android:screenOrientation`: `unspecified` leaves it to the phone, and a game played sideways asks for `sensorLandscape` (turnable) or `landscape` (not), held from the first frame rather than turned once the game's code runs. Android refuses an unsigned APK, so without a keystore the packager generates one under `~/.cache/driftengine/toolchain/keystores/` and says so on every build. **Back that file up.** It is the application's identity: a phone refuses an update signed by a different key, and the only way past is uninstalling, which deletes the player's saves. A second machine silently generates a second key. `DRIFT_ANDROID_KEYSTORE`, `DRIFT_ANDROID_KEYSTORE_PASSWORD` and `DRIFT_ANDROID_KEY_ALIAS` take over once there is a real one. ## iOS ```sh npx drift-package bootstrap --target=ios npx drift-package build --target=ios ``` A `WKWebView` serving the game over a custom scheme, with WebKit as the renderer because Apple requires it. A clip goes to the share sheet, since there is no Downloads folder. The build is unsigned unless `APPLE_TEAM_ID` is set. This target has not yet been built on a Mac: the bridge it shares with Android is tested, and the Swift and the project are written against Apple's documentation. ## What a device says about itself ```text …/index.html?report=1 ``` Draws the renderer string, whether WebGPU is offered, the secure-context answer, the platform and the WebView build over the running game, on every platform. It matters most on a phone, where a shader that compiled on every desktop browser can fail on WebKit alone. ## Three things that bite - **A network drive refuses the first copy.** A share that invents file identities makes Node's copy believe it is copying a folder into itself. `doctor` refuses this before a build starts; `--out=/a/local/disk` puts the build somewhere it cannot happen. - **`ELECTRON_RUN_AS_NODE`.** An editor's integrated terminal often exports it, and a packaged game that inherits it starts as plain Node and dies. The generated scripts and `drift-package run` unset it. - **A fresh `npm ci` may skip the Electron binary.** `node node_modules/electron/install.js` fetches it, and `bootstrap` does the same. --- # In-game tools Tools. https://driftengine.dev/docs/tools/in-game-tools An inspector, a console, a profiler and a network panel over a running game on a key, with undoable edits, plus core's frame meter and contact probe. Trouble on a tester's machine, on a console devkit or in a release build happens where no debugger is attached. `@driftengine/tools` is four of the editor's panels packaged so the game can carry them: an inspector, a console, a profiler and a network panel, with the command stack that makes an edit undoable and an overlay that puts them over the scene on a key. A game that never imports the package carries none of it. Core adds two smaller instruments, a frame meter and a contact probe. (This chapter runs the `tools` example at https://driftengine.dev/docs/tools/in-game-tools.) The example drops six balls on a floor. F3 opens the overlay: the selected ball's fields, a console the page writes to as the balls land, and a profiler of the frame. Tab selects the next ball, `[` and `]` give it less or more bounce, Ctrl+Z takes the change back, and R drops them all again. ## What the panels read ```drs component Ball { y: f32 = 3 vy: f32 = 0 // The share of its speed a ball keeps at each bounce. bounce: f32 = 0.75 // How hard it last hit the floor, in metres a second, and how many times it has. impact: f32 = 0 hits: u32 = 0 } ``` The balls are entities with one DriftScript component, and a system in the same file moves them. Nothing in the script knows about the tools. ```ts /* What each panel reads. The inspector reads the entity world through an adapter; the console a ring of entries the page appends to; the profiler the frame's times and the GPU's. */ const selection = createSelection(); selectOnly(selection, entities[0] as number); const inspectable = entitiesInspectable(world, [Ball]); /* Five lines, which the console shows whole on a phone held sideways: the overlay does not scroll it yet, so a longer ring would show its oldest lines and hide the newest. */ const log = createLogRing(5); const ROW = 16; const consoleView = createConsoleView({ rowHeight: ROW }); consoleView.filter.minSeverity = level(flag('level', 'debug')); const history = createFrameHistory(120); const timings = createGpuPassTimings(); function panels() { return [ bindPanel( inspectorPanel, () => ({ world: inspectable }), createInspectorView({ selection, rowHeight: ROW }), ), bindPanel(consolePanel, () => ({ log }), consoleView), bindPanel( profilerPanel, () => ({ timings, history, residency: null }), createProfilerView({ rowHeight: ROW }), ), ]; } ``` `bindPanel(panel, world, view)` joins a panel to what it reads and to its view, the state that belongs to the panel itself. The `world` function is called on every build, so a panel always reads the current thing. Each panel reads its own shape. The inspector reads an `InspectableWorld`, which addresses a component by name, and `entitiesInspectable(world, types)` adapts an entity world to it, so a row built from a stale schema finds no component and writes nothing. The console reads a `LogRing`, the profiler reads pass timings, a `FrameHistory` and a texture residency table where there is one, and the network panel reads a session. The inspector's subject is a `Selection`. `selectOnly`, `addToSelection`, `toggleSelection` and `selectRange` change it, `primarySelection` answers the entity most recently added, and a field the selected entities disagree on shows `—`. ## The overlay ```ts /* Closed until F3. The overlay lays itself out in a column of its own space and paints through four calls, which here go to a 2D canvas over the stage. Where that space sits on the page is the page's choice: here, below the hint and above the switches, so the page's own controls stay clear. */ let side: 'left' | 'right' = flag('side', 'right') === 'left' ? 'left' : 'right'; let overlay: ToolsOverlay = makeOverlay(flag('open', 'no') === 'yes'); function makeOverlay(open: boolean): ToolsOverlay { return createToolsOverlay({ panels: panels(), key: 'F3', side, visible: open }); } const layer = document.querySelector('#tools'); const ink = layer?.getContext('2d') ?? null; const painter: OverlayPainter = { rect(x, y, w, h, colour) { if (ink === null) return; ink.fillStyle = colour; ink.fillRect(x, y, w, h); }, text(content, x, y, colour) { if (ink === null) return; ink.fillStyle = colour; ink.font = '12px ui-monospace, monospace'; ink.fillText(content, x + 8, y); }, clip(x, y, w, h) { if (ink === null) return; ink.save(); ink.beginPath(); ink.rect(x, y, w, h); ink.clip(); }, unclip() { ink?.restore(); }, }; let top = 0; function fit(): void { if (layer === null || ink === null) return; const scale = devicePixelRatio; const above = document.querySelector('#hint')?.getBoundingClientRect().bottom ?? 0; const below = document.querySelector('#controls')?.getBoundingClientRect().top ?? innerHeight; top = Math.round(above + 8); layer.width = Math.round(innerWidth * scale); layer.height = Math.round(innerHeight * scale); ink.setTransform(scale, 0, 0, scale, 0, top * scale); overlay.resize(innerWidth, Math.max(0, Math.round(below - 8) - top)); } addEventListener('resize', fit); ``` `createToolsOverlay` stacks the panels down one edge, `right` unless `side` says `left`, in a column 320 pixels wide unless `width` says otherwise, and opens and closes on `key`, F3 by default. It lays out in its own space from the top left, at the size `resize` gives it. Where that space sits on the page is the page's choice: the example moves it below its hint line with the painter's transform, and shifts pointer events by the same amount. It draws through four calls, a rectangle, a line of text, a clip and its end, and the page supplies them. A 2D canvas is one way, a sprite batch is another, and a test writes them into an array, which is how the package's own tests run with no graphics device. ## Input goes to the overlay first ```ts /* Every event goes to the overlay first; what it takes, the game never sees. */ addEventListener('keydown', (event) => { if (overlay.route(keyEvent(event.key, event.shiftKey, event.ctrlKey))) { event.preventDefault(); return; } if (event.key === 'Tab') { event.preventDefault(); const at = entities.indexOf(primarySelection(selection) ?? -1); selectOnly(selection, entities[(at + 1) % entities.length] as number); overlay.invalidate(); } else if (event.key === '[' || event.key === ']') { nudgeBounce(event.key === ']' ? 0.05 : -0.05); } else if (event.key === 'r' || event.key === 'R') { drop(); selectOnly(selection, entities[0] as number); appendLog(log, 'info', 'every ball dropped again'); overlay.invalidate(); } }); /* Pointer events in the overlay's space, which starts `top` pixels down the page. */ addEventListener('pointerdown', (event) => { if (overlay.route(pointerEvent('down', event.clientX, event.clientY - top, event.button))) event.preventDefault(); }); addEventListener('pointerup', (event) => { overlay.route(pointerEvent('up', event.clientX, event.clientY - top, event.button)); }); addEventListener( 'wheel', (event) => { if (overlay.route(wheelEvent(event.clientX, event.clientY - top, event.deltaX, event.deltaY))) event.preventDefault(); }, { passive: false }, ); ``` `route` answers whether the overlay took an event, and an event it took is not the game's. Its key is answered whether the overlay is open or closed. While it is closed it refuses everything else, so a game that never presses F3 pays a few comparisons an event. While it is open, Ctrl+Z undoes and Ctrl+Y redoes, a pointer goes to the panel under it in that panel's own coordinates, and other keys go to the panel last clicked. Ctrl+Shift+Z is meant to redo as well, and does not: a browser reports its key as a capital `Z`, which the overlay does not match. ## An edit is a command ```ts /* An edit is a command: pushed onto the overlay's stack, it is applied once and can be taken back with Ctrl+Z while the overlay is open. */ function nudgeBounce(by: number): void { const ball = primarySelection(selection); if (ball === null) return; const now = world.read(ball, Ball, 'bounce') as number; const next = Math.round(Math.min(0.95, Math.max(0, now + by)) * 100) / 100; const command = setFieldCommand(inspectable, [ball], 'Ball', ['bounce'], [next]); if (command === null) return; overlay.undo.push(command); appendLog( log, 'debug', `ball ${entities.indexOf(ball) + 1} bounce ${now.toFixed(2)} to ${next.toFixed(2)}`, ); overlay.invalidate(); } ``` A panel is handed its world read-only and can change it only by returning a `Command`, an object that can `apply` itself and `revert` itself. `setFieldCommand(world, entities, component, fields, values)` makes one that writes a field across the whole selection, and the three fields of a vector together, as one entry, and remembers each entity's own previous value. It answers `null` where an entity lacks the component. `addComponentCommand` and `removeComponentCommand` are the same for a whole component. `overlay.undo.push(command)` applies it once, and Ctrl+Z reverts it. In the example, `]` twice took the first ball's bounce from 0.55 to 0.65, and Ctrl+Z put it back to 0.60. `createUndoStack(limit)` is the same stack for a game that keeps its own, and a command with a `merge` method can absorb the one after it, so a drag of sixty small moves undoes as one. The inspector shows rows and does not yet edit them: its `route` answers `null`. A game edits through `setFieldCommand` as the example does, and the edit is still undoable. Its rows also print a 32-bit float field with the digits of its storage, `0.550000011920929` for 0.55. ## The console ```ts /* What the balls did this step, said once each. Every entry names where the rule lives, so a click on it in the console moves the source cursor there. */ const seen = new Map(); function report(): void { entities.forEach((ball, index) => { const hits = world.read(ball, Ball, 'hits') as number; const resting = (world.read(ball, Ball, 'vy') as number) === 0; const before = seen.get(ball) ?? { hits: 0, resting: false }; if (hits > before.hits) { const impact = world.read(ball, Ball, 'impact') as number; const severity: Severity = impact > 6 ? 'warn' : 'info'; appendLog( log, severity, `ball ${index + 1} hit the floor at ${impact.toFixed(1)} m/s`, 'examples/tools/balls.drs', 26, ); } if (resting && !before.resting) appendLog(log, 'info', `ball ${index + 1} has come to rest`); seen.set(ball, { hits, resting }); }); } ``` `appendLog(log, severity, text, file, line)` writes into a ring of fixed length, and the oldest entry goes when it is full. A repeat of the newest entry is counted, shown as `(3)` after it, and a repeat of anything older is written again, so the order stays the order things happened in. `consoleView.filter` holds a `minSeverity`, one of `debug`, `info`, `warn` and `error`, and a `text` matched without regard to case; the example's console switch sets the first. An entry may name a file and a line. Clicking it moves `consoleView.cursor` there, as a command, so an editor can open the file at the line, and undo takes the cursor back to where it was. The overlay does not scroll the console yet. The console keeps a scroll position that follows the newest entry, and the overlay draws the list from its top, so a long ring shows its oldest lines and hides the newest. The example keeps a ring of five, which the console shows whole. ## The profiler ```ts /* The frame's time from the clock, and the GPU's in the engine's three brackets: the renderer opens shadows and reflection itself, and the game opens rest around the rest of its drawing. A sample arrives a few frames after its frame, and never where the device cannot time. */ pushFrame(history, now - last); meter.sample((now - last) / 1000, now); last = now; const timer = renderer.gpuTimer; timer.beginFrame(); drawShadows(); renderer.beginFrame(CLEAR); timer.begin('rest'); drawScene(); timer.end(); renderer.endFrame(); timer.endFrame(); const sample = timer.poll(); if (sample !== null) recordGpuSample(timings, sample); ``` `pushFrame(history, ms)` keeps the last frames' times, and the profiler shows their mean. The GPU rows come from the renderer's own timer, in three brackets: `shadows` and `reflection`, which the renderer opens itself, and `rest`, which the game opens around everything else it draws. `gpuTimer.poll()` answers a sample a few frames after the frame it measured, since reading one sooner would stall the GPU it is measuring, and `recordGpuSample` writes it into `createGpuPassTimings()`. Both backends time one frame in eight. WebGL2 needs the `EXT_disjoint_timer_query_webgl2` extension, which most mobile browsers lack. WebGPU needs the adapter's `timestamp-query` feature and `gpuTiming: true` in the quality settings, because timing attaches a timestamp block to every render pass in the frame, and the example sets it. Where a row has no measurement it shows `—`. A measured zero shows `0.00`, so a pass that was never timed cannot pass for a free one. ## Painting it ```ts /* The overlay over all of it, rebuilt each frame because the profiler changes every frame. */ if (ink !== null) ink.clearRect(0, -top, innerWidth, innerHeight); overlay.invalidate(); overlay.frame(now); paintOverlay(painter, overlay); ``` `invalidate` says something the overlay shows has changed, and `frame` lays it out again only then. The profiler changes every frame, so the example invalidates every frame. While the overlay is closed, `frame` returns before it builds anything and `paintOverlay` paints nothing. `overlay.sites()` answers where each panel sits. Each panel is drawn on a dark background under a title row `PANEL_TITLE_HEIGHT` pixels tall, and the panel's own space starts below that row. ## The network panel ```ts /** * A lockstep session as the network panel reads it: handed over as it is. The loop the game made is * read beside it for how far each tick rewound, which the session does not count. */ export function networkTools( session: LockstepSession, loop: RewindLoop, snapshotBytes: number, ): { panel: PanelBinding; afterTick(): void } { const recorder = createSessionRecorder(); const view = createNetworkView({}); let replayed = loop.stats.replayedTicks; return { panel: bindPanel( networkPanel, () => ({ session: sessionReadout(session, recorder, snapshotBytes) }), view, ), /** Once a tick, after the session has advanced: any new disagreement, and how far it rewound. */ afterTick() { observeSession(recorder, session); const now = loop.stats.replayedTicks; pushRollback(view.rollback, now - replayed); replayed = now; }, }; } ``` The network panel shows the input delay, the number of peers, how many snapshots the rewind window holds and what they weigh, how deep each recent tick rewound, and the first tick two peers stopped agreeing on, with both fingerprints. Where they agree it says so in words, and where there is no session it says `No session`, so agreement and nobody checking never look alike. A session's `desync` holds the same disagreement on every frame until the next one, so `observeSession` records one only when its tick or peer is new, and keeps the last 32. The size of a snapshot is the game's to supply, because the rewind loop does not know what it stores. Where the game hashes each component as well, `sessionReadout` takes both sides' hashes as its last argument and the panel names the components that differ. [Networking and rollback](https://driftengine.dev/docs/systems/networking) covers sessions and fingerprints. A `LockstepSession` is passed as it is: `rewindDepth` answers how many snapshots its loop holds. A game that keeps its own record of a session can still hand over a shape with `participants`, `inputDelay`, `desync` and `loop: { depth }`, which is `SessionLike`. ## The frame meter `new FpsMeter(options)` adds an element to the page, `#fps-meter` unless `id` says otherwise, and `sample(seconds, nowMs)` once a frame keeps it current, in the profiler code above. It shows the rate, the mean frame time and the slowest frame over the last 60 frames, rewrites its text at most every 250 milliseconds, and adds the class `over-budget` while the slowest frame is more than one and a half times `frameBudgetMs`, 16.7 by default. `fps`, `meanMs` and `worstMs` answer the numbers it last showed, for a game that wants them as well. ## The contact probe ```ts /** * What is around the player, into the console, when a key asks. The reports are filled in place, * so asking every frame allocates nothing but the text. */ const reports = createContactReports(); const scratch = new Int32Array(256); export function logContacts(colliders: ColliderSet, player: Aabb, log: LogRing): void { const count = describeContacts(colliders, player, 0.25, scratch, reports); if (count === 0) appendLog(log, 'info', 'no collider within 25 cm'); for (let at = 0; at < count; at += 1) { const near = reports[at] as ContactReport; /* Overlap on all three axes is inside, and the smallest is the way out. */ const inside = near.depthX > 0 && near.depthY > 0 && near.depthZ > 0; const depth = Math.min(near.depthX, near.depthY, near.depthZ); appendLog( log, inside ? 'warn' : 'info', inside ? `collider ${near.index} is ${(depth * 100).toFixed(1)} cm inside` : `collider ${near.index} is ${(near.distanceM * 100).toFixed(1)} cm away`, ); } } ``` `describeContacts(colliders, box, radius, scratch, reports)` describes every collider overlapping a box or within `radius` of it, and answers how many reports it filled. Each report holds the collider's bounds and its overlap with the box along each axis, positive inside and negative for a gap, so a body 5 cm into a floor and one 5 cm above it read differently, which a single distance would not show. `distanceM` is the straight line between the two boxes and is zero exactly when they overlap on all three axes. A collider that is a hull says so in `hull`, and its box is then only the broad phase. Reports come in the order the spatial hash finds them; sort by `distanceM` to show them nearest first. `createContactReports()` makes `CONTACT_LIMIT` of them, 32, to be filled again on every call. ## Leaving the tools out of a release There is no flag. A build that imports `@driftengine/tools` contains it, and one that does not contains none of it, which the engine's size gate checks: no other package's size changes because this one exists. A game that wants the tools in development builds only imports them behind its bundler's dead-code elimination, as it would any optional dependency. --- # Coming from Three.js Coming from another engine. https://driftengine.dev/docs/coming-from/threejs What a Three.js scene, renderer, animation loop, geometry, light and loader become in DriftEngine, with the same program written in both. Checked against Three.js r186, released on 24 September 2026, and its manual and source at that tag, on 3 October 2026. Three.js is a library for drawing 3D on the web, and a game built on it chooses its own loop, physics, input and audio. DriftEngine is a game engine: the renderer comes with a fixed-step loop, its own physics, entities, input, audio, networking and a scripting language for the rules. Most of what a Three.js developer knows carries over directly. The largest difference is that no scene object holds what is drawn: a program keeps its meshes and nodes, and draws them every frame. ## The first program The cube from the Three.js manual's first chapter, on its WebGPU renderer, lit and turning: ```js import * as THREE from 'three/webgpu'; const renderer = new THREE.WebGPURenderer(); renderer.setSize(innerWidth, innerHeight); document.body.appendChild(renderer.domElement); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 1000); camera.position.z = 3; const light = new THREE.DirectionalLight(0xffffff, 3); light.position.set(0.4, 0.8, 0.3); scene.add(light); const cube = new THREE.Mesh( new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x33bf59 }), ); scene.add(cube); renderer.setAnimationLoop((time) => { cube.rotation.y = (time / 1000) * 1.2; renderer.render(scene, camera); }); ``` The same program here: ```ts /** The background, picked by eye and so stated through `srgbColor`: the renderer grades a clear. */ const CLEAR = srgbColor(0.3, 0.3, 0.7); /** A lit box on a canvas, turning. Every piece is a value the program holds. */ export async function spinningBox(canvas: HTMLCanvasElement): Promise { /* WebGPU where the browser has it, WebGL2 where it does not; `backend` says which. */ const { renderer, backend } = await createRenderer(canvas, {}); console.info(`drawn by ${backend}`); renderer.resize(); addEventListener('resize', () => renderer.resize()); /* The light points toward the sun, and colours are 0 to 1. */ const environment = createEnvironment({ directionalDir: [0.4, 0.8, 0.3], directionalColor: [1, 0.97, 0.9], ambient: [0.2, 0.22, 0.27], }); /* A box by its centre and its half extents: this one is one metre on a side. */ const box = renderer.createMesh( new MeshBuilder().addBox([0, 0, 0], [0.5, 0.5, 0.5], [0.2, 0.75, 0.35]).build(), ); const node = new SceneNode(); const camera = new Camera(); camera.fovYDeg = 60; camera.position[2] = 3; camera.lookAt(0, 0, 0); /* The rules run sixty times a second, whatever the display does. Drawing happens once a frame, between the last two steps by `alpha`. */ let angle = 0; let previous = 0; startLoop({ simulate(dt) { previous = angle; angle += dt * 1.2; }, render(alpha) { node.setRotationAxisAngle(0, 1, 0, previous + (angle - previous) * alpha); node.updateWorld(); camera.updateMatrices(canvas.width / Math.max(1, canvas.height)); renderer.beginFrame(CLEAR); renderer.bindMeshPass(camera, environment); renderer.drawMesh(box, node.worldMatrix); renderer.endFrame(); }, }); } ``` Line by line: - **The renderer.** `createRenderer(canvas)` takes the canvas the page already has and is awaited, because asking for a WebGPU device is asynchronous. Like `THREE.WebGPURenderer`, it uses WebGPU where the browser has it and WebGL2 where it does not; `backend` says which it got. - **The scene.** There is no `THREE.Scene` to add things to. A `SceneNode` is the nearest thing to a `THREE.Object3D`, a transform with a parent, and the frame draws a mesh at a node's `worldMatrix`. A mesh the frame stops drawing is gone, and there is nothing to remove. - **The box.** `THREE.BoxGeometry(1, 1, 1)` takes the full width, height and depth. `addBox` takes a centre and **half** extents, so the same cube is `[0.5, 0.5, 0.5]`. - **The material.** The colour here is vertex data, which `MeshBuilder` writes for every shape. A textured surface is set before a draw with `renderer.setMaterial`, which [Materials](https://driftengine.dev/docs/rendering/materials) covers. - **The light.** A `THREE.DirectionalLight` shines from its `position` toward its `target`. `directionalDir` points the other way, from the scene toward the light, so a light placed at `(0.4, 0.8, 0.3)` aimed at the origin is `directionalDir: [0.4, 0.8, 0.3]`. - **The camera.** Both cameras take a vertical field of view in degrees. The aspect ratio is given to `updateMatrices` each frame, so a resize needs nothing else. - **The loop.** `setAnimationLoop` calls back once per display refresh with the time. `startLoop` calls `simulate` sixty times a second, however fast the display is, and `render` once per displayed frame with `alpha`, how far the display has got between the last two steps. Rules go in `simulate`, and drawing goes in `render`. [The loop](https://driftengine.dev/docs/start/the-loop) explains why, and [Hello world](https://driftengine.dev/docs/start/hello-world) is this program in full, with its rule in DriftScript. ## Conventions | | Three.js | DriftEngine | | ------------------- | ---------------------------------------------------------- | ----------------------------------------------------- | | Axes | Y up, a camera looks down its negative Z | the same, in metres and seconds | | A box | full width, height and depth | a centre and half extents | | A rotation | `rotation` in Euler radians, or `quaternion` | a quaternion, `x, y, z, w`, or `setRotationAxisAngle` | | A directional light | from `position` toward `target` | `directionalDir`, toward the light | | A matrix | `elements` column-major; `set()` takes rows | a column-major `Float32Array` of sixteen | | A colour | a hex number or a `THREE.Color` | `[r, g, b]` from 0 to 1 | | Time | `THREE.Timer`, since `THREE.Clock` is deprecated from r183 | the loop's `dt`, a fixed sixtieth of a second | [Coordinates and units](https://driftengine.dev/docs/concepts/coordinates) has the rest, including how a world larger than single precision stays exact. ## What each thing is called | Three.js | DriftEngine | Where | | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `THREE.WebGPURenderer`, `THREE.WebGLRenderer` | `createRenderer`, one renderer with two backends | [Backends](https://driftengine.dev/docs/concepts/backends) | | `THREE.Scene`, `THREE.Object3D`, `THREE.Group` | `SceneNode`, parented with `attachChild` | [The scene graph](https://driftengine.dev/docs/concepts/scene-graph) | | `THREE.BufferGeometry`, the geometry classes | `MeshBuilder`, uploaded once with `renderer.createMesh` | [Meshes](https://driftengine.dev/docs/rendering/meshes) | | `THREE.MeshStandardMaterial` | `renderer.setMaterial`, with colour, packed ORM, normal and emissive maps | [Materials](https://driftengine.dev/docs/rendering/materials) | | `THREE.MeshPhysicalMaterial.anisotropy`, `alphaHash` | a material's `model` (`anisotropicModel`, and hair, skin and eye models besides), and `cutoutMode: 'dithered'` | [Materials](https://driftengine.dev/docs/rendering/materials) | | `THREE.CompressedTexture` | a `CompressedTextureSource` of BC blocks, where `renderer.compressedFormats` has the format | [Materials](https://driftengine.dev/docs/rendering/materials) | | `THREE.InstancedMesh` | instanced draws | [Instancing](https://driftengine.dev/docs/rendering/instancing) | | `THREE.PointLight`, `THREE.SpotLight` | point and spot lights, chosen per frame | [Lights](https://driftengine.dev/docs/rendering/lights) | | shadow maps on a light | the sun's shadow map, and shadows from point and spot lights | [Shadows](https://driftengine.dev/docs/rendering/shadows) | | post-processing passes | bloom, ambient occlusion and antialiasing, and passes of your own | [Post-processing](https://driftengine.dev/docs/rendering/post-processing), [Custom passes](https://driftengine.dev/docs/rendering/custom-passes) | | `GLTFLoader` | a `.drft` container baked ahead of time, or a model converted in a worker | [Importing models](https://driftengine.dev/docs/content/importing-models) | | `THREE.AnimationMixer` | clips, blend trees and IK | [Animation](https://driftengine.dev/docs/simulation/animation) | | `THREE.Raycaster` | a ray through a pixel against meshes registered for picking, and rays against the physics world | [Picking](https://driftengine.dev/docs/rendering/picking), [Queries](https://driftengine.dev/docs/simulation/queries) | | a physics library beside it | `PhysicsWorld`, the engine's own | [Rigid bodies](https://driftengine.dev/docs/simulation/rigid-bodies) | | `THREE.Audio`, `THREE.PositionalAudio` | a mix, placed sounds and rooms | [Audio](https://driftengine.dev/docs/content/audio) | | `renderer.xr` | WebXR sessions, the head, controllers and hands; drawing into a headset is not built yet | [XR](https://driftengine.dev/docs/interface/xr) | ## Loading a model ```js import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; const gltf = await new GLTFLoader().loadAsync('models/lantern.glb'); scene.add(gltf.scene); ``` ```ts /** * A model baked to a `.drft` ahead of time, streamed in a few parts a frame. A draw function is * what the game calls inside its frame, once the camera and the light are bound. */ export function streamedModel(renderer: RendererApi, url: string) { const loader = new DrftLoader(renderer); void loader.load(url, { footprint: 1, height: 1.5 }); const at = new SceneNode(); at.updateWorld(); return function draw(dt: number): void { loader.update(dt); const textures = loader.textures; const image = (index: number) => (index >= 0 ? (textures?.at(index) ?? null) : null); for (const part of loader.parts) { renderer.setMaterial({ albedo: image(part.albedo), orm: image(part.orm), normal: image(part.normal), emissive: image(part.emissive), }); renderer.drawMesh(part.mesh, at.worldMatrix); } renderer.setMaterial(null); }; } ``` `GLTFLoader` reads a glTF file when the page loads it. Here a model is usually baked once, ahead of time, into a `.drft` container whose bytes are already laid out the way a GPU takes them, and `DrftLoader` streams it in a few parts a frame, so it builds up on screen instead of arriving after a wait. A game that has to open a model the player supplies converts it in a worker, which [Importing models](https://driftengine.dev/docs/content/importing-models) shows with a glTF, an OBJ and an STL. A load never throws: `progress` says what happened. ## Physics Three.js has no physics of its own; its examples bring Ammo, Jolt or Rapier in through addons. The engine has one, written for it, and deterministic: two runs of the same inputs reach the same state tick for tick, checked by a fingerprint, which is what [lockstep networking](https://driftengine.dev/docs/systems/networking) and replays rest on. ```ts /** * A ball dropped on a floor. The world belongs to the game, steps inside `simulate`, and is read * back into a node to draw. */ export function fallingBall() { const world = new PhysicsWorld(); world.addBody({ type: BODY_STATIC, shape: boxShape(5, 0.5, 5), y: -0.5 }); const ball = world.addBody({ type: BODY_DYNAMIC, shape: sphereShape(1), y: 4, restitution: 0.75, }); const node = new SceneNode(); return { simulate(dt: number): void { world.step(dt); }, place(): SceneNode { const b = world.bodies; node.setPosition(b.posX[ball] ?? 0, b.posY[ball] ?? 0, b.posZ[ball] ?? 0); node.rotation[0] = b.rotX[ball] ?? 0; node.rotation[1] = b.rotY[ball] ?? 0; node.rotation[2] = b.rotZ[ball] ?? 0; node.rotation[3] = b.rotW[ball] ?? 1; node.markMoved(); node.updateWorld(); return node; }, }; } ``` The world steps inside `simulate`, on the loop's fixed step, and the frame reads the bodies back. A body is an index into flat arrays of positions and rotations, so reading every body costs no allocation. ## What works differently - **The frame is a list of calls.** `beginFrame`, `bindMeshPass` with a camera and an environment, any number of draws, `endFrame`. Order and visibility are the program's, which is also why [culling](https://driftengine.dev/docs/concepts/scene-graph) is something a program asks for. - **Quality is decided when the renderer is made.** Shadows, anti-aliasing, the output transform and most other options size GPU memory, so changing one means making a new renderer. [Render quality](https://driftengine.dev/docs/concepts/quality) lists them. - **Emissive light has a switch.** Nothing glows, whatever its emissive colour, until the environment's `nightFactor` is above zero. The name is about night scenes, not the clock. - **Rules live in DriftScript.** A `.drs` file is imported like a module and reloads in place while the game runs, with nothing reset. [DriftScript in a game](https://driftengine.dev/docs/scripting/driftscript) covers what belongs in one. --- # Coming from Babylon.js Coming from another engine. https://driftengine.dev/docs/coming-from/babylonjs What a Babylon.js engine, scene, render loop, mesh builder, light, loader and Havok body become in DriftEngine, with the same program written in both. Checked against Babylon.js 9.29.0, released on 1 October 2026, and its documentation and source at that version, on 3 October 2026. Babylon.js and DriftEngine are both game engines for the web, with a renderer on WebGPU and WebGL2, physics, audio, input and a debugging overlay, so most of what a Babylon.js developer knows has a counterpart here. Three things change the most. The engine is right-handed. No scene object holds what is drawn: a program keeps its meshes and nodes, and draws them every frame. And the game's rules run on a fixed step, sixty times a second, separately from drawing. ## The first program A lit box, turning, from the shape of the Babylon.js getting-started chapter: ```js import * as BABYLON from '@babylonjs/core'; const canvas = document.querySelector('#stage'); const engine = await BABYLON.EngineFactory.CreateAsync(canvas); addEventListener('resize', () => engine.resize()); const scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color4(0.3, 0.3, 0.7, 1); const camera = new BABYLON.FreeCamera('camera', new BABYLON.Vector3(0, 0, -3), scene); camera.setTarget(BABYLON.Vector3.Zero()); camera.fov = Math.PI / 3; const light = new BABYLON.DirectionalLight('sun', new BABYLON.Vector3(-0.4, -0.8, 0.3), scene); const box = BABYLON.MeshBuilder.CreateBox('box', { size: 1 }, scene); const material = new BABYLON.StandardMaterial('green', scene); material.diffuseColor = new BABYLON.Color3(0.2, 0.75, 0.35); box.material = material; engine.runRenderLoop(() => { box.rotation.y += (engine.getDeltaTime() / 1000) * 1.2; scene.render(); }); ``` The same program here: ```ts /** The background, picked by eye and so stated through `srgbColor`: the renderer grades a clear. */ const CLEAR = srgbColor(0.3, 0.3, 0.7); /** A lit box on a canvas, turning. Every piece is a value the program holds. */ export async function spinningBox(canvas: HTMLCanvasElement): Promise { /* WebGPU where the browser has it, WebGL2 where it does not; `backend` says which. */ const { renderer, backend } = await createRenderer(canvas, {}); console.info(`drawn by ${backend}`); renderer.resize(); addEventListener('resize', () => renderer.resize()); /* The light points toward the sun, and colours are 0 to 1. */ const environment = createEnvironment({ directionalDir: [0.4, 0.8, 0.3], directionalColor: [1, 0.97, 0.9], ambient: [0.2, 0.22, 0.27], }); /* A box by its centre and its half extents: this one is one metre on a side. */ const box = renderer.createMesh( new MeshBuilder().addBox([0, 0, 0], [0.5, 0.5, 0.5], [0.2, 0.75, 0.35]).build(), ); const node = new SceneNode(); const camera = new Camera(); camera.fovYDeg = 60; camera.position[2] = 3; camera.lookAt(0, 0, 0); /* The rules run sixty times a second, whatever the display does. Drawing happens once a frame, between the last two steps by `alpha`. */ let angle = 0; let previous = 0; startLoop({ simulate(dt) { previous = angle; angle += dt * 1.2; }, render(alpha) { node.setRotationAxisAngle(0, 1, 0, previous + (angle - previous) * alpha); node.updateWorld(); camera.updateMatrices(canvas.width / Math.max(1, canvas.height)); renderer.beginFrame(CLEAR); renderer.bindMeshPass(camera, environment); renderer.drawMesh(box, node.worldMatrix); renderer.endFrame(); }, }); } ``` Line by line: - **The engine.** `BABYLON.EngineFactory.CreateAsync` picks WebGPU where the browser has it and WebGL where it does not. `createRenderer(canvas)` does the same, and `backend` says which it got. One renderer object answers for both, and nothing in a game branches on the backend. - **The scene.** There is no `BABYLON.Scene`. A `SceneNode` is the nearest thing to a `BABYLON.TransformNode`, a transform with a parent, and the frame draws a mesh at a node's `worldMatrix`. A mesh the frame stops drawing is gone, and there is nothing to dispose from a scene. - **The box.** `BABYLON.MeshBuilder.CreateBox` takes a full `size`. `addBox` takes a centre and **half** extents, so the same box is `[0.5, 0.5, 0.5]`. - **The material.** The colour here is vertex data, which `MeshBuilder` writes for every shape. A textured surface is set before a draw with `renderer.setMaterial`, closest to a `BABYLON.PBRMaterial`, which [Materials](https://driftengine.dev/docs/rendering/materials) covers. - **The light.** A `BABYLON.DirectionalLight` is given the direction its light travels. `directionalDir` points the other way, from the scene toward the light, and its Z has the other sign because of the handedness: the light above becomes `directionalDir: [0.4, 0.8, 0.3]`. - **The camera.** Both cameras keep the vertical field of view fixed by default. Babylon.js gives it in radians, `fovYDeg` in degrees. The camera here sits at positive Z looking toward negative Z, which is the Babylon.js camera at negative Z, mirrored by the handedness. - **The loop.** `runRenderLoop` calls back once per displayed frame, and a game scales its motion by `getDeltaTime()`. `startLoop` calls `simulate` sixty times a second with a fixed `dt`, however fast the display is, and `render` once per displayed frame with `alpha`, how far the display has got between the last two steps. Rules go in `simulate`, drawing in `render`. [The loop](https://driftengine.dev/docs/start/the-loop) explains why, and [Hello world](https://driftengine.dev/docs/start/hello-world) is this program in full, with its rule in DriftScript. ## Conventions | | Babylon.js | DriftEngine | | ------------------- | --------------------------------------------------------------- | ----------------------------------------------------------- | | Handedness | left-handed by default; `scene.useRightHandedSystem` changes it | right-handed: X right, Y up, a camera looks down negative Z | | Moving a scene over | negate every Z, or set `scene.useRightHandedSystem` | nothing | | A box | a full `size`, or `width`, `height` and `depth` | a centre and half extents | | A rotation | `rotation` in Euler radians, or `rotationQuaternion` | a quaternion, `x, y, z, w`, or `setRotationAxisAngle` | | A directional light | the direction the light travels | `directionalDir`, toward the light | | Field of view | `fov` in radians, vertical by default | `fovYDeg`, vertical, in degrees | | A colour | `BABYLON.Color3` and `BABYLON.Color4` | `[r, g, b]` from 0 to 1 | | Time | `engine.getDeltaTime()`, in milliseconds | the loop's `dt`, a fixed sixtieth of a second | [Coordinates and units](https://driftengine.dev/docs/concepts/coordinates) has the rest, including how a world larger than single precision stays exact. ## What each thing is called | Babylon.js | DriftEngine | Where | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | | `BABYLON.Engine`, `BABYLON.WebGPUEngine` | `createRenderer`, one renderer with two backends | [Backends](https://driftengine.dev/docs/concepts/backends) | | `BABYLON.Scene`, `BABYLON.TransformNode` | `SceneNode`, parented with `attachChild` | [The scene graph](https://driftengine.dev/docs/concepts/scene-graph) | | `BABYLON.MeshBuilder` | `MeshBuilder`, uploaded once with `renderer.createMesh` | [Meshes](https://driftengine.dev/docs/rendering/meshes) | | `BABYLON.PBRMaterial` | `renderer.setMaterial`, with colour, packed ORM, normal and emissive maps | [Materials](https://driftengine.dev/docs/rendering/materials) | | `BABYLON.PBRMaterial.anisotropy`, `subSurface` scattering | `anisotropicModel`, and `skinModel` with `skinScattering: 'screen-space'`; hair and eye models besides | [Materials](https://driftengine.dev/docs/rendering/materials) | | eight bone influences, `matricesIndicesExtra` | `joints2` and `weights2` beside `joints` and `weights` | [Meshes](https://driftengine.dev/docs/rendering/meshes) | | thin instances, instanced meshes | instanced draws | [Instancing](https://driftengine.dev/docs/rendering/instancing) | | `BABYLON.PointLight`, `BABYLON.SpotLight` | point and spot lights, chosen per frame | [Lights](https://driftengine.dev/docs/rendering/lights) | | `BABYLON.ShadowGenerator`, cascaded shadows | the sun's shadow map, and shadows from point and spot lights | [Shadows](https://driftengine.dev/docs/rendering/shadows) | | the default rendering pipeline | bloom, ambient occlusion and antialiasing, and passes of your own | [Post-processing](https://driftengine.dev/docs/rendering/post-processing), [Custom passes](https://driftengine.dev/docs/rendering/custom-passes) | | `BABYLON.ImportMeshAsync`, asset containers | a `.drft` container baked ahead of time, or a model converted in a worker | [Importing models](https://driftengine.dev/docs/content/importing-models) | | animation groups, skeletons | clips, blend trees and IK | [Animation](https://driftengine.dev/docs/simulation/animation) | | `scene.pick` | a ray through a pixel against meshes registered for picking | [Picking](https://driftengine.dev/docs/rendering/picking) | | the Havok plugin, `BABYLON.PhysicsAggregate` | `PhysicsWorld`, the engine's own | [Rigid bodies](https://driftengine.dev/docs/simulation/rigid-bodies) | | Babylon.js GUI | interface trees with layout, focus and themes | [Interface](https://driftengine.dev/docs/interface/interface) | | the Inspector | the in-game tools overlay | [In-game tools](https://driftengine.dev/docs/tools/in-game-tools) | | WebXR experience helpers | WebXR sessions, the head, controllers and hands; drawing into a headset is not built yet | [XR](https://driftengine.dev/docs/interface/xr) | ## Loading a model ```js import { registerBuiltInLoaders } from '@babylonjs/loaders/dynamic'; registerBuiltInLoaders(); const result = await BABYLON.ImportMeshAsync('models/lantern.glb', scene); ``` ```ts /** * A model baked to a `.drft` ahead of time, streamed in a few parts a frame. A draw function is * what the game calls inside its frame, once the camera and the light are bound. */ export function streamedModel(renderer: RendererApi, url: string) { const loader = new DrftLoader(renderer); void loader.load(url, { footprint: 1, height: 1.5 }); const at = new SceneNode(); at.updateWorld(); return function draw(dt: number): void { loader.update(dt); const textures = loader.textures; const image = (index: number) => (index >= 0 ? (textures?.at(index) ?? null) : null); for (const part of loader.parts) { renderer.setMaterial({ albedo: image(part.albedo), orm: image(part.orm), normal: image(part.normal), emissive: image(part.emissive), }); renderer.drawMesh(part.mesh, at.worldMatrix); } renderer.setMaterial(null); }; } ``` A model is usually baked once, ahead of time, into a `.drft` container whose bytes are already laid out the way a GPU takes them, and `DrftLoader` streams it in a few parts a frame, so it builds up on screen instead of arriving after a wait. A game that has to open a model the player supplies converts it in a worker, which [Importing models](https://driftengine.dev/docs/content/importing-models) shows with a glTF, an OBJ and an STL. A load never throws: `progress` says what happened. ## Physics ```js import HavokPhysics from '@babylonjs/havok'; const havok = await HavokPhysics(); scene.enablePhysics(new BABYLON.Vector3(0, -9.8, 0), new BABYLON.HavokPlugin(true, havok)); const sphere = BABYLON.MeshBuilder.CreateSphere('ball', { diameter: 2 }, scene); sphere.position.y = 4; new BABYLON.PhysicsAggregate(sphere, BABYLON.PhysicsShapeType.SPHERE, { mass: 1, restitution: 0.75 }, scene); const ground = BABYLON.MeshBuilder.CreateGround('ground', { width: 10, height: 10 }, scene); new BABYLON.PhysicsAggregate(ground, BABYLON.PhysicsShapeType.BOX, { mass: 0 }, scene); ``` ```ts /** * A ball dropped on a floor. The world belongs to the game, steps inside `simulate`, and is read * back into a node to draw. */ export function fallingBall() { const world = new PhysicsWorld(); world.addBody({ type: BODY_STATIC, shape: boxShape(5, 0.5, 5), y: -0.5 }); const ball = world.addBody({ type: BODY_DYNAMIC, shape: sphereShape(1), y: 4, restitution: 0.75, }); const node = new SceneNode(); return { simulate(dt: number): void { world.step(dt); }, place(): SceneNode { const b = world.bodies; node.setPosition(b.posX[ball] ?? 0, b.posY[ball] ?? 0, b.posZ[ball] ?? 0); node.rotation[0] = b.rotX[ball] ?? 0; node.rotation[1] = b.rotY[ball] ?? 0; node.rotation[2] = b.rotZ[ball] ?? 0; node.rotation[3] = b.rotW[ball] ?? 1; node.markMoved(); node.updateWorld(); return node; }, }; } ``` A physics body is attached to nothing. The world belongs to the game, steps inside `simulate` on the loop's fixed step, and the frame reads the bodies back into whatever it draws them with, here a node. The engine's physics is its own and deterministic: two runs of the same inputs reach the same state tick for tick, checked by a fingerprint, which is what [lockstep networking](https://driftengine.dev/docs/systems/networking) and replays rest on. Babylon.js's `deterministicLockstep` engine option runs animations on a fixed step too; here the fixed step is the only loop there is. ## What works differently - **The frame is a list of calls.** `beginFrame`, `bindMeshPass` with a camera and an environment, any number of draws, `endFrame`. Order and visibility are the program's, which is also why [culling](https://driftengine.dev/docs/concepts/scene-graph) is something a program asks for. - **Quality is decided when the renderer is made.** Shadows, anti-aliasing, the output transform and most other options size GPU memory, so changing one means making a new renderer. [Render quality](https://driftengine.dev/docs/concepts/quality) lists them. - **Emissive light has a switch.** Nothing glows, whatever its emissive colour, until the environment's `nightFactor` is above zero. The name is about night scenes, not the clock. - **Rules live in DriftScript.** A `.drs` file is imported like a module and reloads in place while the game runs, with nothing reset. [DriftScript in a game](https://driftengine.dev/docs/scripting/driftscript) covers what belongs in one. --- # Coming from PlayCanvas Coming from another engine. https://driftengine.dev/docs/coming-from/playcanvas What a PlayCanvas application, entity, component, script, light, asset and rigid body become in DriftEngine, with the same program written in both. Checked against the PlayCanvas engine 2.23.0, released on 1 October 2026, and its user manual and source at that version, on 3 October 2026. This page is about the engine used from code; the PlayCanvas Editor is outside its scope. PlayCanvas and DriftEngine are both game engines for the web, with a renderer on WebGPU and WebGL2, physics stepped at a fixed rate, audio, input and Gaussian splats, and both keep the same axes: Y up and a forward of negative Z. Two things change the most. No scene graph of entities holds what is drawn: a program keeps its meshes and nodes, and draws them every frame. And behaviour is written as DriftScript systems over components, where PlayCanvas attaches script classes to entities. ## The first program The spinning box from the PlayCanvas guide to using the engine without the Editor, with a colour and a directional light: ```js import * as pc from 'playcanvas'; const canvas = document.getElementById('application'); const device = await pc.createGraphicsDevice(canvas, { deviceTypes: [pc.DEVICETYPE_WEBGPU] }); const options = new pc.AppOptions(); options.graphicsDevice = device; options.componentSystems = [pc.RenderComponentSystem, pc.CameraComponentSystem, pc.LightComponentSystem]; options.resourceHandlers = [pc.TextureHandler, pc.ContainerHandler]; const app = new pc.AppBase(canvas); app.init(options); app.setCanvasResolution(pc.RESOLUTION_AUTO); app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW); app.start(); addEventListener('resize', () => app.resizeCanvas()); const camera = new pc.Entity(); camera.addComponent('camera', { clearColor: new pc.Color(0.3, 0.3, 0.7), fov: 60 }); camera.setPosition(0, 0, 3); app.root.addChild(camera); const light = new pc.Entity(); light.addComponent('light', { type: 'directional' }); light.setEulerAngles(45, 45, 0); app.root.addChild(light); const material = new pc.StandardMaterial(); material.diffuse = new pc.Color(0.2, 0.75, 0.35); material.update(); const box = new pc.Entity(); box.addComponent('render', { type: 'box', material }); app.root.addChild(box); app.on('update', (dt) => box.rotate(0, 70 * dt, 0)); ``` The same program here: ```ts /** The background, picked by eye and so stated through `srgbColor`: the renderer grades a clear. */ const CLEAR = srgbColor(0.3, 0.3, 0.7); /** A lit box on a canvas, turning. Every piece is a value the program holds. */ export async function spinningBox(canvas: HTMLCanvasElement): Promise { /* WebGPU where the browser has it, WebGL2 where it does not; `backend` says which. */ const { renderer, backend } = await createRenderer(canvas, {}); console.info(`drawn by ${backend}`); renderer.resize(); addEventListener('resize', () => renderer.resize()); /* The light points toward the sun, and colours are 0 to 1. */ const environment = createEnvironment({ directionalDir: [0.4, 0.8, 0.3], directionalColor: [1, 0.97, 0.9], ambient: [0.2, 0.22, 0.27], }); /* A box by its centre and its half extents: this one is one metre on a side. */ const box = renderer.createMesh( new MeshBuilder().addBox([0, 0, 0], [0.5, 0.5, 0.5], [0.2, 0.75, 0.35]).build(), ); const node = new SceneNode(); const camera = new Camera(); camera.fovYDeg = 60; camera.position[2] = 3; camera.lookAt(0, 0, 0); /* The rules run sixty times a second, whatever the display does. Drawing happens once a frame, between the last two steps by `alpha`. */ let angle = 0; let previous = 0; startLoop({ simulate(dt) { previous = angle; angle += dt * 1.2; }, render(alpha) { node.setRotationAxisAngle(0, 1, 0, previous + (angle - previous) * alpha); node.updateWorld(); camera.updateMatrices(canvas.width / Math.max(1, canvas.height)); renderer.beginFrame(CLEAR); renderer.bindMeshPass(camera, environment); renderer.drawMesh(box, node.worldMatrix); renderer.endFrame(); }, }); } ``` Line by line: - **The device.** `pc.createGraphicsDevice` tries the device types it is given and adds WebGL2 to the end of the list itself. `createRenderer(canvas)` does the same with WebGPU first, and `backend` says which it got. Nothing has to be registered first: there are no component systems or resource handlers to list, because a program imports what it uses. - **The hierarchy.** There is no `app.root`. A `SceneNode` is the nearest thing to a `pc.GraphNode`, a transform with a parent, and the frame draws a mesh at a node's `worldMatrix`. A mesh the frame stops drawing is gone, and there is nothing to remove from a hierarchy. - **The box.** A render component's `box` is a cube with sides of length 1. `addBox` takes a centre and **half** extents, so the same cube is `[0.5, 0.5, 0.5]`. - **The material.** The colour here is vertex data, which `MeshBuilder` writes for every shape. A textured surface is set before a draw with `renderer.setMaterial`, which [Materials](https://driftengine.dev/docs/rendering/materials) covers. - **The light.** A PlayCanvas directional light shines along its entity's negative Y axis, and is aimed by rotating the entity. `directionalDir` is a direction, from the scene toward the light. - **The camera.** Both take a vertical field of view in degrees by default. The aspect ratio is given to `updateMatrices` each frame, so a resize needs nothing else. - **The loop.** The application's `update` event comes once per frame with that frame's `dt`. `startLoop` calls `simulate` sixty times a second with a fixed `dt`, however fast the display is, and `render` once per displayed frame with `alpha`, how far the display has got between the last two steps. It is the arrangement PlayCanvas uses for its physics, applied to every rule. Rules go in `simulate`, and drawing goes in `render`. [The loop](https://driftengine.dev/docs/start/the-loop) explains why, and [Hello world](https://driftengine.dev/docs/start/hello-world) is this program in full, with its rule in DriftScript. ## Conventions | | PlayCanvas | DriftEngine | | ------------------- | --------------------------------------- | ---------------------------------------------------------------- | | Axes | Y up, forward is negative Z | the same | | Units | a metre to a unit, for physics | metres and seconds | | A rotation | Euler angles in degrees, or a `pc.Quat` | a quaternion, `x, y, z, w`, or `setRotationAxisAngle` in radians | | A box | a unit cube, scaled by its entity | a centre and half extents | | A directional light | along its entity's negative Y axis | `directionalDir`, toward the light | | A colour | `pc.Color`, from 0 to 1 | `[r, g, b]` from 0 to 1 | | Time | the frame's `dt`, in seconds | the loop's `dt`, a fixed sixtieth of a second | [Coordinates and units](https://driftengine.dev/docs/concepts/coordinates) has the rest, including how a world larger than single precision stays exact. ## What each thing is called | PlayCanvas | DriftEngine | Where | | --------------------------------------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------- | | `pc.createGraphicsDevice`, `pc.AppBase` | `createRenderer`, one renderer with two backends | [Backends](https://driftengine.dev/docs/concepts/backends) | | `pc.GraphNode`, `app.root` | `SceneNode`, parented with `attachChild` | [The scene graph](https://driftengine.dev/docs/concepts/scene-graph) | | an entity and its components | an entity in a `World`, with components declared in DriftScript | [Entities](https://driftengine.dev/docs/simulation/entities) | | a script class with `update(dt)` | a DriftScript system over a query | [DriftScript in a game](https://driftengine.dev/docs/scripting/driftscript) | | the render component | `MeshBuilder` and `renderer.createMesh`, drawn with `drawMesh` | [Meshes](https://driftengine.dev/docs/rendering/meshes) | | `pc.StandardMaterial` | `renderer.setMaterial`, with colour, packed ORM, normal and emissive maps | [Materials](https://driftengine.dev/docs/rendering/materials) | | `pc.StandardMaterial` anisotropy, `alphaToCoverage` | `anisotropicModel`, and `cutoutMode: 'dithered'`, which the frame resolves | [Materials](https://driftengine.dev/docs/rendering/materials) | | the light component | the environment's sun, and point and spot lights | [Lights](https://driftengine.dev/docs/rendering/lights) | | a container asset from a glTF | a `.drft` container baked ahead of time, or a model converted in a worker | [Importing models](https://driftengine.dev/docs/content/importing-models) | | the anim component | clips, blend trees and IK | [Animation](https://driftengine.dev/docs/simulation/animation) | | the rigidbody and collision components | `PhysicsWorld`, the engine's own | [Rigid bodies](https://driftengine.dev/docs/simulation/rigid-bodies) | | `app.systems.rigidbody` ray casts | rays and sweeps against the physics world | [Queries](https://driftengine.dev/docs/simulation/queries) | | the sound component | a mix, placed sounds and rooms | [Audio](https://driftengine.dev/docs/content/audio) | | screen and element components | interface trees with layout, focus and themes | [Interface](https://driftengine.dev/docs/interface/interface) | | the gsplat component | splat captures | [Splats](https://driftengine.dev/docs/worlds/splats) | ## Behaviour ```js import { Script } from 'playcanvas'; export class Fall extends Script { static scriptName = 'fall'; vy = 0; bounce = 0.75; update(dt) { const p = this.entity.getLocalPosition(); this.vy -= 9.81 * dt; let y = p.y + this.vy * dt; if (y < 0.35) { y = 0.35; this.vy = -this.vy * this.bounce; } this.entity.setLocalPosition(p.x, y, p.z); } } ``` A script class belongs to one entity and runs once a frame. A DriftScript system runs once a step over every entity that has the components it names, and says which it reads and writes, so the engine can order systems and check their access. The same fall, from the [in-game tools example](https://driftengine.dev/docs/tools/in-game-tools), as one system over every ball: ```drs let GRAVITY: f32 = 9.81 let FLOOR: f32 = 0.35 // Slower than this at the floor and a ball stops bouncing. let REST: f32 = 0.4 system Fall { writes Ball update { for e in query() { e.Ball.vy = e.Ball.vy - GRAVITY / 60 e.Ball.y = e.Ball.y + e.Ball.vy / 60 if e.Ball.y < FLOOR { e.Ball.y = FLOOR let speed = 0 - e.Ball.vy if speed > REST { e.Ball.impact = speed e.Ball.hits = e.Ball.hits + 1 e.Ball.vy = speed * e.Ball.bounce } else { e.Ball.vy = 0 } } } } } ``` The components are declared in the same language, and a game adds them to entities in a `World` from TypeScript or from another script. A `.drs` file reloads in place while the game runs, with every entity keeping its values. [Entities](https://driftengine.dev/docs/simulation/entities) covers worlds, queries, prefabs and rewinding them. ## Loading a model ```js const asset = new pc.Asset('lantern', 'container', { url: 'models/lantern.glb' }); app.assets.add(asset); asset.ready(() => app.root.addChild(asset.resource.instantiateRenderEntity())); app.assets.load(asset); ``` ```ts /** * A model baked to a `.drft` ahead of time, streamed in a few parts a frame. A draw function is * what the game calls inside its frame, once the camera and the light are bound. */ export function streamedModel(renderer: RendererApi, url: string) { const loader = new DrftLoader(renderer); void loader.load(url, { footprint: 1, height: 1.5 }); const at = new SceneNode(); at.updateWorld(); return function draw(dt: number): void { loader.update(dt); const textures = loader.textures; const image = (index: number) => (index >= 0 ? (textures?.at(index) ?? null) : null); for (const part of loader.parts) { renderer.setMaterial({ albedo: image(part.albedo), orm: image(part.orm), normal: image(part.normal), emissive: image(part.emissive), }); renderer.drawMesh(part.mesh, at.worldMatrix); } renderer.setMaterial(null); }; } ``` A model is usually baked once, ahead of time, into a `.drft` container whose bytes are already laid out the way a GPU takes them, and `DrftLoader` streams it in a few parts a frame, so it builds up on screen instead of arriving after a wait. A game that has to open a model the player supplies converts it in a worker, which [Importing models](https://driftengine.dev/docs/content/importing-models) shows with a glTF, an OBJ and an STL. A load never throws: `progress` says what happened. ## Physics PlayCanvas's physics is ammo.js, a WebAssembly build of Bullet, through the rigidbody and collision components. The engine's is its own, and deterministic: two runs of the same inputs reach the same state tick for tick, checked by a fingerprint, which is what [lockstep networking](https://driftengine.dev/docs/systems/networking) and replays rest on. ```ts /** * A ball dropped on a floor. The world belongs to the game, steps inside `simulate`, and is read * back into a node to draw. */ export function fallingBall() { const world = new PhysicsWorld(); world.addBody({ type: BODY_STATIC, shape: boxShape(5, 0.5, 5), y: -0.5 }); const ball = world.addBody({ type: BODY_DYNAMIC, shape: sphereShape(1), y: 4, restitution: 0.75, }); const node = new SceneNode(); return { simulate(dt: number): void { world.step(dt); }, place(): SceneNode { const b = world.bodies; node.setPosition(b.posX[ball] ?? 0, b.posY[ball] ?? 0, b.posZ[ball] ?? 0); node.rotation[0] = b.rotX[ball] ?? 0; node.rotation[1] = b.rotY[ball] ?? 0; node.rotation[2] = b.rotZ[ball] ?? 0; node.rotation[3] = b.rotW[ball] ?? 1; node.markMoved(); node.updateWorld(); return node; }, }; } ``` A body is attached to nothing. The world belongs to the game, steps inside `simulate` on the loop's fixed step, and the frame reads the bodies back into whatever it draws them with, here a node. ## What works differently - **The frame is a list of calls.** `beginFrame`, `bindMeshPass` with a camera and an environment, any number of draws, `endFrame`. Order and visibility are the program's, which is also why [culling](https://driftengine.dev/docs/concepts/scene-graph) is something a program asks for. - **Quality is decided when the renderer is made.** Shadows, anti-aliasing, the output transform and most other options size GPU memory, so changing one means making a new renderer. [Render quality](https://driftengine.dev/docs/concepts/quality) lists them. - **Emissive light has a switch.** Nothing glows, whatever its emissive colour, until the environment's `nightFactor` is above zero. The name is about night scenes, not the clock. --- # Six 3D engines measured in the browser https://driftengine.dev/blog/webgpu-engines-measured DriftEngine beside Three.js, Babylon.js, PlayCanvas, Godot and Bevy: five scenes timed on WebGPU and WebGL2, on a desktop GPU and a phone, with a picture of every scene, what each engine ships for a game, and where DriftEngine is behind. _We make DriftEngine. This is our comparison with Three.js, Babylon.js, PlayCanvas, Godot and Bevy. [The results page](https://driftengine.dev/blog/webgpu-engines-measured-results) has the method and tables; we welcome corrections from people who know the other engines better than we do._ ![Intel's Sponza at noon, drawn in a browser by DriftEngine on WebGPU](https://driftengine.dev/stills/articles/sponza-noon.jpg) _The opening picture comes from DriftEngine's own Sponza demo, separate from the benchmark. Intel Sponza (2022) is from the Intel Sample Library under Creative Commons Attribution; see the [model credits](https://driftengine.dev/blog/webgpu-engines-measured-results#sponza)._ DriftEngine is a 3D game engine written in TypeScript. It renders through WebGPU, falls back to WebGL2 when a browser has no usable WebGPU device, and packages the same game for the web, Linux, Windows, macOS and Android. We built it for browser games, including games ported from elsewhere. Here we explain what it provides and measure it alongside the other engines. Every scene's timing table has pictures of what each engine drew beside it: a fast frame only counts if it shows the scene. We print the numbers that favour DriftEngine and those that favour the others. ## What a game gets Install the packages your game needs. `@driftengine/core` provides the fixed-step loop, both renderers, cameras, an input action map, the scene graph, geometry, text and physics. Separate packages add animation, audio, model loading, navigation meshes, terrain, lockstep and rollback netcode, Gaussian splats, a 2D layer for sprites and menus, and native packaging. We publish them on npm under Apache-2.0. Core includes rigid bodies, joints, ray and shape queries, sensors, a character controller with air control and a jump buffer, a raycast vehicle with tyre curves, ragdolls and cloth. The matrix below records built-in rigid-body physics, character controllers, vehicles and ragdolls for both DriftEngine and Godot, and lists the dependencies the other engines use. The renderer supports directional, point and spot lights through clustered shading, plus rectangular area lights with shadows that soften as the emitter grows. It provides image-based lighting, exposure, ambient occlusion, temporal antialiasing, bloom, depth of field, motion blur, tone mapping and colour grading. The sky follows a latitude and season. Fog, rain and water share wind with other systems. WebGPU also offers an optional GPU-driven pipeline with instance and cluster culling, and temporal reconstruction from a lower resolution. Our baker reads glTF, OBJ, STL, USD, 3MF, FBX and Blender files and writes `.drft` containers. It quantises geometry, recovers repeated meshes as instances, keeps textures in GPU compression formats and divides scenes into regions that stream nearest first. The benchmark loads a container baked from Intel's Sponza glTF and renders its main pass through the loader's `draw()` method. That API call can submit several GPU draws; the scene also has a shadow pass. The engine imposes no character type or level format. Its functions take positions, colours, sizes and time, leaving you to organise the game. ## Built for an agent to write We provide unattended project setup and checks that a coding agent can run after a change. `npm create @driftengine@latest my-game` creates a project without prompts. It includes an `AGENTS.md` with project instructions, the engine's skill in the locations agents look for it, and `npm run check`. That command typechecks the project, runs its tests in Node, then opens and photographs the game on WebGPU and WebGL2 using the machine's GPU. It rejects console errors and warnings, a flat-colour canvas, or a different backend from the one requested. The image check can catch an empty frame even when compilation and unit tests pass. The simulation is plain TypeScript, so game rules can be tested in Node without a GPU. An agent can check a jump's height or a score calculation before rendering anything. Every export carries its documentation; we also publish the manual as Markdown, an `llms.txt` index and an installable skill. [Orbfall](https://driftengine.dev/showcase/orbfall) is a small 3D arcade game an agent built from one prompt using this setup. Its page includes the original prompt and the agent's log of its checks. ## Two backends, one picture WebGPU and WebGL2 share one API. We try WebGPU first, draw a probe frame and read its pixels back before accepting the device. Checking for the API alone would miss a device that uses a software rasteriser or draws nothing. If we reject it, we fall back to WebGL2 and return a reason the game can display or log. We write shaders once and generate the WebGPU versions from them; the WebGL2 path does not need a translator. In the still scenes here, instancing, lights and Sponza, DriftEngine's two backends draw nearly identical pictures, with nearly every pixel the same. ## Determinism The simulation advances in fixed steps of a sixtieth of a second, and rendering interpolates between them. Our seeded random generator keeps its sequence across releases; a new distribution gets a new function. Physics computes a world fingerprint at each step. Replays and rollback also need reproducible arithmetic and game logic that uses recorded inputs instead of external time or unseeded randomness. With those conditions met, rollback can rewind, apply a late input and simulate forward to the same state. Tests can compare fingerprints from the same initial state and inputs to find the step where runs diverge. The matrix below describes the simulation support and integrations available in each engine. ## The numbers ### How they were taken We wrote five scenes from each engine's documentation and examples: 1. **Cube**: one lit, spinning cube, used to measure download size, time to first frame and memory. 2. **Separate objects**: individually transformed cubes. Bevy batches these automatically, so an object count is not a draw-call count across engines. 3. **Instances**: a cube repeated through each engine's instancing path. 4. **Lights**: a floor and 64 pillars under coloured point lights. 5. **Sponza**: Intel's 2022 base scene, with textures capped at 1,024 pixels and a sun casting shadows through the same size of shadow map in each engine. The desktop has an AMD Radeon RX 9070 XT, with Chrome using Vulkan. Vsync and the frame-rate cap are off. Each canvas is 1280 by 720, with a pixel ratio of one and no multisampling. Fixed-count runs discard 120 warm-up frames, then record up to 600 frames within 15 seconds. The probe tracks GPU completion and allows 2 frames in flight. Each timing reading averages 4 frames; tables show the median and 95th percentile of those readings. Desktop fixed-count cells take the median of each metric from 3 interleaved runs. Desktop searches and all phone cells ran once. For counts at sixty frames a second, we double the count while the 95th percentile is at or under 18 milliseconds, then narrow the interval to the greater of 5% or 16 objects. The search also checks for a flat image and GPU errors; it cannot verify that every object or light was drawn. [The results page](https://driftengine.dev/blog/webgpu-engines-measured-results) gives the full timing and search method. All engines use pinned release builds: DriftEngine 4.13.0, Three.js r186, Babylon.js 9.30.0, PlayCanvas 2.23.2, Godot 4.7.2 and Bevy 0.20.0. Each uses its default output encoding. Godot exports only WebGL2; Bevy needs a build for each backend. For Sponza, Godot imports the model ahead of time and DriftEngine bakes it; the other engines load the glTF. We exclude runs that use another backend or a software renderer, report GPU errors or produce a flat canvas. Repeating DriftEngine and Three.js desktop cube and separate-object measurements in two sessions gave a median difference of 2.0% and a largest difference of 4.9%. These repeats cover only those engines and desktop scenes. Bold marks the best value and timings within 2.0% or counts within 5% of it. These bands group nearby results without establishing a tie. Download, first-frame and memory columns bold only the best value. If every value falls within a column's band, none is bold. A plus sign means the search reached its cap, leaving the maximum unknown. A figure an engine reached by shading fewer lights than it was given is never bold. The pictures beneath the timing tables are separate desktop captures at the fixed counts being timed. They show neither the search ceilings nor the phone runs. The results page explains the lighting settings that changed between measurement and photography. ### Download and first frame | Engine | Backend | Brotli | gzip | First frame | Memory | | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 544.5 KB | 928.1 KB | 456 ms | 26.6 MB | | DriftEngine | WebGL2 | 304.1 KB | 378.6 KB | 148 ms | 13.7 MB | | Three.js | WebGPU | 241.7 KB | 300.3 KB | 156 ms | 13.1 MB | | Three.js | WebGL2 | **163.6 KB** | **198.9 KB** | **81 ms** | 10.6 MB | | Babylon.js | WebGPU | 317.5 KB | 368.6 KB | 258 ms | **10.4 MB** | | Babylon.js | WebGL2 | 318.7 KB | 370.2 KB | 237 ms | 13.5 MB | | PlayCanvas | WebGPU | 485.3 KB | 624.8 KB | 169 ms | 20.5 MB | | PlayCanvas | WebGL2 | 485.3 KB | 624.8 KB | 149 ms | 19.5 MB | | Godot | WebGL2 | 6.8 MB | 9.8 MB | 1430 ms | 63.0 MB | | Bevy | WebGPU | 4.3 MB | 6.2 MB | 813 ms | 65.1 MB | | Bevy | WebGL2 | 4.3 MB | 6.2 MB | 736 ms | 48.0 MB | ![The one-cube scene as each of the eleven builds drew it, each engine on its own clear colour](https://driftengine.dev/stills/articles/bench-cube-1.jpg) The cube measures the cost of a small application. Three.js on WebGL2 has the smallest Brotli download, 163.6 KB, and the earliest first frame, 81 ms. DriftEngine downloads 304.1 KB on WebGL2 and 544.5 KB on WebGPU. Its WebGPU first frame is 456 ms, the latest among the JavaScript builds. That includes our device probe, whose individual cost we did not measure. Godot and Bevy download WebAssembly engines and have larger page totals. ### Many separate objects | Engine | Backend | 1,000: median | 1,000: p95 | 10,000: median | 10,000: p95 | Most at 60 fps | | --- | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 2.67 ms | 3.24 ms | 22.39 ms | 25.34 ms | 7,168 | | DriftEngine | WebGL2 | 2.67 ms | 3.21 ms | 21.68 ms | 24.49 ms | 7,424 | | Three.js | WebGPU | 4.71 ms | 6.45 ms | 55.29 ms | 62.17 ms | 2,688 | | Three.js | WebGL2 | 1.47 ms | 1.93 ms | 12.51 ms | 14.11 ms | 9,472 | | Babylon.js | WebGPU | 7.67 ms | 8.93 ms | 87.99 ms | 93.07 ms | 1,792 | | Babylon.js | WebGL2 | 4.10 ms | 6.21 ms | 61.86 ms | 64.71 ms | 2,688 | | PlayCanvas | WebGPU | **1.35 ms** | **1.77 ms** | 16.60 ms | 21.43 ms | 8,192 | | PlayCanvas | WebGL2 | 1.48 ms | 2.03 ms | 18.37 ms | 21.83 ms | 7,424 | | Godot | WebGL2 | 3.04 ms | 3.46 ms | 29.14 ms | 31.48 ms | 5,376 | | Bevy | WebGPU | 3.12 ms | 4.02 ms | **10.58 ms** | **11.75 ms** | **16,896** | | Bevy | WebGL2 | 2.41 ms | 3.29 ms | **10.77 ms** | 12.04 ms | 15,360 | ![Ten thousand separate cubes in a grid, as each of the eleven builds drew them](https://driftengine.dev/stills/articles/bench-draws-10000.jpg) This scene measures updating and rendering ten thousand separate objects. Bevy's WebGPU build has the lowest median, 10.6 ms, and holds 16,896 objects at sixty frames a second. Its automatic batching matters when interpreting these counts. DriftEngine is third on WebGPU, behind Bevy and PlayCanvas, at 22.4 ms. Three.js takes 55.3 ms and Babylon.js 88.0 ms. On WebGL2, Three.js takes 12.5 ms, PlayCanvas 18.4 ms and DriftEngine 21.7 ms. ### One object, many times | Engine | Backend | 100,000: median | 100,000: p95 | 1,000,000: median | 1,000,000: p95 | Most at 60 fps | | --- | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 0.45 ms | 0.55 ms | **1.08 ms** | 1.64 ms | **4,194,304+** | | DriftEngine | WebGL2 | 0.47 ms | 0.65 ms | 3.15 ms | 4.04 ms | 3,801,088 | | Three.js | WebGPU | 0.37 ms | 0.55 ms | 1.49 ms | 2.20 ms | **4,063,232** | | Three.js | WebGL2 | 0.33 ms | 0.56 ms | 1.12 ms | **1.43 ms** | **4,194,304+** | | Babylon.js | WebGPU | 0.31 ms | **0.46 ms** | 1.13 ms | 1.70 ms | **4,194,304+** | | Babylon.js | WebGL2 | **0.30 ms** | **0.47 ms** | 1.14 ms | **1.40 ms** | **4,194,304+** | | PlayCanvas | WebGPU | 0.37 ms | 0.59 ms | 1.13 ms | 1.71 ms | **4,194,304+** | | PlayCanvas | WebGL2 | 0.33 ms | 0.53 ms | 1.32 ms | 2.02 ms | **4,194,304+** | | Godot | WebGL2 | 0.51 ms | 0.65 ms | 2.05 ms | 3.03 ms | **4,194,304+** | | Bevy | WebGPU | 24.12 ms | 25.65 ms | 211.10 ms | 218.15 ms | 71,680 | | Bevy | WebGL2 | 94.71 ms | 97.27 ms | 895.04 ms | 908.40 ms | 15,872 | ![A million instanced cubes in a grid, as each of the eleven builds drew them](https://driftengine.dev/stills/articles/bench-instances-1000000.jpg) Instancing lets a game repeat a mesh efficiently, as in a forest or crowd. At a million copies, DriftEngine on WebGPU has the lowest median, 1.1 ms. Babylon.js on WebGL2 has the lowest 95th percentile, 1.40 ms, against DriftEngine's WebGPU 1.64 ms. Our WebGL2 median, 3.1 ms, is the highest of the JavaScript builds. Several builds reach the search cap. Three.js on WebGPU accepts 4,063,232 copies. Bevy creates an entity for each cube and uses automatic instancing, so its figures include entity processing as well as rendering. We did not measure those costs separately. ### Many lights DriftEngine's desktop lights figures include point-light shadows, which none of the other engines draws here. We turned them off on the phone. | Engine | Backend | 64 lights | 256 lights | Most lights at 60 fps | Limits | | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 0.48 ms | 0.70 ms | 4,096+ | shades the nearest 320 of 4096 lights | | DriftEngine | WebGL2 | 0.57 ms | 0.92 ms | 4,096+ | shades the nearest 320 of 4096 lights | | Three.js | WebGPU | 0.51 ms | **0.57 ms** | **4,096+** | | | Three.js | WebGL2 | **0.45 ms** | 1.21 ms | 992 | forward: every light is evaluated for every fragment | | Babylon.js | WebGPU | 0.72 ms | 0.78 ms | **4,096+** | | | Babylon.js | WebGL2 | 0.59 ms | 0.64 ms | **4,096+** | | | PlayCanvas | WebGPU | 0.52 ms | 0.77 ms | **4,096+** | | | PlayCanvas | WebGL2 | 0.48 ms | 0.72 ms | **4,096+** | | | Godot | WebGL2 | 0.62 ms | 0.69 ms | 4,096+ | Compatibility renderer: at most 32 lights per object | | Bevy | WebGPU | 2.52 ms | 2.46 ms | **4,096+** | | | Bevy | WebGL2 | 2.01 ms | 2.39 ms | 4,096+ | WebGL2: at most 256 clusterable lights | ![The floor and pillars under 256 coloured point lights, as each of the eleven builds drew them: Godot lights only the middle of its floor, Babylon.js's floor runs to white, and Bevy on WebGL2 leaves the far end dark](https://driftengine.dev/stills/articles/bench-lights-256.jpg) At 256 requested lights, Three.js on WebGPU has the lowest median, 0.57 ms. DriftEngine takes 0.70 ms on WebGPU and 0.92 ms on WebGL2. Three.js on WebGL2 has the highest median among the JavaScript builds and accepts 992 lights in the desktop search. Read the limits column alongside the counts. DriftEngine, Godot and Bevy on WebGL2 limit the lights they shade at once, so reaching the search cap does not mean shading every requested light. The pictures show how those choices affect the floor; we discuss them below. ### Sponza | Engine | Backend | Download | Load to first frame | Frame | | --- | --- | --- | --- | --- | | DriftEngine (baked) | WebGPU | 44.2 MB | 2445 ms | 1.09 ms | | DriftEngine (baked) | WebGL2 | **44.0 MB** | 1974 ms | 1.25 ms | | Three.js | WebGPU | 73.7 MB | 1778 ms | 2.71 ms | | Three.js | WebGL2 | 73.6 MB | **1638 ms** | 1.85 ms | | Babylon.js | WebGPU | 74.0 MB | 2108 ms | 4.27 ms | | Babylon.js | WebGL2 | 74.0 MB | 2722 ms | 2.47 ms | | PlayCanvas | WebGPU | 73.9 MB | 1753 ms | **1.00 ms** | | PlayCanvas | WebGL2 | 73.9 MB | 1678 ms | 1.44 ms | | Godot (imported) | WebGL2 | 230.1 MB | 6386 ms | 2.71 ms | | Bevy | WebGPU | 77.8 MB | 5680 ms | 4.17 ms | | Bevy | WebGL2 | 77.7 MB | 5515 ms | 9.45 ms | ![Intel's Sponza as each of the eleven builds drew it, with the sun and sky the benchmark set for that engine](https://driftengine.dev/stills/articles/bench-sponza-1.jpg) We chose each engine's sun and sky settings separately for the benchmark. The pictures show those settings and do not rank rendering quality. Sponza brings a more varied workload: detailed geometry, many materials, alpha-tested foliage, blended decals and sun shadows. DriftEngine's median is 1.1 ms on WebGPU, behind PlayCanvas at 1.0 ms, and the lowest on WebGL2 at 1.2 ms. DriftEngine also has the smallest total page download: 44.2 MB on WebGPU and 44.0 MB on WebGL2. Three.js on WebGPU downloads 73.7 MB. These totals include engine and page resources as well as the model. DriftEngine reaches its first frame later than Three.js and PlayCanvas on both backends. ### On a phone | Engine | Backend | Most draws at 60 fps | Most instances at 60 fps | Most lights at 60 fps | Sponza frame | Sponza first frame | | --- | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 1,728 | 63,488 | 160 | 37.5 ms | 6386 ms | | DriftEngine | WebGL2 | 2,688 | 262,144 | 192 | 33.3 ms | 3001 ms | | Three.js | WebGPU | 1,024 | 688,128 | **4,096+** | **16.7 ms** | 3226 ms | | Three.js | WebGL2 | 8,704 | 753,664 | 48 | **16.7 ms** | **2561 ms** | | Babylon.js | WebGPU | 1,280 | 753,664 | 1,792 | **16.7 ms** | 3309 ms | | Babylon.js | WebGL2 | 4,096 | **786,432** | **4,096+** | **16.7 ms** | 3326 ms | | PlayCanvas | WebGPU | 7,168 | 540,672 | **4,096+** | **16.7 ms** | 3034 ms | | PlayCanvas | WebGL2 | 7,936 | **819,200** | **4,096+** | **16.7 ms** | 2933 ms | | Godot | WebGL2 | 3,712 | 360,448 | 4,096+ | **16.7 ms** | 38643 ms | | Bevy | WebGPU | **12,288** | 53,248 | 624 | 25.0 ms | 6850 ms | | Bevy | WebGL2 | **12,288** | 13,824 | 4,096+ | 20.8 ms | 7659 ms | We ran the same pages on a Samsung Galaxy S23 Ultra with an Adreno 740, using Chrome on Android over USB. The canvas remains 1280 by 720 at a pixel ratio of one. Vsync stays on, so the cube mostly measures the display's refresh. The useful comparisons are the counts held at sixty frames a second and the heavier Sponza scene. Phone temperature can move the ceilings; we measured the lights column in one sitting. DriftEngine has the highest Sponza median on each backend: 37.5 ms on WebGPU and 33.3 ms on WebGL2. Three.js, Babylon.js, PlayCanvas and Godot keep up with the display. DriftEngine's WebGPU instancing holds 63,488 copies at sixty frames a second, against 688,128 for Three.js. Our desktop lead at a million copies does not carry over to this phone's search. DriftEngine holds 160 lights on WebGPU and 192 on WebGL2. Most engines reach the search cap; Godot and Bevy's WebGL2 light limits still apply. Bevy on WebGPU holds the most separate objects, 12,288. DriftEngine's 1,728 exceeds Three.js and Babylon.js on that backend, but trails PlayCanvas's 7,168. Godot takes 38643 ms to reach Sponza's first frame. Its export packs the scene into one download; the total page transfer is 230.1 MB. ### What the pictures show Godot's Compatibility renderer shades at most 32 lights per object. Beyond that count, its floor is lit only around the middle. Bevy's WebGL2 build leaves the far end of the floor dark at 256 lights. Babylon.js's standard material fades each light linearly to its range; with this many overlapping lights, the floor runs to white. That is a difference in appearance, with the floor still present. Three.js's WebGL2 renderer drew a blank frame at 1,024 lights on the desktop and at 64 on the phone. Its WebGPU renderer lost the device at the step after 4,063,232 copies on the desktop. Every DriftEngine picture shows the whole scene at the photographed count, on both backends. No DriftEngine step on either device drew a blank frame or lost its device. Babylon.js, PlayCanvas, Godot and Bevy had none either; Three.js was the only engine with either outcome in these runs. A fast frame is only worth having if it shows the scene. Our backend rules aim to preserve that: anything added to one backend must reach the other, and a capability the device cannot provide must be refused with a clear message when the renderer starts. We photograph rendering changes on both backends before shipping them. ### Where DriftEngine loses For a minimal scene on WebGPU, DriftEngine downloads more and reaches its first frame later than Three.js and PlayCanvas. On WebGL2 its download is larger than Three.js's and smaller than PlayCanvas's. It also trails several JavaScript builds when drawing separate objects or a million instances on WebGL2, and takes longer than Three.js and PlayCanvas to show Sponza's first frame. Our strongest desktop results are on WebGPU: the lowest median at a million instances, and second at 256 lights and in Sponza. Those rankings depend on the count; they do not apply across every row of the tables. The phone leaves us more work. DriftEngine has the highest Sponza median, and its WebGPU instance count and light counts on both backends trail several other engines. These are priorities for our phone work. ## What each engine ships The feature matrix shows what each engine provides and what you would need to add. The table puts every engine in one of four states for each capability: **built in**, an **official add-on** from the engine's own organisation, a **community plugin** from someone else, or **none found**, where we found neither and the game would build it. An official add-on is not an absence. Every state links to the page that shows it, and [the results page](https://driftengine.dev/blog/webgpu-engines-measured-results#the-notes-on-each-cell) has the note on each cell. | Capability | DriftEngine | Three.js | Babylon.js | PlayCanvas | Godot | Bevy | | --- | --- | --- | --- | --- | --- | --- | | Rigid-body physics | [Built in](https://driftengine.dev/docs/simulation/rigid-bodies) | [Official add-on](https://threejs.org/docs/pages/RapierPhysics.html) | [Official add-on](https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine) | [Official add-on](https://developer.playcanvas.com/user-manual/physics/physics-basics/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/physics/physics_introduction.html) | [Community plugin](https://rapier.rs/docs/user_guides/bevy_plugin/getting_started_bevy) | | Character controller | [Built in](https://driftengine.dev/docs/simulation/characters) | [Community plugin](https://rapier.rs/docs/user_guides/javascript/character_controller) | [Official add-on](https://doc.babylonjs.com/features/featuresDeepDive/physics/characterController) | [Official add-on](https://developer.playcanvas.com/user-manual/physics/forces-and-impulses/) | [Built in](https://docs.godotengine.org/en/4.7/classes/class_characterbody3d.html) | [Community plugin](https://rapier.rs/docs/user_guides/bevy_plugin/character_controller) | | Vehicle physics | [Built in](https://driftengine.dev/docs/simulation/vehicles) | [Community plugin](https://rapier.rs/docs/user_guides/javascript/vehicle_controller) | [None found](https://doc.babylonjs.com/features/featuresDeepDive/physics) | [Official add-on](https://developer.playcanvas.com/tutorials/vehicle-physics/) | [Built in](https://docs.godotengine.org/en/4.7/classes/class_vehiclebody3d.html) | [Community plugin](https://rapier.rs/docs/user_guides/bevy_plugin/vehicle_controller) | | Ragdolls | [Built in](https://driftengine.dev/docs/simulation/ragdolls-and-cloth) | [None found](https://threejs.org/docs/pages/RapierPhysics.html) | [Official add-on](https://doc.babylonjs.com/features/featuresDeepDive/physics/ragdolls) | [None found](https://developer.playcanvas.com/user-manual/physics/joints/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/physics/ragdoll_system.html) | [None found](https://bevy.org/assets/) | | Deterministic simulation and replays | [Built in](https://driftengine.dev/docs/concepts/determinism) | [None found](https://threejs.org/docs/pages/Timer.html) | [None found](https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations) | [None found](https://developer.playcanvas.com/user-manual/physics/physics-basics/) | [None found](https://docs.godotengine.org/en/4.7/tutorials/physics/physics_introduction.html) | [Community plugin](https://rapier.rs/docs/user_guides/bevy_plugin/determinism) | | Rollback netcode | [Official add-on](https://driftengine.dev/docs/systems/networking) | [None found](https://github.com/rameshvarun/netplayjs) | [None found](https://doc.babylonjs.com/guidedLearning/networking/Colyseus) | [None found](https://github.com/rameshvarun/netplayjs) | [Community plugin](https://foxssake.github.io/netfox/latest/netfox/guides/network-rollback/) | [Community plugin](https://github.com/gschup/bevy_ggrs) | | WebGPU with an automatic WebGL2 fallback | [Built in](https://driftengine.dev/docs/concepts/backends) | [Built in](https://threejs.org/docs/pages/WebGPURenderer.html) | [Built in](https://doc.babylonjs.com/setup/support/webGPU/webGPUStatus) | [Built in](https://developer.playcanvas.com/user-manual/engine/supported-browsers/) | [None found](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_web.html) | [None found](https://github.com/bevyengine/bevy/tree/v0.20.0/examples#webgl2-and-webgpu) | | Native desktop builds | [Official add-on](https://driftengine.dev/docs/systems/packaging) | [Community plugin](https://www.electronjs.org/docs/latest/) | [Official add-on](https://doc.babylonjs.com/BabylonCrossPlat/multiplePlatforms) | [Community plugin](https://developer.playcanvas.com/user-manual/editor/publishing/desktop/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/export/index.html) | [Built in](https://bevy.org/) | | Android builds | [Official add-on](https://driftengine.dev/docs/systems/packaging) | [Community plugin](https://capacitorjs.com/docs/android) | [Official add-on](https://doc.babylonjs.com/BabylonCrossPlat/multiplePlatforms) | [Community plugin](https://developer.playcanvas.com/user-manual/editor/publishing/mobile/cordova/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_android.html) | [Built in](https://github.com/bevyengine/bevy/tree/v0.20.0/examples#android) | | Navigation meshes | [Official add-on](https://driftengine.dev/docs/simulation/navigation) | [Community plugin](https://github.com/isaac-mason/recast-navigation-js) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/crowdNavigation/createNavMesh) | [Community plugin](https://github.com/isaac-mason/recast-navigation-js) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/navigation/navigation_using_navigationmeshes.html) | [Community plugin](https://github.com/janhohenheim/rerecast) | | Terrain | [Official add-on](https://driftengine.dev/docs/worlds/terrain) | [Community plugin](https://github.com/IceCreamYou/THREE.Terrain) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/ground_hmap) | [None found](https://developer.playcanvas.com/tutorials/terrain-generation) | [Community plugin](https://terrain3d.readthedocs.io/en/stable/docs/platforms.html) | [Community plugin](https://github.com/Katsutoshii/bevy_heightmap) | | Spatial audio | [Official add-on](https://driftengine.dev/docs/content/audio) | [Built in](https://threejs.org/docs/pages/PositionalAudio.html) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic) | [Built in](https://api.playcanvas.com/engine/classes/SoundComponent.html) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_web.html) | [Built in](https://docs.rs/bevy/0.20.0/bevy/audio/struct.SpatialListener.html) | | Gaussian splats | [Official add-on](https://driftengine.dev/docs/worlds/splats) | [Official add-on](https://threejs.org/docs/pages/GaussianSplat.html) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/mesh/gaussianSplatting) | [Built in](https://developer.playcanvas.com/user-manual/gaussian-splatting/) | [None found](https://godotengine.org/asset-library/asset/5076) | [Community plugin](https://github.com/mosure/bevy_gaussian_splatting) | | A scripting language of its own | [Official add-on](https://driftengine.dev/docs/scripting/driftscript) | [None found](https://threejs.org/llms.txt) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/flowGraph) | [None found](https://developer.playcanvas.com/user-manual/scripting/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/scripting/gdscript/gdscript_basics.html) | [Community plugin](https://makspll.github.io/bevy_mod_scripting/) | | Coding-agent tooling | [Official add-on](https://driftengine.dev/docs/start/with-an-agent) | [Official add-on](https://threejs.org/llms.txt) | [Official add-on](https://doc.babylonjs.com/llms.txt) | [Official add-on](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas/) | [Community plugin](https://github.com/jame581/GodotPrompter) | [Community plugin](https://github.com/natepiano/bevy_brp) | | Visual editor | [Official add-on](https://github.com/drftrun/driftengine/tree/main/packages/editor) | [Official add-on](https://threejs.org/editor/) | [Official add-on](https://doc.babylonjs.com/communityExtensions/editor) | [Official add-on](https://developer.playcanvas.com/user-manual/editor/) | [Built in](https://docs.godotengine.org/en/4.7/getting_started/introduction/first_look_at_the_editor.html) | [Community plugin](https://bevyskein.dev/) | DriftEngine has gaps of its own in that table, and the largest is the editor. ## And Unreal Unreal Engine has no official browser target, so it is outside these measurements. We have not compared native rendering performance. The practical differences for a browser project are: | | DriftEngine | Unreal Engine | | --- | --- | --- | | Runs in a browser | Yes, it is the first target | Not since version 4.24, when HTML5 moved out of the engine to a community-supported extension ([Epic's forum](https://forums.unrealengine.com/t/html5-support/1172997)) | | Native apps | Linux, Windows, macOS and Android, from the same project | Desktop, console and mobile platforms | | Language | TypeScript, and DriftScript for scripts | C++ and Blueprints ([Epic](https://dev.epicgames.com/documentation/unreal-engine)) | | Terms | Apache-2.0 | A five per cent royalty on a product's revenue past its first US$1 million, three and a half per cent for qualifying Launch Everywhere releases, with the exclusions the EULA lists. Some other uses need paid seats. See the [EULA](https://www.unrealengine.com/en-US/eula/unreal), section 3 and the Royalty Addendum. | | Editor | Early: a scene tree, an inspector and play-in-editor | An established visual editor with level design, animation and profiling tools | Our editor is still a substantial gap. It provides a scene tree, an inspector and play-in-editor; a full visual editor is our next major step. Teams that rely on an editor for daily development will find much more in Unreal. For teams targeting browsers with TypeScript, we offer a workflow built around code, with agent instructions and automated browser checks. ## Porting a game to the browser An existing game's language, assets and target platforms determine how much of it can carry over. **What language is the game in?** Godot and Bevy export supported projects to the browser through WebAssembly. Both have web restrictions, including Godot 4's lack of C# web export. DriftEngine uses TypeScript, so game code written in another language needs rewriting. You can carry over the design and data, then test the port's rules in Node against results from the original. An existing fixed-step simulation fits our loop naturally. **Where are its assets?** Our baker reads glTF, FBX, OBJ, STL, USD, 3MF and Blender files and converts them into streaming containers. Textures retain GPU compression; when a phone does not support the desktop format, a worker re-encodes them. **Must it still run outside a browser?** Our packager builds desktop and Android apps from the same project. The native host runs the game on Dawn and SDL without a browser. Browser and native pictures match in measurements made in the engine's own repository. For ports from another JavaScript engine, our guides map the concepts: [from Three.js](https://driftengine.dev/docs/coming-from/threejs), [from Babylon.js](https://driftengine.dev/docs/coming-from/babylonjs) and [from PlayCanvas](https://driftengine.dev/docs/coming-from/playcanvas). ## Start here ```sh npm create @driftengine@latest my-game cd my-game npm install npm run dev ``` Add `-- --template first-game` after the project's name to start from a complete 3D game with physics, a character, shadows and sound rather than a lit cube. To give an existing project's agent the engine's skill, run `npx skills add drftrun/driftengine` in it. - [The manual](https://driftengine.dev/docs), from installation to every system, with code that runs in the page. - [The examples](https://driftengine.dev/examples), one complete program per capability. - [Building with an agent](https://driftengine.dev/docs/start/with-an-agent), the chapter on the project, the skill and the check. - [The results page](https://driftengine.dev/blog/webgpu-engines-measured-results): the method, measurements and feature notes. _Unreal and Unreal Engine are trademarks or registered trademarks of Epic Games, Inc. Three.js, Babylon.js, PlayCanvas, Godot and Bevy are the names of their projects, used only to say which engine each figure belongs to. DriftEngine and Drift Technologies are not affiliated with, endorsed by or partnered with any of them._ --- # Six 3D engines measured: the method and results https://driftengine.dev/blog/webgpu-engines-measured-results How the DriftEngine comparison was measured on a desktop and a phone, the figures it produced, and the feature matrix with a note and a source for every cell. We publish the method, aggregate measurements and sourced feature notes behind [our engine comparison](https://driftengine.dev/blog/webgpu-engines-measured) here. The benchmark code and raw reports remain private. ## What was measured | Engine | Version | Backends | Sponza from | | --- | --- | --- | --- | | DriftEngine | 4.13.0 | WebGPU, WebGL2 | a container from its own baker | | Three.js | r186 | WebGPU, WebGL2 | the glTF, through `GLTFLoader` | | Babylon.js | 9.30.0 | WebGPU, WebGL2 | the glTF, through its glTF loader | | PlayCanvas | 2.23.2 | WebGPU, WebGL2 | the glTF, through its container loader | | Godot | 4.7.2 | WebGL2 | the glTF, imported into the project | | Bevy | 0.20.0 | WebGPU, WebGL2, one build each | the glTF, through its asset server | We wrote each engine's scenes from its documentation and examples. A shared layout sets object positions and light colours, with equivalent code in GDScript and Rust. The engines use their own rendering paths and asset pipelines. Bevy automatically batches the separate cubes; in the instancing scene, it creates an entity per cube and uses automatic instancing. Neither scene isolates the cost of a GPU draw call. ## The machine and the browser We measured the desktop on 2026-10-11 using an AMD Radeon RX 9070 XT, reported by the browser as `amd rdna-4`, in `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/151.0.0.0 Safari/537.36`. The GPU runs through ANGLE on Vulkan. We disabled vsync and the browser's frame-rate cap, and checked for hardware rendering before each session. We measured the phone on 2026-10-11 using a Samsung Galaxy S23 Ultra with an Adreno 740, in `Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Mobile Safari/537.36`. The runner controlled it over USB and opened each page in the foreground. Every page used the desktop's 1280 by 720 canvas at a pixel ratio of one. We checked the reported canvas size and corrected Bevy's pixel ratio before taking the published measurements. Phone vsync remained on, so cube timings mostly reflect the display's refresh interval. Temperature affects the accepted counts; we measured the lights column in one sitting with the phone on its charger. ## How a frame time is taken The probe waits for each engine's readiness signal before warming up. Where available, we use its preparation calls, including DriftEngine's `prepare` and `ready`, Three.js's `compileAsync` and Babylon.js's `whenReadyAsync`. Fixed-count runs discard 120 warm-up frames, then record up to 600 frames within 15 seconds. Slow runs therefore have fewer readings. We record intervals from both the page's CPU loop and GPU completion, using `onSubmittedWorkDone` on WebGPU and fences on WebGL2. The probe holds back the next frame when 2 frames are still unfinished on the GPU. We use the GPU readings when their mean exceeds 1.05 times the CPU mean; otherwise we use the CPU readings. These are frame intervals under that scheduling rule, rather than isolated GPU execution times. We wait for outstanding GPU work to finish before the next run. **Each reading averages 4 frames.** This smooths out the browser reporting adjacent completions together, but also spreads an individual slow frame across the window. The median and 95th percentile are readings at those ranks, without interpolation. Desktop fixed-count measurements have 3 interleaved runs, and we print the median of each metric. Desktop count searches and all phone measurements have one run. First-frame time starts at navigation and ends when the GPU completes the first frame after the engine reports ready. Pages are served locally on desktop and through USB port forwarding on the phone, so these figures do not estimate loading over the internet. Memory comes from the browser's `measureUserAgentSpecificMemory()` after the scene settles; it does not measure GPU memory. Download totals cover fetched application resources, including the engine and assets but excluding the benchmark probe. We count the bytes at the server, using the highest Brotli and gzip settings. Images served without HTTP compression keep their stored size. Sponza's download column uses Brotli. KB and MB here mean 1,024 and 1,048,576 bytes. ## How a ceiling is found For separate objects, instances and lights, we search for the largest count held at sixty frames a second. A count meets the timing criterion when the 95th percentile of the four-frame readings is at or under the 18 ms hold. This allows some room around the target frame interval; it does not guarantee every frame meets it. Each search step discards 60 warm-up frames and measures up to 180 frames within 6 seconds. We double the count until a step exceeds the timing limit or is excluded, then bisect the interval between the last accepted count and the first rejected one. We stop when the gap is at most the greater of 16 objects and 5% of the accepted count, or after 20 steps. The table reports the largest accepted count tested. **An accepted count must pass the image check.** We photograph each step that meets the timing criterion and reject a flat canvas. This checks that something was drawn; it cannot verify every requested object or light. A GPU error or lost device also excludes the step. After a GPU loss, we restart the browser before continuing the search. ## What is not a number If a run uses another backend, uses a software rasteriser, reports a GPU error or has GPU work the probe cannot observe, we print the outcome in place of a number. Desktop fixed-count runs are also photographed; a flat-colour image excludes the run. We repeated DriftEngine and Three.js desktop measurements for the cube and separate-object scenes in two sessions. The differences were 2.0% at the median and 4.9% at worst. These repeats cover only those engines and desktop scenes. Bold marks the best value, plus frame intervals within 2.0% and counts within 5% of it. We use these bands to group nearby results; bold does not establish a tie. Download, first-frame and memory columns bold only the best value. A column with every value inside the band has nothing in bold. A plus sign means the search cap was reached, so the engine's maximum remains unknown. A figure an engine reached by shading fewer lights than it was given is never bold. The picture sheets show separate desktop captures at fixed counts, including those timed in the tables. They do not show the search ceilings or phone runs. The lights section records the settings changed between the timed runs and these captures. ## Desktop ### Download, first frame and memory | Engine | Backend | Brotli | gzip | First frame | Memory | | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 544.5 KB | 928.1 KB | 456 ms | 26.6 MB | | DriftEngine | WebGL2 | 304.1 KB | 378.6 KB | 148 ms | 13.7 MB | | Three.js | WebGPU | 241.7 KB | 300.3 KB | 156 ms | 13.1 MB | | Three.js | WebGL2 | **163.6 KB** | **198.9 KB** | **81 ms** | 10.6 MB | | Babylon.js | WebGPU | 317.5 KB | 368.6 KB | 258 ms | **10.4 MB** | | Babylon.js | WebGL2 | 318.7 KB | 370.2 KB | 237 ms | 13.5 MB | | PlayCanvas | WebGPU | 485.3 KB | 624.8 KB | 169 ms | 20.5 MB | | PlayCanvas | WebGL2 | 485.3 KB | 624.8 KB | 149 ms | 19.5 MB | | Godot | WebGL2 | 6.8 MB | 9.8 MB | 1430 ms | 63.0 MB | | Bevy | WebGPU | 4.3 MB | 6.2 MB | 813 ms | 65.1 MB | | Bevy | WebGL2 | 4.3 MB | 6.2 MB | 736 ms | 48.0 MB | ![The one-cube scene as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-cube-1.jpg) ### Separate objects | Engine | Backend | 1,000: median | 1,000: p95 | 10,000: median | 10,000: p95 | Most at 60 fps | | --- | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 2.67 ms | 3.24 ms | 22.39 ms | 25.34 ms | 7,168 | | DriftEngine | WebGL2 | 2.67 ms | 3.21 ms | 21.68 ms | 24.49 ms | 7,424 | | Three.js | WebGPU | 4.71 ms | 6.45 ms | 55.29 ms | 62.17 ms | 2,688 | | Three.js | WebGL2 | 1.47 ms | 1.93 ms | 12.51 ms | 14.11 ms | 9,472 | | Babylon.js | WebGPU | 7.67 ms | 8.93 ms | 87.99 ms | 93.07 ms | 1,792 | | Babylon.js | WebGL2 | 4.10 ms | 6.21 ms | 61.86 ms | 64.71 ms | 2,688 | | PlayCanvas | WebGPU | **1.35 ms** | **1.77 ms** | 16.60 ms | 21.43 ms | 8,192 | | PlayCanvas | WebGL2 | 1.48 ms | 2.03 ms | 18.37 ms | 21.83 ms | 7,424 | | Godot | WebGL2 | 3.04 ms | 3.46 ms | 29.14 ms | 31.48 ms | 5,376 | | Bevy | WebGPU | 3.12 ms | 4.02 ms | **10.58 ms** | **11.75 ms** | **16,896** | | Bevy | WebGL2 | 2.41 ms | 3.29 ms | **10.77 ms** | 12.04 ms | 15,360 | ![256 separate cubes as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-draws-256.jpg) ![1,000 separate cubes as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-draws-1000.jpg) ![10,000 separate cubes as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-draws-10000.jpg) ### One object, many times | Engine | Backend | 100,000: median | 100,000: p95 | 1,000,000: median | 1,000,000: p95 | Most at 60 fps | | --- | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 0.45 ms | 0.55 ms | **1.08 ms** | 1.64 ms | **4,194,304+** | | DriftEngine | WebGL2 | 0.47 ms | 0.65 ms | 3.15 ms | 4.04 ms | 3,801,088 | | Three.js | WebGPU | 0.37 ms | 0.55 ms | 1.49 ms | 2.20 ms | **4,063,232** | | Three.js | WebGL2 | 0.33 ms | 0.56 ms | 1.12 ms | **1.43 ms** | **4,194,304+** | | Babylon.js | WebGPU | 0.31 ms | **0.46 ms** | 1.13 ms | 1.70 ms | **4,194,304+** | | Babylon.js | WebGL2 | **0.30 ms** | **0.47 ms** | 1.14 ms | **1.40 ms** | **4,194,304+** | | PlayCanvas | WebGPU | 0.37 ms | 0.59 ms | 1.13 ms | 1.71 ms | **4,194,304+** | | PlayCanvas | WebGL2 | 0.33 ms | 0.53 ms | 1.32 ms | 2.02 ms | **4,194,304+** | | Godot | WebGL2 | 0.51 ms | 0.65 ms | 2.05 ms | 3.03 ms | **4,194,304+** | | Bevy | WebGPU | 24.12 ms | 25.65 ms | 211.10 ms | 218.15 ms | 71,680 | | Bevy | WebGL2 | 94.71 ms | 97.27 ms | 895.04 ms | 908.40 ms | 15,872 | ![256 instanced cubes as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-instances-256.jpg) ![100,000 instanced cubes as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-instances-100000.jpg) ![A million instanced cubes as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-instances-1000000.jpg) ### Point lights DriftEngine's desktop figures include point-light shadows, which none of the other engines draws in this scene. They are off in the phone measurements and in these separate picture captures. | Engine | Backend | 64 lights | 256 lights | Most lights at 60 fps | Limits | | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 0.48 ms | 0.70 ms | 4,096+ | shades the nearest 320 of 4096 lights | | DriftEngine | WebGL2 | 0.57 ms | 0.92 ms | 4,096+ | shades the nearest 320 of 4096 lights | | Three.js | WebGPU | 0.51 ms | **0.57 ms** | **4,096+** | | | Three.js | WebGL2 | **0.45 ms** | 1.21 ms | 992 | forward: every light is evaluated for every fragment | | Babylon.js | WebGPU | 0.72 ms | 0.78 ms | **4,096+** | | | Babylon.js | WebGL2 | 0.59 ms | 0.64 ms | **4,096+** | | | PlayCanvas | WebGPU | 0.52 ms | 0.77 ms | **4,096+** | | | PlayCanvas | WebGL2 | 0.48 ms | 0.72 ms | **4,096+** | | | Godot | WebGL2 | 0.62 ms | 0.69 ms | 4,096+ | Compatibility renderer: at most 32 lights per object | | Bevy | WebGPU | 2.52 ms | 2.46 ms | **4,096+** | | | Bevy | WebGL2 | 2.01 ms | 2.39 ms | 4,096+ | WebGL2: at most 256 clusterable lights | ![The floor and pillars under 16 point lights, as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-lights-16.jpg) ![The floor and pillars under 64 point lights, as each of the eleven builds drew it: past 32, Godot lights only the middle of its floor](https://driftengine.dev/stills/articles/bench-lights-64.jpg) ![The floor and pillars under 256 point lights, as each of the eleven builds drew it: Godot lights only the middle of its floor, Babylon.js's floor runs to white, and Bevy on WebGL2 leaves the far end dark](https://driftengine.dev/stills/articles/bench-lights-256.jpg) We measured Godot's floor and pillars with an orange material. The pictures use grey to match the other engines and show the blue lights more clearly. A separate interleaved check found frame times within the observed spread after the colour change. Godot's Compatibility renderer shades at most 32 lights per object, leaving the floor lit around its middle beyond that count. Bevy on WebGL2 leaves the far end dark at 256 lights. Babylon.js's standard material fades each light linearly to its range, so the overlapping lights make the floor white. The floor is still drawn. ### Sponza | Engine | Backend | Download | Load to first frame | Frame | | --- | --- | --- | --- | --- | | DriftEngine (baked) | WebGPU | 44.2 MB | 2445 ms | 1.09 ms | | DriftEngine (baked) | WebGL2 | **44.0 MB** | 1974 ms | 1.25 ms | | Three.js | WebGPU | 73.7 MB | 1778 ms | 2.71 ms | | Three.js | WebGL2 | 73.6 MB | **1638 ms** | 1.85 ms | | Babylon.js | WebGPU | 74.0 MB | 2108 ms | 4.27 ms | | Babylon.js | WebGL2 | 74.0 MB | 2722 ms | 2.47 ms | | PlayCanvas | WebGPU | 73.9 MB | 1753 ms | **1.00 ms** | | PlayCanvas | WebGL2 | 73.9 MB | 1678 ms | 1.44 ms | | Godot (imported) | WebGL2 | 230.1 MB | 6386 ms | 2.71 ms | | Bevy | WebGPU | 77.8 MB | 5680 ms | 4.17 ms | | Bevy | WebGL2 | 77.7 MB | 5515 ms | 9.45 ms | ![Intel's Sponza under the same sun, as each of the eleven builds drew it](https://driftengine.dev/stills/articles/bench-sponza-1.jpg) We set each engine's sun and sky separately. The pictures show those settings and do not rank rendering quality. ## Phone | Engine | Backend | Most draws at 60 fps | Most instances at 60 fps | Most lights at 60 fps | Sponza frame | Sponza first frame | | --- | --- | --- | --- | --- | --- | --- | | DriftEngine | WebGPU | 1,728 | 63,488 | 160 | 37.5 ms | 6386 ms | | DriftEngine | WebGL2 | 2,688 | 262,144 | 192 | 33.3 ms | 3001 ms | | Three.js | WebGPU | 1,024 | 688,128 | **4,096+** | **16.7 ms** | 3226 ms | | Three.js | WebGL2 | 8,704 | 753,664 | 48 | **16.7 ms** | **2561 ms** | | Babylon.js | WebGPU | 1,280 | 753,664 | 1,792 | **16.7 ms** | 3309 ms | | Babylon.js | WebGL2 | 4,096 | **786,432** | **4,096+** | **16.7 ms** | 3326 ms | | PlayCanvas | WebGPU | 7,168 | 540,672 | **4,096+** | **16.7 ms** | 3034 ms | | PlayCanvas | WebGL2 | 7,936 | **819,200** | **4,096+** | **16.7 ms** | 2933 ms | | Godot | WebGL2 | 3,712 | 360,448 | 4,096+ | **16.7 ms** | 38643 ms | | Bevy | WebGPU | **12,288** | 53,248 | 624 | 25.0 ms | 6850 ms | | Bevy | WebGL2 | **12,288** | 13,824 | 4,096+ | 20.8 ms | 7659 ms | ## The feature matrix Four states: **built in**; an **official add-on**, published by the engine's own organisation; a **community plugin**, published by someone else; and **none**, where neither exists. Each state links to the page that shows it, read against the versions above. | Capability | DriftEngine | Three.js | Babylon.js | PlayCanvas | Godot | Bevy | | --- | --- | --- | --- | --- | --- | --- | | Rigid-body physics | [Built in](https://driftengine.dev/docs/simulation/rigid-bodies) | [Official add-on](https://threejs.org/docs/pages/RapierPhysics.html) | [Official add-on](https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine) | [Official add-on](https://developer.playcanvas.com/user-manual/physics/physics-basics/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/physics/physics_introduction.html) | [Community plugin](https://rapier.rs/docs/user_guides/bevy_plugin/getting_started_bevy) | | Character controller | [Built in](https://driftengine.dev/docs/simulation/characters) | [Community plugin](https://rapier.rs/docs/user_guides/javascript/character_controller) | [Official add-on](https://doc.babylonjs.com/features/featuresDeepDive/physics/characterController) | [Official add-on](https://developer.playcanvas.com/user-manual/physics/forces-and-impulses/) | [Built in](https://docs.godotengine.org/en/4.7/classes/class_characterbody3d.html) | [Community plugin](https://rapier.rs/docs/user_guides/bevy_plugin/character_controller) | | Vehicle physics | [Built in](https://driftengine.dev/docs/simulation/vehicles) | [Community plugin](https://rapier.rs/docs/user_guides/javascript/vehicle_controller) | [None found](https://doc.babylonjs.com/features/featuresDeepDive/physics) | [Official add-on](https://developer.playcanvas.com/tutorials/vehicle-physics/) | [Built in](https://docs.godotengine.org/en/4.7/classes/class_vehiclebody3d.html) | [Community plugin](https://rapier.rs/docs/user_guides/bevy_plugin/vehicle_controller) | | Ragdolls | [Built in](https://driftengine.dev/docs/simulation/ragdolls-and-cloth) | [None found](https://threejs.org/docs/pages/RapierPhysics.html) | [Official add-on](https://doc.babylonjs.com/features/featuresDeepDive/physics/ragdolls) | [None found](https://developer.playcanvas.com/user-manual/physics/joints/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/physics/ragdoll_system.html) | [None found](https://bevy.org/assets/) | | Deterministic simulation and replays | [Built in](https://driftengine.dev/docs/concepts/determinism) | [None found](https://threejs.org/docs/pages/Timer.html) | [None found](https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations) | [None found](https://developer.playcanvas.com/user-manual/physics/physics-basics/) | [None found](https://docs.godotengine.org/en/4.7/tutorials/physics/physics_introduction.html) | [Community plugin](https://rapier.rs/docs/user_guides/bevy_plugin/determinism) | | Rollback netcode | [Official add-on](https://driftengine.dev/docs/systems/networking) | [None found](https://github.com/rameshvarun/netplayjs) | [None found](https://doc.babylonjs.com/guidedLearning/networking/Colyseus) | [None found](https://github.com/rameshvarun/netplayjs) | [Community plugin](https://foxssake.github.io/netfox/latest/netfox/guides/network-rollback/) | [Community plugin](https://github.com/gschup/bevy_ggrs) | | WebGPU with an automatic WebGL2 fallback | [Built in](https://driftengine.dev/docs/concepts/backends) | [Built in](https://threejs.org/docs/pages/WebGPURenderer.html) | [Built in](https://doc.babylonjs.com/setup/support/webGPU/webGPUStatus) | [Built in](https://developer.playcanvas.com/user-manual/engine/supported-browsers/) | [None found](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_web.html) | [None found](https://github.com/bevyengine/bevy/tree/v0.20.0/examples#webgl2-and-webgpu) | | Native desktop builds | [Official add-on](https://driftengine.dev/docs/systems/packaging) | [Community plugin](https://www.electronjs.org/docs/latest/) | [Official add-on](https://doc.babylonjs.com/BabylonCrossPlat/multiplePlatforms) | [Community plugin](https://developer.playcanvas.com/user-manual/editor/publishing/desktop/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/export/index.html) | [Built in](https://bevy.org/) | | Android builds | [Official add-on](https://driftengine.dev/docs/systems/packaging) | [Community plugin](https://capacitorjs.com/docs/android) | [Official add-on](https://doc.babylonjs.com/BabylonCrossPlat/multiplePlatforms) | [Community plugin](https://developer.playcanvas.com/user-manual/editor/publishing/mobile/cordova/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_android.html) | [Built in](https://github.com/bevyengine/bevy/tree/v0.20.0/examples#android) | | Navigation meshes | [Official add-on](https://driftengine.dev/docs/simulation/navigation) | [Community plugin](https://github.com/isaac-mason/recast-navigation-js) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/crowdNavigation/createNavMesh) | [Community plugin](https://github.com/isaac-mason/recast-navigation-js) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/navigation/navigation_using_navigationmeshes.html) | [Community plugin](https://github.com/janhohenheim/rerecast) | | Terrain | [Official add-on](https://driftengine.dev/docs/worlds/terrain) | [Community plugin](https://github.com/IceCreamYou/THREE.Terrain) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/ground_hmap) | [None found](https://developer.playcanvas.com/tutorials/terrain-generation) | [Community plugin](https://terrain3d.readthedocs.io/en/stable/docs/platforms.html) | [Community plugin](https://github.com/Katsutoshii/bevy_heightmap) | | Spatial audio | [Official add-on](https://driftengine.dev/docs/content/audio) | [Built in](https://threejs.org/docs/pages/PositionalAudio.html) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic) | [Built in](https://api.playcanvas.com/engine/classes/SoundComponent.html) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_web.html) | [Built in](https://docs.rs/bevy/0.20.0/bevy/audio/struct.SpatialListener.html) | | Gaussian splats | [Official add-on](https://driftengine.dev/docs/worlds/splats) | [Official add-on](https://threejs.org/docs/pages/GaussianSplat.html) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/mesh/gaussianSplatting) | [Built in](https://developer.playcanvas.com/user-manual/gaussian-splatting/) | [None found](https://godotengine.org/asset-library/asset/5076) | [Community plugin](https://github.com/mosure/bevy_gaussian_splatting) | | A scripting language of its own | [Official add-on](https://driftengine.dev/docs/scripting/driftscript) | [None found](https://threejs.org/llms.txt) | [Built in](https://doc.babylonjs.com/features/featuresDeepDive/flowGraph) | [None found](https://developer.playcanvas.com/user-manual/scripting/) | [Built in](https://docs.godotengine.org/en/4.7/tutorials/scripting/gdscript/gdscript_basics.html) | [Community plugin](https://makspll.github.io/bevy_mod_scripting/) | | Coding-agent tooling | [Official add-on](https://driftengine.dev/docs/start/with-an-agent) | [Official add-on](https://threejs.org/llms.txt) | [Official add-on](https://doc.babylonjs.com/llms.txt) | [Official add-on](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas/) | [Community plugin](https://github.com/jame581/GodotPrompter) | [Community plugin](https://github.com/natepiano/bevy_brp) | | Visual editor | [Official add-on](https://github.com/drftrun/driftengine/tree/main/packages/editor) | [Official add-on](https://threejs.org/editor/) | [Official add-on](https://doc.babylonjs.com/communityExtensions/editor) | [Official add-on](https://developer.playcanvas.com/user-manual/editor/) | [Built in](https://docs.godotengine.org/en/4.7/getting_started/introduction/first_look_at_the_editor.html) | [Community plugin](https://bevyskein.dev/) | ### The notes on each cell **Rigid-body physics** - DriftEngine, built in: In @driftengine/physics, which core depends on and re-exports, so installing core installs it. [Source](https://driftengine.dev/docs/simulation/rigid-bodies) - Three.js, official add-on: RapierPhysics, AmmoPhysics and JoltPhysics in three/addons wrap third-party engines. RapierPhysics loads Rapier from a CDN. [Source](https://threejs.org/docs/pages/RapierPhysics.html) - Babylon.js, official add-on: Physics V2 is in @babylonjs/core, but the Havok engine it drives is the separate, official @babylonjs/havok package. [Source](https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine) - PlayCanvas, official add-on: Rigid body and collision components are in the engine; the physics itself is ammo.js, loaded as a separate WebAssembly module. [Source](https://developer.playcanvas.com/user-manual/physics/physics-basics/) - Godot, built in: Rigid bodies, areas and joints in the engine. [Source](https://docs.godotengine.org/en/4.7/tutorials/physics/physics_introduction.html) - Bevy, community plugin: Rapier via bevy_rapier3d, whose 0.37 release targets Bevy 0.20. avian3d is the other option and targets Bevy 0.19 as of this reading. [Source](https://rapier.rs/docs/user_guides/bevy_plugin/getting_started_bevy) **Character controller** - DriftEngine, built in: CharacterController with acceleration, air control and a jump buffer, in @driftengine/physics. [Source](https://driftengine.dev/docs/simulation/characters) - Three.js, community plugin: Rapier's kinematic character controller via @dimforge/rapier3d. The official physics_rapier_character_controller example calls it directly; the RapierPhysics add-on does not wrap it. [Source](https://rapier.rs/docs/user_guides/javascript/character_controller) - Babylon.js, official add-on: PhysicsCharacterController in Physics V2, which runs on the separate @babylonjs/havok package. [Source](https://doc.babylonjs.com/features/featuresDeepDive/physics/characterController) - PlayCanvas, official add-on: First-person and third-person controller scripts in the engine repository's scripts/esm. No controller component. [Source](https://developer.playcanvas.com/user-manual/physics/forces-and-impulses/) - Godot, built in: CharacterBody3D. [Source](https://docs.godotengine.org/en/4.7/classes/class_characterbody3d.html) - Bevy, community plugin: bevy_rapier3d's kinematic character controller. bevy-tnua is an alternative and targets Bevy 0.19 so far. [Source](https://rapier.rs/docs/user_guides/bevy_plugin/character_controller) **Vehicle physics** - DriftEngine, built in: A raycast Vehicle with tyre curves, in @driftengine/physics. [Source](https://driftengine.dev/docs/simulation/vehicles) - Three.js, community plugin: Rapier's raycast vehicle controller via @dimforge/rapier3d, used directly by the official physics_rapier_vehicle_controller example. [Source](https://rapier.rs/docs/user_guides/javascript/vehicle_controller) - Babylon.js, none found: No vehicle controller in core or the official add-ons. Forum projects build cars from rigid bodies, joints and shape casts, and no maintained package was found. [Source](https://doc.babylonjs.com/features/featuresDeepDive/physics) - PlayCanvas, official add-on: An official tutorial and a script in the engine repository drive ammo.js's RaycastVehicle. No vehicle component. [Source](https://developer.playcanvas.com/tutorials/vehicle-physics/) - Godot, built in: VehicleBody3D with VehicleWheel3D. [Source](https://docs.godotengine.org/en/4.7/classes/class_vehiclebody3d.html) - Bevy, community plugin: bevy_rapier3d's raycast vehicle controller. [Source](https://rapier.rs/docs/user_guides/bevy_plugin/vehicle_controller) **Ragdolls** - DriftEngine, built in: A ragdoll built from a skeleton, and cloth, in @driftengine/physics. [Source](https://driftengine.dev/docs/simulation/ragdolls-and-cloth) - Three.js, none found: No ragdoll add-on or maintained package found. Joints in Rapier or Ammo can be assembled into one by hand. [Source](https://threejs.org/docs/pages/RapierPhysics.html) - Babylon.js, official add-on: A Ragdoll class in Physics V2 builds one from a skeleton and a list of shapes, on the separate @babylonjs/havok package. [Source](https://doc.babylonjs.com/features/featuresDeepDive/physics/ragdolls) - PlayCanvas, none found: No ragdoll helper. The official ragdoll example assembles one by hand from the joint component, which is marked alpha. [Source](https://developer.playcanvas.com/user-manual/physics/joints/) - Godot, built in: Physical bones driven from a Skeleton3D. [Source](https://docs.godotengine.org/en/4.7/tutorials/physics/ragdoll_system.html) - Bevy, none found: No ragdoll plugin found. Joints in bevy_rapier3d or avian3d can be assembled into one by hand. [Source](https://bevy.org/assets/) **Deterministic simulation and replays** - DriftEngine, built in: A fixed-step loop, a seeded generator whose sequence is frozen, and world fingerprints, so a replay or a test reruns exactly. [Source](https://driftengine.dev/docs/concepts/determinism) - Three.js, none found: three.js is a renderer rather than a simulation runtime: it has a seeded random function (MathUtils.seededRandom) but no fixed-step loop or replay, and its Timer reports variable frame deltas. Rapier's deterministic builds cover physics only. [Source](https://threejs.org/docs/pages/Timer.html) - Babylon.js, none found: Partial. A deterministicLockstep engine option steps physics and animation at a fixed rate, which the docs suggest for replays, but there is no seeded random generator and no cross-machine guarantee. [Source](https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations) - PlayCanvas, none found: Partial. Physics steps at a fixed 1/60 s, but the engine random helpers use Math.random with no seed and nothing promises reproducible runs. [Source](https://developer.playcanvas.com/user-manual/physics/physics-basics/) - Godot, none found: The physics docs state that physics is not deterministic. RandomNumberGenerator takes a seed, but its reference calls the algorithm an implementation detail. [Source](https://docs.godotengine.org/en/4.7/tutorials/physics/physics_introduction.html) - Bevy, community plugin: Bevy has a built-in FixedUpdate schedule. Seeded, portable random numbers come from bevy_rand and cross-platform physics from bevy_rapier3d's enhanced-determinism feature with Bevy's libm feature. [Source](https://rapier.rs/docs/user_guides/bevy_plugin/determinism) **Rollback netcode** - DriftEngine, official add-on: @driftengine/network: lockstep and rollback over a lossy link, checked by fingerprints. [Source](https://driftengine.dev/docs/systems/networking) - Three.js, none found: Nothing three.js-specific. NetplayJS, an engine-agnostic rollback library, has had no npm release since April 2023. [Source](https://github.com/rameshvarun/netplayjs) - Babylon.js, none found: The networking guide uses Colyseus for server-authoritative state sync. No rollback layer found. [Source](https://doc.babylonjs.com/guidedLearning/networking/Colyseus) - PlayCanvas, none found: Nothing PlayCanvas-specific. NetplayJS, an engine-agnostic rollback library, has had no npm release since April 2023. [Source](https://github.com/rameshvarun/netplayjs) - Godot, community plugin: netfox (foxssake/netfox), addons for Godot 4.x with rollback, client-side prediction and server reconciliation. [Source](https://foxssake.github.io/netfox/latest/netfox/guides/network-rollback/) - Bevy, community plugin: bevy_ggrs, GGRS rollback for Bevy. Its latest release targets Bevy 0.19. [Source](https://github.com/gschup/bevy_ggrs) **WebGPU with an automatic WebGL2 fallback** - DriftEngine, built in: createRenderer tries WebGPU and accepts a device only after drawing a probe frame on it, else WebGL2. [Source](https://driftengine.dev/docs/concepts/backends) - Three.js, built in: WebGPURenderer uses WebGPU when the browser has it and falls back to a WebGL 2 backend. [Source](https://threejs.org/docs/pages/WebGPURenderer.html) - Babylon.js, built in: EngineFactory.CreateAsync creates a WebGPU engine when supported, otherwise a WebGL one. The plain Engine class is WebGL only. [Source](https://doc.babylonjs.com/setup/support/webGPU/webGPUStatus) - PlayCanvas, built in: createGraphicsDevice tries WebGPU when it is listed in deviceTypes and falls back to WebGL 2. WebGL 2 is the default. [Source](https://developer.playcanvas.com/user-manual/engine/supported-browsers/) - Godot, none found: The web export renders with WebGL 2 through the Compatibility renderer. The docs state that Godot does not support WebGPU. [Source](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_web.html) - Bevy, none found: webgl2 and webgpu are build-time features. A build with webgpu enabled overrides webgl2 and will not run in browsers without WebGPU. [Source](https://github.com/bevyengine/bevy/tree/v0.20.0/examples#webgl2-and-webgpu) **Native desktop builds** - DriftEngine, official add-on: @driftengine/package builds Linux, Windows and macOS apps; the native host runs a game on Dawn and SDL. [Source](https://driftengine.dev/docs/systems/packaging) - Three.js, community plugin: No packaging of its own. A web shell such as Electron or Tauri wraps the page. [Source](https://www.electronjs.org/docs/latest/) - Babylon.js, official add-on: Babylon Native runs Babylon.js in native apps on Windows, macOS and Linux. It is a public preview in source form. The docs also suggest Electron. [Source](https://doc.babylonjs.com/BabylonCrossPlat/multiplePlatforms) - PlayCanvas, community plugin: The docs recommend NW.js, a third-party web shell, for Windows, macOS and Linux executables. [Source](https://developer.playcanvas.com/user-manual/editor/publishing/desktop/) - Godot, built in: Export to Windows, Linux and macOS from the same project. [Source](https://docs.godotengine.org/en/4.7/tutorials/export/index.html) - Bevy, built in: Windows, macOS and Linux. [Source](https://bevy.org/) **Android builds** - DriftEngine, official add-on: @driftengine/package builds an Android app. [Source](https://driftengine.dev/docs/systems/packaging) - Three.js, community plugin: No packaging of its own. A WebView shell such as Capacitor or Cordova wraps the page. [Source](https://capacitorjs.com/docs/android) - Babylon.js, official add-on: Babylon Native and Babylon React Native target Android. The docs also suggest Ionic. [Source](https://doc.babylonjs.com/BabylonCrossPlat/multiplePlatforms) - PlayCanvas, community plugin: Apache Cordova wraps the app in a WebView. PlayCanvas publishes a tool that prepares Editor projects for it. [Source](https://developer.playcanvas.com/user-manual/editor/publishing/mobile/cordova/) - Godot, built in: Android export from the editor. [Source](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_android.html) - Bevy, built in: Built with cargo-ndk and Gradle, as the examples README describes. [Source](https://github.com/bevyengine/bevy/tree/v0.20.0/examples#android) **Navigation meshes** - DriftEngine, official add-on: @driftengine/nav [Source](https://driftengine.dev/docs/simulation/navigation) - Three.js, community plugin: recast-navigation-js with its @recast-navigation/three helpers. [Source](https://github.com/isaac-mason/recast-navigation-js) - Babylon.js, built in: RecastJSPlugin in core, which needs the recast-detour library. Its successor, built on recast-navigation-js, is in the official @babylonjs/addons package. [Source](https://doc.babylonjs.com/features/featuresDeepDive/crowdNavigation/createNavMesh) - PlayCanvas, community plugin: recast-navigation-js with its @recast-navigation/playcanvas helpers. [Source](https://github.com/isaac-mason/recast-navigation-js) - Godot, built in: NavigationMesh baking and the navigation server. [Source](https://docs.godotengine.org/en/4.7/tutorials/navigation/navigation_using_navigationmeshes.html) - Bevy, community plugin: bevy_rerecast, a Rust port of Recast, with bevy_landmass or vleue_navigator for agents. All target Bevy 0.19 so far. [Source](https://github.com/janhohenheim/rerecast) **Terrain** - DriftEngine, official add-on: @driftengine/terrain [Source](https://driftengine.dev/docs/worlds/terrain) - Three.js, community plugin: THREE.Terrain (three.terrain.js), procedural height-map terrain. The official examples build terrain from noise but ship no terrain add-on. [Source](https://github.com/IceCreamYou/THREE.Terrain) - Babylon.js, built in: Ground from a height map in core. The Dynamic Terrain extension, a community project, adds a terrain that follows the camera. [Source](https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/ground_hmap) - PlayCanvas, none found: No terrain system. An official tutorial builds a mesh from a height map with the mesh API, and no maintained terrain package was found. [Source](https://developer.playcanvas.com/tutorials/terrain-generation) - Godot, community plugin: Terrain3D (TokisanGames). Its docs call web exports very experimental. HTerrain, written in GDScript, is an alternative. [Source](https://terrain3d.readthedocs.io/en/stable/docs/platforms.html) - Bevy, community plugin: bevy_heightmap builds meshes from height maps and targets Bevy 0.19. It is a small project, and no larger maintained terrain plugin was found. [Source](https://github.com/Katsutoshii/bevy_heightmap) **Spatial audio** - DriftEngine, official add-on: @driftengine/audio [Source](https://driftengine.dev/docs/content/audio) - Three.js, built in: PositionalAudio and AudioListener over the Web Audio API. [Source](https://threejs.org/docs/pages/PositionalAudio.html) - Babylon.js, built in: Spatial sounds and a listener in the audio engine (AudioEngineV2). [Source](https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic) - PlayCanvas, built in: The sound component's positional mode, heard through an audio listener component. [Source](https://api.playcanvas.com/engine/classes/SoundComponent.html) - Godot, built in: AudioStreamPlayer3D. On the web the default sample playback may not handle positional audio correctly, and the Stream playback type restores it at higher latency. [Source](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_web.html) - Bevy, built in: SpatialListener with spatial audio sinks, panned by ear position. [Source](https://docs.rs/bevy/0.20.0/bevy/audio/struct.SpatialListener.html) **Gaussian splats** - DriftEngine, official add-on: @driftengine/splats [Source](https://driftengine.dev/docs/worlds/splats) - Three.js, official add-on: GaussianSplat add-on with SPLAT and SPZ loaders, for WebGPURenderer only. The community Spark library (@sparkjsdev/spark) is a larger alternative. [Source](https://threejs.org/docs/pages/GaussianSplat.html) - Babylon.js, built in: GaussianSplattingMesh loads PLY, SPLAT, SPZ and SOG. [Source](https://doc.babylonjs.com/features/featuresDeepDive/mesh/gaussianSplatting) - PlayCanvas, built in: The gsplat component and asset type, with streamed levels of detail. [Source](https://developer.playcanvas.com/user-manual/gaussian-splatting/) - Godot, none found: For the web export. GDGS (community) renders splats on desktop but needs the Forward+ renderer and compute shaders, which the web export does not have. [Source](https://godotengine.org/asset-library/asset/5076) - Bevy, community plugin: bevy_gaussian_splatting. Its latest release targets Bevy 0.19. [Source](https://github.com/mosure/bevy_gaussian_splatting) **A scripting language of its own** - DriftEngine, official add-on: DriftScript, through @driftengine/script [Source](https://driftengine.dev/docs/scripting/driftscript) - Three.js, none found: Code is written in JavaScript or TypeScript. No scripting language of its own. [Source](https://threejs.org/llms.txt) - Babylon.js, built in: Flow Graph, a node-based visual scripting system in core with an official editor. Visual only: there is no text scripting language. [Source](https://doc.babylonjs.com/features/featuresDeepDive/flowGraph) - PlayCanvas, none found: Scripts are JavaScript or TypeScript classes. No scripting language of its own. [Source](https://developer.playcanvas.com/user-manual/scripting/) - Godot, built in: GDScript. C# projects cannot be exported to the web in Godot 4. [Source](https://docs.godotengine.org/en/4.7/tutorials/scripting/gdscript/gdscript_basics.html) - Bevy, community plugin: bevy_mod_scripting adds Lua and Rhai. Its latest release targets Bevy 0.19. [Source](https://makspll.github.io/bevy_mod_scripting/) **Coding-agent tooling** - DriftEngine, official add-on: npm create @driftengine starts a project with instructions for an agent, the driftengine skill and a check that opens the game on both backends; llms.txt and a skills index on driftengine.dev. [Source](https://driftengine.dev/docs/start/with-an-agent) - Three.js, official add-on: llms.txt and llms-full.txt published on threejs.org. [Source](https://threejs.org/llms.txt) - Babylon.js, official add-on: llms.txt on doc.babylonjs.com. The @babylonjs/mcp-servers package also lets agents drive the node and GUI editors. [Source](https://doc.babylonjs.com/llms.txt) - PlayCanvas, official add-on: npm create playcanvas includes PlayCanvas Skills for coding agents. An llms.txt and an Editor MCP server are also published. [Source](https://developer.playcanvas.com/user-manual/getting-started/start-with-create-playcanvas/) - Godot, community plugin: GodotPrompter, agent skills for Godot 4.x. The project publishes no llms.txt or agent skill of its own. [Source](https://github.com/jame581/GodotPrompter) - Bevy, community plugin: bevy_brp_mcp, an MCP server that lets coding agents inspect and drive a running app over the Bevy Remote Protocol, with Bevy 0.20 support. It is not a skill or an llms.txt, and the project publishes neither. [Source](https://github.com/natepiano/bevy_brp) **Visual editor** - DriftEngine, official add-on: @driftengine/editor holds a scene tree, an inspector and play-in-editor, and an editor app lives in the engine repository. A full visual editor is the next step on the roadmap. [Source](https://github.com/drftrun/driftengine/tree/main/packages/editor) - Three.js, official add-on: A browser scene editor kept in the editor folder of the three.js repository. [Source](https://threejs.org/editor/) - Babylon.js, official add-on: The Babylon.js Editor lives in the BabylonJS GitHub organisation, though its docs call it a community project. The official Inspector edits a running scene. [Source](https://doc.babylonjs.com/communityExtensions/editor) - PlayCanvas, official add-on: The browser-based Editor is a hosted service separate from the MIT engine. Its front end is published on GitHub under MIT. [Source](https://developer.playcanvas.com/user-manual/editor/) - Godot, built in: The Godot editor. [Source](https://docs.godotengine.org/en/4.7/getting_started/introduction/first_look_at_the_editor.html) - Bevy, community plugin: Skein uses Blender as the scene editor. Bevy has no editor yet, and its 0.20 notes describe editor building blocks. [Source](https://bevyskein.dev/) ## Sponza We used Intel Sponza (2022), commissioned by Frank Meinl and sponsored by Anton Kaplanyan, from the [Intel Sample Library](https://www.intel.com/content/www/us/en/developer/topic-technology/graphics-research/samples.html) under Creative Commons Attribution. Reference photographs are by Katica Putica and Princino.photo, Dubrovnik. We resized the base scene's textures to at most 1,024 pixels on a side and removed its lights and cameras before applying the benchmark's settings. The model and texture files are not distributed here. Intel does not endorse this benchmark or any engine in it.