Photoreal 3D games from code
A procedure for turning a code-generated 3D scene into a short, playable game that reads as photographic. The target is a game, not a still, a tech demo, or a walkthrough: a player with a verb, a system that answers, a way to win, and a way to lose.
Nothing here assumes a genre. The subject decides the verb — a container yard suggests hauling a load before a shift ends; a workshop suggests repairing a machine; a stairwell suggests getting out without being seen. Shooters are one instantiation among many, and the same procedure produces them only when the subject asks for one.
The procedure is tool-agnostic. It assumes an agent that can edit files, run commands, and inspect images. Nothing below depends on a specific engine, library version, or vendor product.
Origin and significance. This skill exists to answer a question posed by Saltline — a 1,423,668-byte single-file browser shooter with zero external assets, made with Claude Fable 5.2. The interesting part was not the size; it was that the model wrote the generator. This skill packages that production discipline into executable gates, so a low-cost model (such as DeepSeek V4.1 Flash) can be held to the same standard. The result is not the same game; it is the same discipline — and the evidence is recorded in the repository's case studies.
The bundled harness is optional but recommended: it makes the gates runnable
instead of aspirational. It needs Node.js 22+, Python 3.10+ with Pillow, and a
Chrome/Chromium binary (CHROME_PATH if it is not in a standard location). The
skill text itself has no dependencies.
How to run this with a low-cost model
The skill is written so that a weak model can execute it: every judgement that matters is delegated to a check, and the model's job is to fill tables and apply the top-ranked fix. Follow these rules literally.
- Do not design architecture. Start from a skeleton that already has: the
render harness, the page contract (
__READY,__STATS,__SCENE,__AUDIT,__COLLIDERS,__BOUNDS,__TESTMOVE,__TEST,__PRODUCT), the post chain, a finished-game shell (title, settings, pause, save, touch, HUD markers) and an empty kit table. Copy it, then fill tables. Architecture invented per run is where weak models fail. - Fill, don't invent. The work products are six tables: product (shell + content), art direction, kit (dimensions + parts + decals), surfaces (albedo/roughness/normal), lights (position + fixture), and the loop (verb/system/feedback/failure/test).
- Product first, then look.
product → census → lights → collide → playtest → mobile → look. A frame that is beautiful but has no settings, no second enemy role, no objective markers or no touch path is not a finished round. - One change per round, then run all gates. A round is only valid if no gate regresses. A visual gain that breaks the product or the loop is reverted.
- Never self-assess. If a gate disagrees with your opinion, the gate wins. If a gate is wrong, fix the gate with a counter-example — never bypass it.
- Stop at the budget or the plateau, whichever comes first, and report the worst camera and the failing gate list.
A model that follows those six rules produces comparable output at a fraction of the cost; a model that skips rule 5 produces plausible-looking regressions.
Deliverable contract
A run is complete only when these exist and all gates are green:
| Artifact | Check |
|---|---|
| one self-contained HTML, no network requests | load with the network disabled |
page contract exposed (__READY, __STATS, __SCENE, __AUDIT, __COLLIDERS, __BOUNDS, __TESTMOVE, __TEST, __GAME, __PRODUCT) | harness reads them |
| finished-game shell | menu, settings, pause, save, touch, HUD hierarchy, end/restart |
| content breadth | ≥2 enemy/interactable roles, ≥2 tools, ≥1 objective chain, ≥3 beats |
| census report | coverage = 100%, zero failures |
| light audit | every light anchored to a fixture |
| collision report | zero penetrations, zero out-of-bounds, collider parity 100% |
| playtest | loop completable, failure path reachable, restart works |
| mobile report | 390×844 layout, no horizontal overflow, touch controls present |
| box report on 3–6 subject objects | each metric >= 0.8 of the reference |
| frame score | reported, but never used to override a gate |
Finished-product contract
A playable frame is not a finished game. The loop gates protect behaviour; the
product gates protect the shell, content breadth and first impression. Declare the
following in the page so harness/product.mjs can check it without reading the
model's mind.
| Artifact | Minimum |
|---|---|
| Screens | menu, playing, paused, settings, lost, won |
| Title screen | visible on load; HUD hidden; title, premise, start, settings/controls |
| Settings | sensitivity, volume, FOV, invert-Y, quality (or an equivalent set) |
| Persistence | one key survives reload (best score/progress/settings) |
| Input | keyboard + mouse + touch; fallback aim when pointer lock fails |
| Objectives | ≥1 chain with ≥3 beats and world markers/compass |
| Roles | ≥2 enemy/obstacle/interactable roles, not one recoloured |
| Tools | ≥2: a primary and a secondary verb (weapon/tool/ability) |
| HUD | objective+progress, survival, weapon/ammo, context prompt, compass/markers, subtitles |
| Audio | mute + ≥6 state-change events |
| Cameras | hero + close-up still cameras in __PRODUCT.cameras |
| Performance | declared budgets for calls/tris/lights, measured after start |
| Mobile | 390×844 without horizontal overflow; touch controls reachable |
Content budget for a vertical slice
Fill this before any art pass. A vertical slice is one 3–8 minute session with one complete objective chain, two roles, one signature system and a designed shell. It is smaller than a demo reel and larger than a tech demo.
| Slot | Vertical slice | Finished small game |
|---|---|---|
| Objectives | 1 chain, 3 beats | 1–3 chains, 5–8 beats |
| Enemy/interactable roles | 2 | 3–5 + a climax |
| Weapons/tools | 2 (primary + secondary) | 3–5 |
| Player verbs | move, aim, fire, reload | + crouch/jump/interact/ability |
| World | one location, 3 depth layers | 2–3 connected spaces |
| Shell | title, pause, settings, end | + save, quality, touch |
| Session | 3–8 min | 10–30 min |
The manifest is a claim; the gate checks DOM behaviour and the declared counts. Do not declare what the page does not do.
window.__PRODUCT = {
title: { name: 'Game title', start: '#start', hud: '#hud', hudHiddenOnTitle: true },
screens: ['menu', 'playing', 'paused', 'settings', 'lost', 'won'],
ui: { start: '#start', hud: '#hud', pause: '#pause', settings: '#settings', end: '#end', touch: '#touch' },
settings: ['sensitivity', 'volume', 'fov', 'invertY', 'quality'],
persistence: ['game.best'],
input: { keyboard: true, mouse: true, touch: true },
content: {
objectives: [{ id: 'objective-1', title: 'Objective', steps: 3 }],
roles: ['role-a', 'role-b'],
tools: ['tool-a', 'tool-b'],
beats: ['intro', 'contact', 'mid', 'climax', 'win'],
},
hud: ['objective', 'compass', 'health', 'ammo', 'prompt', 'subtitles'],
audio: { events: 10, mute: true },
perf: { maxCalls: 700, maxTris: 400000, maxLights: 14 },
cameras: [
{ name: 'hero', cam: [0.5, 1.7, 10, -2.6, 1.3, -10] },
{ name: 'close', cam: [-6.4, 1.4, 5.2, -9.9, 1.0, 2.2] },
],
test: { start: 'start', pause: 'pause', resume: 'resume', settings: 'openSettings', save: 'save' },
};
Standard __TEST actions (extra actions allowed): start, pause, resume,
openSettings, closeSettings, save, state. They must work without pointer
lock and return a JSON-safe snapshot. The title screen must hide the HUD; starting
must reveal it; settings, pause and end screens must be DOM-inspectable.
When to use
- A scene is geometrically correct but reads as flat, plastic, or "generated".
- A render must match a reference photograph, concept, or art direction.
- Lighting, materials, or composition need to be improved in a controlled way.
- A long generation needs to stay coherent across many iterations.
When not to use
- Deliberately stylised output (flat shading, cel, diagrammatic, UI-like). Those need consistent abstraction, not physical plausibility. The procedure transfers, but replace the photoreal profile and look gate with a style-consistent one; a stylised scene measured against a photographic profile loses by construction, not by quality.
- Precision tasks (CAD, engineering drawings) where readability beats realism.
- Scenes with no camera: data visualisation, node graphs, UI.
Model of the problem
Perceived realism comes from five levers. Apply them in this order; the return on effort drops sharply as you go down the list.
- Light — a single dominant source with a defined direction, colour, and elevation, plus an environment for reflections and fill.
- Materials — variation in roughness, normal, and grime, rather than colour alone.
- Composition and density — objects at several scales and depths, with a clear focal point and readable scale cues.
- Image formation — anti-aliasing, tonemapping, bloom, grain, vignette.
- Geometry detail — the last resort, and only where it survives to several pixels on screen.
Two consequences worth stating explicitly:
- Detail smaller than roughly two pixels is removed by anti-aliasing and does not contribute to the image. Adding polygon count at that scale is wasted.
- A scene can have a correct exposure and still look empty. Emptiness is a density problem, not a grading problem.
Three more consequences for a finished game:
- A frame is necessary but not sufficient. The product layer — title key art, settings, pause, save, touch, objective markers, radio/subtitles, content breadth — is judged before the player notices the lighting.
- The five levers are subject-independent. They apply to a daylight port, a bright interior, a snowy field or a stylised arena. Night/rain/fog are one scenario, not the default.
- The frame score is a compass for one reference look. It cannot tell a finished game from a beautiful demo.
Workflow
Each step has an output. Do not begin the next step without it.
Step 1 — Make the render observable (recommended before any scene work)
Produce a repeatable way to capture a frame and inspect it.
Output: one command that returns an image and, ideally, a few numbers.
If your environment already has a screenshot tool, use it. If not, build the smallest one that works:
- Launch a headless browser against a local static server.
- Wait for a readiness signal from the page (see contract below), then capture.
- Optionally compute image statistics: exposure histogram, clipping, colour count, edge density.
Page contract that keeps captures deterministic:
window.__READY = true; // set after a few rendered frames
window.__STATS = { calls, triangles }; // optional renderer counters
// optional query parameters
// ?shot=1 hide UI
// ?cam=x,y,z,tx,ty,tz fixed camera
// ?seed=N fixed random seed
Rules:
- Fixed camera, fixed seed, fixed viewport for every comparison.
- Store each capture under a versioned name; never overwrite the previous one.
- If no metrics are available, keep the images and compare them side by side. Visual comparison is sufficient; metrics only make attribution faster.
Step 2 — Write an art direction brief
Output: a short table. Every row must be concrete enough to implement.
| Decision | Content |
|---|---|
| Subject | what the frame is about, at what scale |
| Time and weather | determines fog, reflection strength, contrast |
| Key light | direction, elevation, colour temperature, intensity |
| Sky and ambient | colour of shadow fill |
| Material family | which surfaces exist, how rough, how wet |
| Focal point | what the eye should land on first |
| Constraints | what must not appear (e.g. pure white, flat ground, clear sky) |
Guidance:
- Choose one dominant light story. Additional sources are fill, bounce, or practicals, and must be subordinate.
- Constrain the subject before adding detail. Conditions that reduce visible complexity — night, rain, fog, dust, backlight, industrial or interior settings — are legitimate and effective choices, not shortcuts.
- Pick a key elevation deliberately. Shadow length scales as
height / tan(elevation): a low key produces long shadows that may put the whole foreground in shade, which reads as "no shadows". Mid elevations (roughly 20–30°) usually give both form and a lit area to contrast against. - Choose the lighting scenario before the kit. Do not default to night, rain or industrial interiors because they hide missing detail. Night is one option; a backlit dawn or a bright interior is harder and often more convincing.
| Scenario | Key | Fill / IBL | Air | Signature material |
|---|---|---|---|---|
| Night industrial | cool low-mid key, practicals | sky env, warm pools | exponential, sky-coloured | wet ground, emissive fixtures |
| Overcast daylight | broad sky key, 35–60° | strong IBL | thin aerial perspective | matte concrete, puddles |
| Golden hour / backlight | low warm key behind subject | cool sky fill | long haze, rim | wet asphalt, glass, metal |
| Clear noon | high key, hard shadows | sky fill + bounce | minimal | sand, stone, paint |
| Interior practicals | window + few warm sources | window/sky env | light shafts, dust | wood, fabric, metal |
| Underground / artificial light | practicals + emissives | low ambient | volumetric | wet concrete, signs |
A backlit scene is not "easier": it exposes clipped highlights, colour casts and weak silhouettes. Fix exposure and highlight rolloff before adding atmosphere.
Step 3 — Light
Do:
- Build the sky as a function of direction, not a flat colour: zenith, horizon, and a tighter glow around the key.
- Generate an environment map from that sky and use it for image-based lighting. Metals and wet surfaces need something to reflect; this is the highest-value step in the whole procedure.
- Add volumetric or exponential fog whose colour follows the sky. A single fog colour against a graded sky produces a visible horizon seam.
- Enable shadows on the key light only. Set a normal bias to avoid self-shadow acne. If shadow camera bounds are changed, update the projection matrix.
Check: the frame has a readable light direction, a lit area, a shadow area, and no hard seam at the horizon.
Step 4 — Materials
Do:
- Keep the engine's physically based material and inject procedural variation, rather than writing a custom lighting model. Shadows, image-based lighting, and fog then continue to work.
- Vary at least three properties: base colour (macro variation), roughness (wet/dry, worn/smooth), and normal (surface relief).
- Add grime as a function of world position, not UV: darkening near the ground, streaks running downward, accumulation in crevices.
- Convert height fields to normals at a scale that survives on screen, and damp the effect with distance to avoid shimmer.
- Use triplanar projection for objects without sane UVs.
Check: no two large surfaces share the same roughness, and every horizontal surface shows variation at more than one frequency.
Step 5 — Composition and density
Do:
- Build a kit of parts with real dimensions, then assemble scenes from it. Reuse through instancing and merged geometry with vertex colours.
- Breadth is a quality of the world, not of one prop: aim for ≥12 distinct prop families before polish. A repeated family needs ≥3 variants (colour, size, state, signage) or it reads as a copy-paste wall.
- Place objects at several scales and depths. A row of identical objects reads as a wall regardless of how detailed each one is.
- Provide scale cues near the camera: railings, furniture, door frames, small clutter.
- Give every object contact with the ground: a shadow, an ambient-occlusion decal, or both.
- Frame with a foreground, a subject, and a background layer. Empty foregrounds and empty skies are the most common composition failures.
- Add a landmark at 30–80 m and a second depth layer at 10–20 m. A scene with only near-field clutter and no far silhouette reads as a room, not a place.
- Build one signature surface system and reuse it across the world: wet ground with planar reflection and a wetness mask; wind-blown foliage; dust; snow; sand. It is a system, not one material parameter. It should be visible in the title frame and in every gameplay frame.
- Decals deserve an atlas: impact per surface, oil/rust/grime, signage and paint. Verify attachment mechanically; a floating decal costs more than none.
Check: at least three distinct object scales are visible, the nearest object is within a few metres, the frame has a clear focal point, and ≥12 prop families exist across the location (not necessarily all in one frame).
Step 6 — Image formation
Do:
- Render with multisampling or a post-process anti-aliasing pass. Missing anti-aliasing is the single most reliable "generated" tell.
- Compose in a linear colour space, apply a filmic or ACES-style tonemap once, then encode to sRGB once.
- Add bloom from a thresholded, blurred copy of the bright areas.
- Add a small amount of grain and a gentle vignette; both mask banding and separate a render from a screenshot.
Check: no aliasing on high-contrast edges, no clipped highlights, no banding in large gradients.
Step 7 — Atmosphere and motion (as applicable)
Atmosphere: one draw call per weather system. Particles can be positioned and animated entirely in a vertex shader from per-particle seeds.
Motion, for interactive or animated targets: put camera and interaction parameters in one table rather than scattering constants (walk and run speed, acceleration, eye height, field of view, bob amplitude, view kick, recovery). Motion quality dominates perceived quality in interactive scenes.
Audio, if required: synthesis and filtering are sufficient; recorded assets are optional.
One-shot protocol (no questions asked)
"One shot" means one request and no clarification — not one pass of the model.
A single blind pass of 500 lines will contain silent breakages; this run produced
three (an undefined identifier, a String.replace dollar pattern, a reversed
smoothstep) and each rendered a near-black frame that only the loop caught.
Encode the loop, then run it without asking. Spend the budget in this order:
- Build the shell and the vertical slice first. Title frame, menu, settings,
pause, save, touch, one objective chain, two roles, two tools, one signature
surface system, win/lose/restart. Run
product,mobileandplaytestbefore any global grading. If the product gate is red, stop: lighting cannot fix it. - Capture or load the project's reference profile (2–3 target frames). If
absent, capture them and run
calibrate.py. - Write the scene so it satisfies the page contract (
__READY,__STATS,__PRODUCT,?cam,?shot,?seed) before any art code. - Loop until
min(energy across cameras) >= targetor the round budget ends:- render the fixed cameras (hero + close), score each, keep the worst;
- run
diagnose.pyon the worst camera: it prints the three lowest ratios with the mapped fix, so no judgement is required to pick the next change; - apply only the top item — one row, one change;
- re-render; keep the change only if the worst camera improved and no gate regressed.
- Report the worst camera, the per-metric table, and the remaining gaps.
Illustrative budget split for a finished small game: product/shell/content 40%, world/kit 25%, look 25%, QA/polish 10%. A run that spends most of its rounds on exposure and bloom will pass the look gate and still read as a demo.
Metric → fix map:
| Lowest metric | Fix |
|---|---|
| fine | film grain, micro-normal maps, high-frequency albedo noise — but only up to the mip limit: pushing a normal map past ~8 cm wavelength per screen pixel averages to flat grey and lowers measured detail |
| mid | mid-scale objects, panel seams, decals, hardware on large faces |
| coarse | depth layers: foreground occlusion, second/third row, silhouette break |
| std | contrast lighting: darker fill, stronger key and practicals |
| p10 / flat tiles | unproject the flat tile centres, place detail there |
| sky band | cloud octaves, deck rim, cirrus, horizon haze |
| saturation high | desaturate composite, mute the palette |
| tone fail | fix exposure before anything else |
Exit conditions (all must be explicit, or the loop runs forever):
- Reached: worst-camera energy ≥ target for two consecutive rounds.
- Plateau: two consecutive rounds with no metric gain → stop and report.
- Regression: any change that lowers the worst camera → revert immediately.
- Budget: a fixed number of rounds (start with 6).
- Eye veto: a human or a visual check rejects the frame → stop, regardless of score. Scores are gameable: in this project a noise-based "cirrus" layer raised the sky metric while reading as television static. If a change raises the number and looks worse, the number is wrong, not the eye.
Guardrails: never keep a frame whose worst-camera score dropped; keep every previous render for comparison; stop after two rounds with no gain and report the plateau instead of continuing.
Iteration protocol
- Change one lever per round.
- Record, for each round: hypothesis, change, observed result, verdict.
- Compare against the previous capture, never against memory.
- Stop when two consecutive rounds change nothing measurable. At that point the remaining gap is content or composition, not shading.
Quality checklist
Binary items; a scene is not finished until all are true.
- A single dominant light direction is readable from the image alone.
- Shadowed areas carry colour from the sky, not black.
- No horizon seam, no visible ground-plane edge.
- No aliasing on strong edges.
- Every object is visually grounded (shadow or contact occlusion).
- At least three object scales and three depth layers are present.
- Materials vary in roughness and normal, not only in colour.
- Highlights are not clipped; blacks retain detail.
- A fixed camera and seed reproduce the same frame.
- The scene runs at interactive frame rate if it is interactive.
Executable contracts
Prose constraints do not survive contact with a weaker model; executable ones do. Two contracts make the budget checkable instead of aspirational:
Audit manifest. The scene exposes its own object budget, so a script can check it without reading the model's mind:
window.__AUDIT = [
{ name: 'hero-prop', size: 3.4, segments: 26, parts: 14,
texelDensity: 110, bevel: false, ao: false },
];
A 20-line checker compares each row against the per-object budget table and prints failures. Failures are fixed before any render is judged.
Defect list. diagnose.py converts a render into at most three ranked actions
with the fix attached. The loop applies one action per round; the model never
decides what "looks worse" means.
Both contracts exist so that the same skill produces comparable results from different models: judgement is encoded once, in the tool, instead of being re-derived every run.
Deciding what to do next (never ask the user)
Priority is fixed by failure class, not by taste. Work down this list; do not jump to a lower class because it is more interesting.
- Behavioural failures — something that does not work: collision, input, the loop cannot be completed, audio silent. These invalidate everything else.
- Craft failures — the audit fails: missing bevels, segments, decals, hardware, contact AO. Cheap, mechanical, and visible at close range.
- Visual failures — the worst camera's
diagnoselist. Fix only the top item. - Polish — anything not in 1-3.
Within a class, pick the item with the lowest measured ratio, not the one that is easiest to talk about. If a class is empty, move down. If the top item is fixed and the metric does not move, revert and take the second item.
Report the class you are working in. "It still looks flat" without a class and a number is not a defect report.
Rule governance: what to do when the rule was violated
A violation is evidence, not automatically a bug in the rule. Triage it with one question: would following the rule have produced a better result here?
- Yes, and I skipped it because it was boring — follow the rule. Boredom is not a reason to amend it. Add enforcement so the skip is visible next time.
- No, the rule pointed somewhere useless — the rule is wrong. Change it, but only with a counter-example: the frame, the number, and why the rule mis-ranked.
- The rule had no answer for this case — extend it, do not discard it. Missing coverage is the usual cause of a violation, not a wrong priority.
Amendments are cheap to write and expensive to trust, so:
-
A rule change requires a counter-example, not an opinion.
-
Change the thing that enforces the rule (a tool, a check, a logged field), not only the prose. A prose-only amendment will be violated again.
-
Keep a deviation log. Every round writes one line:
round N | class: visual | top item: p10 0.27 | doing: <this> | deviation: reasonA round whose
doingdiffers fromtop itemwithout adeviationreason is a process defect and gets reverted, regardless of whether the frame improved. -
If two consecutive deviations produce no metric gain, stop and return to the rule. That pattern means the rule was right and the deviation was avoidance.
Generalisation rules (apply to every amendment)
A skill that only works for the scene that produced it is a case study, not a skill. Every rule added from a specific failure must pass these tests before it is kept:
- No subject nouns in the rule. A rule may name roles (hero prop, large surface, foreground plane, backdrop), never object classes (forklift, container, harbour). If the rule needs a class name, it is an example, not a rule — move it to a "worked example" and generalise the statement.
- No absolute numbers. Thresholds are ratios against a reference profile captured from the user's own target. Any number in the body is illustrative and must be labelled as such.
- Cross-domain check. Re-read the rule as if the subject were: an interior, a product shot, a landscape, a vehicle, an architectural still. If it becomes meaningless or wrong, rewrite it in terms of the underlying property (edge contrast, contact separation, scale of detail) rather than the object.
- Tool-neutral. The rule must be checkable without a specific engine, renderer, or vendor tool; if it needs a capability, state the capability.
- One failure, one clause. Add the smallest clause that would have caught the failure. Do not restructure the skill around a single bad frame.
- Evidence lives with the project. A named build, a frame score or a counter-example belongs in the project's report. The skill states the rule and the failure class; it never names a product as the standard or cites its score as a target. Worked examples may test a rule; they must not become the rule.
Amendment log format (append when a rule changes):
rule: <what changed> | evidence: <frame + measurement> | generalised to: <property>
Acceptance command
One command, eight gates, one verdict:
node harness/verify.mjs --dir <project> --page <page.html> [--profile refs/profile.json]
| Gate | Fails when |
|---|---|
| shaders | any material logs a compile/link error (the silent fallback) |
| census | any object is missing segment, surface, or identity budget |
| collide | a blocker has no collider, the boundary is bare, or anything tall is walk-through |
| lights | a light has no fixture within its mount distance |
| playtest | the loop cannot be completed, cannot fail, or the UI promises what E will not do |
| product | the shell/content manifest is missing, a screen/setting/save/touch/objective is absent, or the declared budgets are exceeded |
| mobile | 390×844 overflows horizontally, the title is unusable, or touch controls are missing when touch is declared |
| look | the project's reference energy ratio is below target, or the tone gate fails; measured on the worst of the declared cameras |
A gate that lives only in a README stops being run. Ship this whole directory
with the skill (harness/: render, verify, product, mobile, census, collide,
lightaudit, playtest, calibrate, score, diagnose, objectbox), wire verify.mjs
into the project's only entry point, and treat a red verdict as a build failure,
not a report.
--profile points at the project's own calibration (2–3 target frames, see
calibrate.py). The shipped profile.json is an example, not a universal target;
a profile captured from another subject will rank styles, not quality.
The harness requires the page to expose a small contract:
| Hook | Purpose |
|---|---|
window.__SCENE | scene graph, for census, collision parity and light anchors |
window.__COLLIDERS / __BOUNDS / __TESTMOVE(x,z,dx,dz) | solids, world bounds and the movement clamp |
window.__GAME / window.__TEST(action, arg) | loop state and scripted actions |
window.__PRODUCT | shell/content/perf/cameras manifest (see Finished-product contract) |
window.__AUDIT | optional per-object budget for audit.mjs |
window.__STATS | calls/triangles/fps after the last frame |
window.__READY | true only after a few frames have rendered |
?shot=1 / ?cam= / ?seed=N | still mode, fixed camera, fixed random seed |
?solo=<name> | isolated object shots for per-object measurement |
Standard __TEST actions (start, pause, resume, openSettings,
closeSettings, save, state) let the product gate drive the shell without
knowing the implementation. Add game-specific actions on top; keep the standard
ones working without pointer lock.
Playtest protocol: let the page own its loop
playtest.mjs is deliberately not a genre test. It knows two protocols and no
coordinates:
__TEST('selftest')— the page runs its own scripted win, loss and restart path and returns a JSON report:{ win: true, fail: true, restart: true, cause: 'named cause', steps: [...] }. This is the right choice for racing, puzzles, management and any loop whose success is not a list of points.__TEST('plan')— the page returns targets and a far point, and the gate drives the interaction contract:{ key: 'E', farPoint: [x,z], targets: [{ id, pos }], required: 3 }. It checks the negative half (no key prompt when out of range), the positive half (prompt, interact, progress, a visible world change), lethal damage with a named cause, the end screen, and reset.
A page that implements neither fails the gate with an instruction, not with a project-specific coordinate. This is the difference between a gate and a script that only works on the run that produced it.
Maintaining the standard
A rubric that is never revised drifts away from the goal it was meant to serve. Three rules keep it honest:
- The score must be able to lose. Every metric added has to be able to go down when the image gets worse. If a change raises the number and the frame looks worse, the metric is wrong: revise it before continuing.
- Region-specific character matters, not just magnitude. Aggregate energy cannot tell cloud shapes from noise. Where a region has a known character, add a ratio test: sky should carry energy at mid scales, so a fine/mid ratio far above the reference in the sky band means "static", not "cloud".
- Report the detail ceiling too.
p50/p75of block detail catch "no surface is ever rich";p10only catches emptiness. They need different fixes: p10 low = add objects, p75 low = add material contrast at 2-8 px. - Judge at the hardest camera. Score at least one camera at 1.5-3 m from a prop and report the minimum across cameras. A hero framing hides untextured primitives; close range does not.
When a standard change is made, record it with the evidence that forced it.
Census, not sample
The unit of audit is every rendered instance, never a hand-picked shortlist. A six-item manifest that passes says nothing about the hundred objects that were not in it — and the ones left out are always the ones that look worst.
Harness procedure:
- Walk the scene graph (
scene.traverse), collect every visible mesh/instance. - Derive per-instance facts from geometry and material, not from declarations: world AABB, triangle count, radial segment count, maps present (albedo / normal / roughness), attached decals, collider presence.
- Compare each instance against the craft budget for its size class.
- Report coverage:
passing / total. A sample-based "6/6" is invalid.
Hand-written manifests are allowed only as overrides with a reason field. An
instance missing from the manifest is a failure, not an exemption.
Every check needs its dual
Each check above has a blind twin that a weaker model will fall into:
| Check | Blind twin it misses |
|---|---|
| blocker has a collider | free space has no collider (phantom wall) |
| object has N parts | the parts do not identify the object (anonymous blob) |
| surface has detail | detail is noise, not wear (uniform static) |
| light exists | light has no fixture (free-floating cheat) |
| loop completes | loop has no failure state (walkthrough) |
Write the pair at the same time. A suite with only the positive half will pass while the scene has invisible walls, unidentifiable props, and lights bolted to nothing — all of which this project produced in a single session.
Identity features (nothing may be an anonymous blob)
Counting parts proves an object is complicated, not that it is recognisable. At the closest viewing distance the object must be nameable, and that is a property of form, not of part count.
Every prop declares the features that make it legible:
{ name: 'hero-prop', identity: ['forks', 'mast', 'wheels', 'cab'] }
Rules:
- Each identity feature must be a separate, named part, not implied by a texture.
- At the closest camera, each feature must project to at least ~12 px in its smallest useful dimension. Below that the feature exists but cannot be read.
- The silhouette must not be a blob: compactness
perimeter² / (4π·area)of the object's mask should sit near the reference's props, not near a circle. - A prop whose identity list is empty is a placeholder, and placeholders do not ship.
If a viewer cannot say what the object is in one second, the object fails — no matter how many bolts, bevels or decals it carries.
Identity must survive batching. Merging parts into one draw call is the right default for performance and the wrong default for legibility: after the merge there is nothing left to name, so identity cannot be checked, fixed, or tested. Resolve the tension explicitly, one of:
- build each prop as a named group, merge only within the prop, and record
userData.identityon the group before merging; - keep an authoring-time registry
{ prop, features: [{name, parts, size}] }that the census reads, and assert the registry covers every rendered prop.
A scene where identity lives only in the author's head fails this gate by construction — which is the honest outcome, not a reason to weaken the gate.
A decal that cannot be verified should be omitted. Missing signage costs far less realism than signage hovering in space. If you cannot assert the attachment at runtime (raycast hit within a few centimetres of the decal plane) and cannot see the result, ship without it. In this project two attempts at container numbers ended up floating and were removed; the measured detail gain from them was under 1%.
Attached decals need a surface check. A decal placed by offset from an object's origin looks correct in code and floats in the image whenever the instance is rotated, scaled, or the object is missing. Assert attachment mechanically: raycast from the decal's centre along its normal; it must hit the intended parent within 5 cm. Without that, decals pass every image metric while hovering in mid-air — which this project did twice.
Instrument calibration. Gates fail for two reasons: the scene is wrong, or the measurement is. Distances must be measured to a mesh's bounding volume, not its origin (merged geometry sits at the origin and reports every light as far away). Headless evaluate loops must stay inside the harness timeout, or the gate crashes instead of failing. When a gate flips after an unrelated change, suspect the instrument before the scene.
Anti-gaming gates
Numbers can be raised without improving the image. These gates run before any score and void a round when they fail:
| Gate | Check | Why |
|---|---|---|
| Light anchoring | every light has a fixture mesh within 0.4 m and appears in the lighting sheet | a floating point light brightens an object without existing in the world |
| Object justification | every added object is registered with the verb/subject it serves | props added only to fill a measurement box are noise |
| Collision parity | every rendered instance above the walk-through size has a collider, or is tagged passable | tests that read the implementation's own list prove nothing |
| Change attribution | each round logs the change, the expected metric effect, and the gate it might break | an accepted gain that breaks a gate is not a gain |
A round that raises a metric and fails a gate is reverted, no discussion.
Collision, tested from the graph
What counts as a blocker must be stated, or the test is arbitrary: inside the walkable area, tall enough to stop a person (~0.45 m), thick enough not to be a decal or a sign (~0.12 m in both horizontal axes), and not explicitly passable with a reason.
Merged meshes. Merging geometry destroys per-object identity, so a merged mesh cannot be tested at the object level. If it declares itself passable, it must also declare where its colliders came from, and that source must be countable on its own:
setDressing.userData.passable = true;
setDressing.userData.colliderSource = 'kit-parts'; // 733 AABBs registered at authoring time
A passable flag without a countable source is a backdoor: it makes the parity
test green while the player walks through the props. The census must total the
declared source; if the number is zero, the exemption is invalid.
Test sampling. March the mover at a step smaller than the thinnest collider (0.02 m for fence panels and rails), and discard start points that begin inside geometry — otherwise the test reports penetrating a wall the player never touches, and the fix will be to weaken the test instead of the geometry.
Collision is bidirectional. A penetration test only proves you cannot enter solid geometry. It says nothing about being stopped where nothing exists — the "invisible wall" failure — and that is the failure a penetration-only suite will never report, no matter how many rounds it runs.
Two tests are required:
| Direction | Test | Catches |
|---|---|---|
| positive | march into every blocker; assert no entry | walking through walls |
| negative | sample free space; assert the mover can travel a minimum distance in the direction it should be free | being blocked by nothing |
Colliders must be three-dimensional and only counted if they intersect the
player's vertical band (roughly 0–1.8 m). A collider derived from a lamp head at
13 m or a beam at 17 m will block a person walking underneath it; that is exactly
how a phantom wall is born. A collider with no y0/y1 is a 2-D collider and is
invalid.
The negative test is cheap and decisive: for N sampled points in open space, push the player 3 m in 8 directions; on average at least 5 of 8 must move freely. A site with aisles will pass; a site with a phantom slab across an aisle will not.
- Colliders are derived from rendered instances, not maintained as a second list. Two sources of truth always drift, and the drift is exactly where the camera walks through a wall.
- The test enumerates objects from the scene graph and asserts a collider exists for each blocking instance; then it samples a grid over the walkable area, pushes the player toward each collider, and asserts zero penetration and zero out-of-bounds.
- A test that iterates the same array the implementation uses is a tautology.
Metric stack (order matters)
- Gate 0 — plausibility (binary). Lights anchored, shadows present, objects grounded, colliders complete, loop completable. Any failure blocks scoring.
- Gate 1 — craft coverage. Share of all instances passing the per-object budget. Report the failures by name.
- Gate 2 — per-object image quality. Inside boxes around the subject objects: detail p50/p75, specular peaks, edge wear, contact band, each as a ratio to the reference frame.
- Gate 3 — frame composition. Multi-scale energy and flat tiles. This is the weakest signal and must never outrank gates 0-2.
An average can only be computed after gates 0 and 1 pass; until then the only valid number is the failure count.
Edge criteria (what the eye actually uses)
Whole-frame energy says "this is detailed"; it does not say "this object is used". Humans judge realism from four edge signatures. All four are measurable inside a box drawn around one object, and all four are missing from an average-based rubric.
| Criterion | Definition | Measure | Fails as |
|---|---|---|---|
| Silhouette break-up | outline curvature changes along the object's border | count of convexity changes per 100 px of outline | reads as a primitive |
| Edge wear | luminance/chroma discontinuity within 3-6 px inside an edge | mean gradient in an edge band, normalised | reads as new/unused |
| Contact darkening | dark band where object meets ground, 5-20 px below the seam | mean luma drop vs 40 px away | object floats |
| Specular density | count of local maxima above the 99th percentile inside the object | peaks per 1000 px² | reads as matte/plastic |
Reference values are relative, not absolute: measure the same four on the target frame, then require >= 0.8 of the reference for each. A frame can pass every global energy test and fail all four — that is the "smooth boxes" failure.
Per-object measurement needs a mask
A rectangle around an object always contains something else — a container wall behind a forklift, a wet floor under a drum. Measured inside a plain rectangle, the object's numbers are contaminated by its background and can look better than the reference while the object itself is bare.
Measure the object against black:
?solo=<object-name> hide every other mesh, render on black
--auto crop to the silhouette, then measure
Only those numbers describe the object. Rectangle numbers are still useful for composition, but they must never be reported as the object's quality.
Measured this way, the same scene gave 10.31 p75 inside a rectangle and 8.67 in silhouette — the rectangle had been reading the warehouse behind it.
Compare like with like. A masked object cannot be compared against a reference rectangle: the reference number includes whatever surrounded that object, so it is inflated and the target becomes unreachable. Either segment the reference the same way, or fall back to frame-to-frame comparison, which is self-consistent even though it is coarser. In this project the same scene read 0.62 peaks against a contaminated object box and 2.17 against the reference frame — the first number was a measurement bug, not a quality gap.
Object-box protocol (how to judge, not what to build)
- Pick 3-6 subject objects that the frame is about (the hero prop, a large surface, the foreground plane).
- Draw their screen rectangles, by hand or from the camera projection.
- Inside each box, measure the four edge criteria plus p50/p75 block detail.
- Report the worst box, not the frame average. A detailed background must not disguise an untextured hero prop; averaging is exactly how that happens.
- Fix only the worst box, then re-measure the same box.
A box that scores below 0.8 on edge wear or contact darkening cannot be fixed by global grading, bloom, or fog: those operate outside the object.
Per-object budget (check in code, before rendering)
Image metrics cannot see faceting or missing bevels: anti-aliasing averages a low-poly cylinder into a smooth edge. These limits are checked against the kit table and the material definitions, not against pixels. Distances are the closest the object is expected to be seen.
| Property | Limit | Check |
|---|---|---|
| Curved segments | < 3 m: 32+, 3-8 m: 24+, > 8 m: 16+ | count radial segments in the kit builder |
| Bevel / chamfer | every hard edge, radius 0.5-2 cm (or a 1-2 segment chamfer) | geometry builder has a bevel step |
| Parts per prop | 2-4 m object: 12-25 parts; small prop: 4-10 | count merged parts per kit entry |
| Texel density | close-up (< 3 m): 256+ px/m; mid: 64+ px/m | texture repeat x object size |
| Material channels | albedo + roughness + normal all vary; normal contrast >= 8/255 | material definition |
| Contact occlusion | every grounded object: cast shadow or AO decal; concave junctions darken | scene graph audit |
| Edge wear | visible at 2 m: broken edges, chips, or a wear mask | close-up render |
| Silhouette breaks | no perfectly straight run longer than 40% of the object's largest dimension | close-up render |
A prop that fails any row is not finished, regardless of its screen-space score. Budgeting this per object is what stops "hero camera 0.95, close-up 0.56".
Bloom is a lens effect, not a grade. A strong bloom on a low threshold puts a veil over the whole frame and reads as haze; it also hides missing contrast. Keep the threshold above the brightest surface and let only practicals and speculars bloom. If the image looks washed, check bloom before adding contrast.
Delete what you cannot verify. Two subsystems in this project were removed after failed attempts to make them correct: additive halo quads (white squares) and container number decals (floating three times). Both had measurable value near zero and cost several rounds. A feature that survives only by constant repair is not a feature.
Freeze the clock before comparing renders. An animated scene (rain, grain, particles) gives a different screenshot every run: the per-tile detail metric moved by 0.26 between two renders of the same build, which is larger than most changes being judged. Pin the time in the page and pass it from the render tool by default; re-measure any decision that was made without it.
Fog sets a visibility budget; compute it before building. At f = 1-exp(-k·d²)
with k = 2.4e-4, anything past 80 m is 78% fogged and past 105 m is 91% — a
container ship at that distance renders as nothing. Place distant content by
solving for the distance at which it still reads, not by eye.
Sub-pixel geometry subtracts detail. Thin cables strung across the sky lowered the per-tile detail floor: at 3-5 px with a dark colour they average into the background rather than adding structure. Lines need ~2 px of contrast to count as structure at all.
A flat region is fixed with an object, not with a shader. Four shading attempts (more octaves, fine noise, coarse grime, camera tilt) moved the per-tile detail floor by less than noise, and the tilt made it worse — the near ground was flatter than the sky. Adding three drain covers and two skid marks to the near field moved it 1.78 → 1.95. Always unproject the flat tiles first and check what is actually there; if it is empty ground, the answer is geometry.
GLSL reserved words fail silently. patch, sample, filter, input,
output and friends are reserved; using one fails the whole program and the
material falls back with no exception. The render-time shader check catches this
on the first frame — keep it wired into every run.
Check the sky projection for collapse at the zenith. Any mapping of the form
d.xz / d.y (or / (d.y + c)) converges to a point overhead, so the top of the
frame is a single colour no matter how many octaves you add. Divide by something
that stays large (d.xz / (a + b·max(d.y,0))) and drop the horizon fade if the
deck is meant to continue to the vanishing point.
Match saturation before touching contrast. A scene lit entirely by sodium
lamps drifts 30-40% above the reference's chroma without any single element being
wrong. One constant in the composite (mix(luma, c, k)) fixes it: measured here
0.257 → 0.205 against a reference 0.202.
Sky needs structure at the scale of the frame, not more octaves. A deck edge and a horizon glow band give the sky a readable shape; adding octaves gives it noise. Structure survives at any resolution, noise does not.
Stretched noise is the classic fake cloud. Sampling an fbm in screen- or direction-proportional coordinates produces radial streaks that read as brushed metal; it also scores well on detail metrics, which is why it survives review by number. Warp the domain before the octaves, keep the shapes isotropic, and add a lit underside rather than more octaves.
Define the metric before trusting it. Three reasonable definitions of highlight density gave three verdicts on the same frames (behind / clearly behind / ahead). Absolute and percentile thresholds track exposure; a ratio to a local blur tracks isolated highlights and is exposure-invariant. If a metric flips its verdict when redefined, it is not yet a measurement — pick the exposure-invariant form and state it explicitly.
Highlight count is a density of distinct emitters, not a brightness. Raise an emitter's intensity and it blooms into a blob, which lowers the count (measured: brightening windows 3x moved 1.17 → 1.08). To raise it, add more separate small emitters across the frame, each still small at the target resolution.
Specular peaks count light sources, not gloss. Raising a material's gloss or adding a clearcoat does not increase the number of small highlights; only more small bright things do (distant lit windows, wet points, practicals, sparks). If a frame is short on peaks, add emitters or reflective clutter, not shininess — two attempts to fix it through material parameters produced +0.03 and 0.00.
Feature thickness is a distance decision. A structurally correct 14 cm member is five pixels at 10 m and reads as a scratch. Size silhouette features (masts, rails, guard bars) from the distance they must be legible at — 3-5 px minimum for a line, 10+ px for a mass — and only then check that it still looks plausible up close.
Judge the hero prop in isolation. Frame statistics move very little when a
single prop improves: the forklift went from 8.7 to 17.1 p75 in isolation while
the frame moved 4.29 → 4.37. If the subject matters, measure it with ?solo and
a mask, and accept that the frame score will lag behind.
A push after the batch is merged is a silent no-op. If geometry is batched into
one mesh at a known point, every later push into that batch renders nothing and
raises nothing. This cost three rounds of "the foreground props do not appear".
Assert that every authored part ends up in a rendered mesh: count parts before
the merge and compare with the scene's instance count.
Adding an object is not the same as putting it in the frame. Before adding a prop for composition, project its world position through the camera and assert it lands inside the viewport with the intended size. This project placed foreground occluders three times that never appeared: below the lower frustum edge, behind the near plane, or off the side.
Measure region luma, not just the frame. Global statistics cannot see that the background is out-valuing the subject. Crop the subject and the largest background mass, compare mean luma, and require background ≤ subject: here it was 89 vs 78 before, 71 vs 66 after. Fix it by dimming the light that reaches the background first, then by lowering the background's albedo; never by brightening the subject alone, which flattens the frame.
Any light change must be followed by a tone check. Raising a cool bounce to separate shadows from sodium highlights dropped midtones from 64% to 58% and needed exposure +9% to recover. Re-read the tone gate after every lighting edit.
Know when a metric has hit its content ceiling. If nine different additions move a metric by less than its noise, the metric is measuring something the scene does not contain. Stop adding objects to satisfy it; either change the scene's subject (more emitters in frame by construction) or accept the gap and record why.
When every global metric reaches parity, switch instrument. At that point the
numbers stop discriminating: further work goes into named objects (measured with
solo + mask) and into specific defects a human names out loud ("the sky looks
like streaks", "the forklift is boxes"). Record those as text, fix one, and use
the image — not the metric — as the verdict.
Content audit (run before judging the image)
Image statistics cannot see faceting, missing textures, or floating objects: anti-aliasing averages a low-poly cylinder into a smooth-looking edge. Walk the asset list and check each item. This is a checklist, not a score.
Close range is the honest test. Score a camera at 1.5–3 m from a prop, not only a hero shot: one scene scored well on its hero framing and half of that on a hero prop at 2 m. Textures, bevels and occlusion only matter at that distance, so that is the camera to judge by.
Geometry
- Curved surfaces within 5 m use enough segments to read as round (roughly 32+ for cylinders, 24+ for small props); a visible flat facet is a defect, not a style.
- Edges of real-world objects are broken or bevelled; perfectly sharp silhouettes read as untextured primitives.
- Nothing intersects without a reason, and nothing floats.
Materials
- Every material carries variation in at least two channels: albedo, roughness, normal.
- Large flat faces (panels, boxes, pipes) have intra-material variation — wear, streaks, seams, dirt. A uniformly coloured polygon is the single most common "toy" cue.
- Roughness is not constant across a category; wet and dry areas differ.
Contact and light
- Every object touching the ground shows either a cast shadow or an occlusion band; otherwise it floats.
- Concave junctions (pipe on pipe, box on box) darken.
- Specular highlights exist where a wet or polished surface faces a light.
Sky and backdrop
- The sky has structure at the scale of the frame: cloud deck, haze band, gradient break. A flat vertical gradient is the largest easy-to-miss region of empty image.
- Horizon haze ties the ground fog to the sky colour; without it the seam reads as a cut-out.
Game layer: the deliverable is a game
The default output is a playable piece, not a still and not a walkable scene. The camera follows the verb: an embodied verb (carry, hide, repair, drive) wants first person; a verb about spatial judgement (steering, aiming a rig, managing a yard) may want third person, a chase cam, or a fixed isometric view. Choose the camera last, after the verb, and make the choice explicit in the brief. A still is a fallback only when the brief explicitly asks for an image. Judge the work by three separate budgets — look, solids, loop — and never trade one for another: a beautiful frame you can walk through is a failure, and a correct loop with a fake-looking frame is also a failure.
A scene becomes a game when it has a loop. Do not import a genre template — shooters, stealth, puzzles, driving, building all reduce to the same grammar. Derive the loop from the subject, then instantiate it.
Loop grammar (fill all five; if a row is empty there is no game yet):
| Slot | Question | Example answers (same subject, different games) |
|---|---|---|
| Verb | what does the player do most often? | aim, hide, read, carry, repair, drive |
| System | what responds, with state? | guards with sight, a machine with cycles, cargo with weight |
| Feedback | how do they know it worked? | sound, light, counter, animation, score |
| Failure | what ends or costs the run? | detection, damage, timer, lost cargo |
| Session | how long is one loop? | 30 s, 3 min, 20 min |
Derivation procedure:
- List the verbs the subject naturally affords (carry, climb, hide, repair, drive). Pick one primary and two supporting; drop the rest.
- For each verb, name the system state it changes and the feedback that reports the change. A verb without observable feedback is not a mechanic.
- Define failure and restart. A loop without failure has no tension and reads as a walkthrough.
- Budget each mechanic like an object: it needs input, state, feedback, failure, and a test. Unbudgeted mechanics are the ones that silently break.
Combat is one instantiation, not the default. If the subject suggests shooting, derive it from the verb list; if it suggests repair or stealth, derive that instead. The grammar is constant; the mechanics are not.
Derivation table — same grammar, six genres, none of them a shooter:
| Subject | Primary verb | System that answers | Failure | Session |
|---|---|---|---|---|
| Container yard | carry a drum to a junction | cargo sockets, a shift clock, a swinging load | clock runs out, or struck | 90 s |
| Workshop | repair a machine | parts with wear, a schematic, a power budget | the machine seizes | 5 min |
| Stairwell | move unseen | patrol cones, sound made by footsteps | seen | 3 min |
| Quay road | drive without spilling | cargo inertia, road camber, gates | spill, or late | 60 s |
| Flooded basement | explore and route power | water level, fuses, doors that lock behind you | drowned | 8 min |
| Market stall | manage stock and price | customers with patience, a cash float | bankrupt | open |
If the table's "system that answers" column is empty for your subject, the subject is a place, not a game. Add a system or pick another verb.
Scope: one verb, one failure, one session of 1-10 minutes. A vertical slice beats a half-finished epic: the first build must be completable and loseable end to end.
Mechanic budget (per mechanic, checked before polish):
| Field | Requirement |
|---|---|
| Input | one clear binding, works with pointer lock, keyboard and touch |
| State | explicit, inspectable, serialisable |
| Feedback | at least two channels (visual + audio) within 100 ms |
| Failure | a way to lose or retry, with a visible cause |
| Test | a scripted path that exercises it headlessly |
A hazard must sit where the verb happens, at the height the player occupies. Risk that is 40 m down an unused aisle, or swinging eight metres overhead, is scenery: it cannot change the run. Place the hazard on the route the loop already forces, at body height, and give it a telegraph long enough to be dodged. Measured here: 40 m away → never encountered; 8.6 m up → cannot touch; 1.6 m on the carry route → the loop has tension.
The UI must not promise what the game will not do. Marker range, prompt text and the action's own radius must come from one constant. Measured here: a marker at 3.0 m, an action at 1.8 m, and a prompt that always named the key — a player at 2.5 m pressed a key that did nothing. Test both directions: the key appears whenever something is in range, and never when nothing is.
Hide debug chrome, never delete it. Removing the HUD in screenshot mode made
the state unreadable to the headless tests that verify the same game; display:none
keeps stills clean and keeps the DOM inspectable.
Escape sequences inside template literals bite test code. A regex written as
/\bE ·/ inside a JS template literal is \b = backspace, so the check silently
never matches. Prefer includes() for substring assertions in generated scripts.
Success needs the same visible consequence as failure. A counter that ticks is
not feedback: the delivered object must appear where it was delivered, with a
marker that fires once. Test it by asserting the world state equals the counter —
visibleDrums === connected — not by reading the number back.
Audit props by intent, not by visibility. Objects that appear during play (the
held item, delivered cargo, spawned enemies) are hidden at load time and are
skipped by any check that filters on visible. Include anything that declares an
identity, or half the game escapes the asset budget.
Every failure needs a named cause on screen. "TIME OUT" and "struck by the swinging load" teach different lessons; a player who cannot name what killed them cannot improve.
An interaction whose consequence is invisible is not implemented. Every verb needs a visible before/after in the first-person view, not just a counter: the lifted object appears in the player's hands, the target of the verb carries a ground marker while it is in range, the prompt names the key. Measured here: the carry loop passed its playtest for dozens of rounds while the carried drum was never rendered and nothing marked what could be picked up — mechanically correct, unplayable in the hand.
Discoverability checklist for each interactable:
- visible in the world before the player is told about it
- a marker or highlight appears when it is in range
- the prompt states the key and the verb (
E · lift the drum) - the consequence is visible within one frame (object in hand, socket filled)
- the state change is also audible
The shell is part of the game
The first frame a player sees is the title screen, and the first minute is the menu. Both are product, not chrome.
- Title = key art. Hide the gameplay HUD. Compose the scene as a title frame: a readable silhouette, a premise line, a start action, settings/controls, and the run's state (best score, chapter, difficulty). A modal card floating over a live HUD reads unfinished even when the game behind it is good.
- Shell screens: menu, playing, paused, settings, lost, won. Each is a real screen with a clear way back; pause carries run stats and resume/restart/menu.
- Settings: look sensitivity, invert-Y, FOV, master volume, mute, quality preset (calls/tris/shadow/texture budgets), fullscreen. Persist them.
- Persistence: best score or progress survives reload. Save the settings too.
- Touch: left stick moves, right drag looks, fire/aim/reload/jump on screen. Do not require hover or a keyboard. Offer a fallback when pointer lock fails.
- Objective UI: world markers and a compass with distance; the marker range, prompt text and interaction radius come from one constant.
- Radio/subtitles: name the beat and the failure cause. This is the cheapest way to make a small game feel authored.
- Game feel: recoil, hitstop, camera shake, muzzle light, enemy telegraph, death animation, distinct hit/empty/reload sounds. The first ten seconds must show the verb, the threat and the stakes.
Audio and HUD are part of the loop, not decoration
- Every state change gets a sound within 100 ms: pick up, place, hit, complete, fail. Silence reads as "nothing happened" even when the world changed.
- Route audio through a single master gain and start it on the first user gesture; an AudioContext created before any gesture is suspended and stays silent.
- The HUD has a hierarchy, not an arbitrary count: objective + progress, then
survival, then weapon/ammo. Context prompts, markers/compass and subtitles are
secondary and may be diegetic. Debug numbers are not HUD. Hide the HUD in stills
with
display:none, never remove it, because the headless tests read it. - Failure text names the cause, not the rule ("struck by the swinging load", not "you failed").
Verification contract: expose window.__GAME = { state, actions, reset } and
window.__TEST(action) returning the resulting state. A playtest script drives
the loop headlessly — walk, interact, fail, retry — and asserts the transitions.
Scoring screenshots cannot tell whether the game is playable.
Interaction contract (if the scene is walkable)
Visual realism and behavioural correctness are separate budgets; a scene can score 0.9 and let the camera walk through a wall. Before calling a walkable scene done:
- Every blocking object has a collider. Build them from the same data used to place the geometry, so they cannot drift apart.
- The player has a radius and the collider test expands by it; resolve one axis at a time, otherwise corners trap or eject the player.
- The world has bounds. Without them the camera leaves the set and the illusion ends at the first step.
- Walk into the nearest object, a corner, and the outer edge, and confirm each stops the camera. Automated scoring will not catch this.
Failure modes
| Symptom | Likely cause | Correction |
|---|---|---|
| Plastic, toy-like surfaces | uniform roughness, colour-only materials | vary roughness and normal; add grime |
| Everything floats | no shadow receiving, no contact occlusion | shadow-casting key plus contact decals |
| Flat, grey, lifeless | ambient-only lighting, no key | one directional key plus environment map |
| Washed-out distance | fog or ambient values specified as if sRGB | specify in linear space or convert from hex |
| Hard line at the horizon | single fog colour against a graded sky | drive fog colour from sky direction |
| Empty frame | few, large objects | multi-scale kit and layout |
| Flat sky | single gradient, no cloud or haze structure | two cloud octaves + horizon haze band |
| Faceted curves | low segment count on cylinders/tori | raise segments to 24-32 where the curve is within 5 m |
| Camera walks through geometry | no collider, or colliders not derived from the placement data | generate AABBs from the layout table; resolve per axis with a player radius |
| Shimmering surfaces | sub-pixel normal detail, no distance damping | damp normals with distance, enable mipmaps |
| Foreground in shadow | key elevation too low | raise the key to roughly 20–30° |
| Poor frame rate | per-object allocation, no batching | merge, instance, render auxiliary passes at reduced resolution |
| Effects invisible | reversed smoothstep edges, back-face culling, sub-pixel size | normalise edges, disable culling for billboards, size in metres |
Calibration (optional, per project)
Do not adopt a single number as "the realism score". Every cheap proxy encodes one failure mode and ignores the rest. Edge density, for example, responds to mid-frequency boundaries and is blind to exposure, highlights, and material detail: a scene can double its contrast and its edge density will not move.
A workable procedure:
- Collect 2–3 reference frames of the look you are aiming at (stills, concept art, a shipped title). Same resolution and framing class as your target output.
- Measure energy at several scales, not one. A difference-of-Gaussians mean at fine (~1 px), mid (~5 px), and coarse (~15 px) scales, plus global contrast (standard deviation of luminance), covers texture, structure, and tonal range independently.
- Measure spatially as well. Slice the frame into a coarse grid (8×5 is
enough) and compute mid-band energy per tile. Global means hide flat
regions: a frame can pass an average test while a third of it is empty sky
or an untextured wall, and that is exactly what reads as "the objects have
no detail". Track the weakest decile (
p10) and the share of tiles below a floor (flat_frac). Fix the weakest tiles first: they are specific objects, not a global grade. Do not guess where they are — take the tile centres, unproject them through the camera at a chosen depth, and place the detail at those world positions. Placing props "somewhere near" the flat area moves the score by almost nothing. - Compare as ratios, not absolutes. For each metric take
min(1, yours / reference)and average them. Absolute thresholds do not transfer between subjects; ratios do. - Add binary tone checks that are style-independent: clipped highlights below ~1%, crushed blacks below ~3%, midtones within a sane band.
- Score at least three fixed cameras, and report the worst. A hero framing flatters a scene; wide shots expose empty mid-ground and bare sky. Track the minimum across cameras, not the best.
- Capture the target itself. Marketing stills are cropped, graded, and resized; they measure differently from a live frame. Run the reference build (or open the reference project) and capture at your own resolution with the same harness. That capture becomes the baseline.
- Include a saturation check. Measured colourfulness (mean chroma plus its variance) separates "filmic" from "gamey" better than saturation alone. A render that is 2x more colourful than the target reads as illustration even when its detail is right; treat excess as a failure, not a bonus.
- Require monotonic improvement. The score exists to attribute changes between rounds, not to declare victory.
Calibrate per project
A profile is not universal. Capture 2–3 frames of the project's own target (the reference build, a still, concept art), then run:
python3 harness/calibrate.py refs/target-a.png refs/target-b.png --out refs/profile.json
node harness/verify.mjs --dir . --page game.html --profile refs/profile.json
A profile captured from another subject measures similarity to that look, not finished-ness. A deliberately stylised scene can score below a photographic scene even when it is the more finished game. Use the project's own profile; keep the comparison in the project's report. The number is a compass, not a finished-game score, and must never outrank the product gate.
Reading the result:
| Mean ratio | Meaning |
|---|---|
| < 0.60 | reads as a demo |
| 0.60–0.80 | reads as a game |
| 0.80–0.95 | close to the reference |
| > 0.95 | indistinguishable at this resolution |
If the ratio is low but tone checks pass, the frame is under-detailed: add
mid-scale objects and surface variation, not contrast or bloom. If flat_frac
is above roughly 10%, find the flat tiles and give those specific surfaces
something to say — decals, seams, clutter, wear — rather than raising noise
everywhere. If tone checks fail, fix exposure before adding detail.
What transfers and what does not
Gates must be written against the page contract, never against a project.
Every hard-coded coordinate, mesh name, counter or item id makes the gate
silently project-specific. Move those facts into the page: a test plan, a
progress report, a generic hurt action. The gate should run on an unrelated
subject without edits; only the page's __TEST actions change.
| Hard-coded pattern | Portable contract |
|---|---|
| coordinates or ids in the test | page answers __TEST('plan') with targets and goals |
| project mesh names | page reports progress and shown; the gate compares them |
| a bespoke damage hook | __TEST('hurt', n) |
| one progress flag | a small state object with carried/held/done |
Thresholds must scale with the space, too. A clear-run distance or an "inside geometry" test that assumes an outdoor set fails on the first small room; derive thresholds from the page's declared bounds and player radius.
The look gate needs a declared fallback. With no reference frame for the subject, the only defensible criteria are tone (clip and midtones) and emptiness; comparing an interior against a different scene's energy profile measures nothing. State which mode was used.
The procedure, the contracts and the gates transfer to any subject: two unrelated projects with different verbs, lighting and scale pass the same acceptance command, and each uses its own calibration profile.
The result does not transfer. A new subject starts at the same place the first one did — plausible geometry, flat image — and needs the same loop: measure, diagnose, one change per round, gates after each. Budget for that; do not read a first successful render as a finished scene.
A room is lit by what you can see. An interior with only a point light reads as a dark box. Add the source you can see (a window, a screen, a lamp shade), frame it, and let it spill onto a surface; two rounds of that doubled edge density in an interior test.
Portability notes
- Engine mapping: the levers are the same in WebGL, WebGPU, Unity, Unreal, and offline renderers. What changes is the API for environment lighting, material injection, and post-processing.
- Harness mapping: any agent runtime that can run a shell and read an image can follow this procedure. The readiness contract in Step 1 is the only integration point.
- Keep the skill independent of any single project. Project-specific subjects, palettes, and budgets belong in the project, not here.