Draw the city in high definition, still in text

The payload splits per world: index.html keeps the engine and the city,
and w/west.js, w/jp.js and w/moon.js carry the other worlds, each loaded
with a content-hash cache-buster and isolated so one failing chunk only
loses its own world.

Under the glyphs sits a per-world underpainting (CC.Compose.UNDER, with
0 as a kill switch for the frame data and glyph layer), glyphs print
through a pixel path on small cells, optics are sized for denser grids,
and the default bands reach about 300 columns at 1920 px and 360 at
2560, stepping back down on a slow machine.

The photosensitivity probes now see the composite, at 200x60 and
400x120, weighted by ink-compensated coverage for the real cell size.
27 of 28 runs pass; lum-mode west-flicker at 400x120 (3.25/s against
the city's 3.16/s) is documented in CONTRACT as still open.

Also carries the share card: og.jpg, its og/twitter meta and sitemap.
This commit is contained in:
MiguelCarino 2026-10-21 21:32:38 -06:00
parent 7425bb2bdc
commit b62b368034
32 changed files with 9233 additions and 6829 deletions

View file

@ -1,7 +1,11 @@
# CyberCity — module contract
Deliverable: **one self-contained `index.html`**, fullscreen, pure ambient, no game loop.
Sources live in `src/`; `node build.js` inlines them into `index.html`. Never edit `index.html` by hand.
Deliverable: **`index.html` plus `w/`** — the page with the engine and the city inline, and one
`w/<world>.js` per secondary world loaded by synchronous `<script src>` — fullscreen, pure ambient,
no game loop. Until the HD pass it was one self-contained `index.html`; that property was spent on
purpose, by the owner, and `build.js`'s essay records the trade. Sources live in `src/`;
`node build.js` writes both. Never edit `index.html` or `w/` by hand, and never publish one without
the other.
## Renderer model — voxel-space (heightmap) raycasting at character resolution
@ -26,6 +30,17 @@ Per column `x`:
| `lum` | Uint8Array | 0..255 brightness multiplier applied to the palette colour |
| `dist` | Float32Array | depth in world units; `Infinity` for sky. Elements MUST depth-test against this |
| `kind` | Uint8Array | `0` sky `1` façade `2` floor `3` element |
| `under` | Uint8ClampedArray, `cols*rows*3` | the underpainting: RGB per cell, additive under the glyphs. Written ONLY by `CC.Compose.post`, after `tone()`. **Elements never write it**, and nothing else may; all-zero (the `UNDER = 0` kill switch) is the glyph-only print |
| `D` | number, ≥ 1 | grid density against the 200-column 9:16 reference, `max(1, cols*cellAspect/112.5)`. Published by `raycast.js` every render (1 under `CC.DETAIL_SCALE === 0`); read by `optics.js`, `weather.js`, `west_stock.js` (the wagon bed's sample count and the team's leg-width threshold), the underpainting's spill box and `render_canvas.js`'s bloom radii. Declared in `makeFrame` with `uon`, so the frame's shape never changes after birth |
**The render order is contract**, because the underpainting needs the world pass on its own:
`CC.clearFrame(f)` → `CC.Cast.render(f, cam, city)` → `CC.Compose.world(f)` → every element's
`draw` → `CC.Compose.post(f, cam, t)` → `CC.Canvas.draw(f)`. `main.js`, `tools/headless.cjs` and every
composite probe repeat it. `world()` snapshots the frame before any element draws (so lightning and
other element flashes never reach the mass term) and stamps the snapshot with the frame; `post()`
and `clearFrame()` spend the stamp. A caller that skips `world()` still gets a field — `post()`
snapshots the frame itself before toning it — but a degraded one with the elements in it, which is
fine for a probe that never reads `under` and wrong for anything that does.
## Modules
@ -34,7 +49,7 @@ concatenates them in order and the headless harness `require`s them through a sh
| file | global | responsibility |
| --- | --- | --- |
| `src/core.js` | `CC`, `CC.Compose` | Frame alloc, PALETTE, GLYPHS, rng/noise, math, `put()`, and the print — the two exposure ladders, `ladder()`, the LUT and `Compose.post()`. `src/compose.js` does not exist; the contract allows it not to and `build.js` filters it out rather than assuming it |
| `src/core.js` | `CC`, `CC.Compose` | Frame alloc, PALETTE, GLYPHS, rng/noise, math, `put()`, and the print — the two exposure ladders, `ladder()` (its source set is the one `SRC` list, which the underpainting's emitter set `EM` extends), the LUT, `Compose.post()`, and the underpainting: `Compose.world(f)` (the pre-element snapshot), the field it writes into `f.under`, and `Compose.UNDER` (strength 0..1; 0 is the kill switch). `src/compose.js` does not exist; the contract allows it not to and `build.js` filters it out rather than assuming it |
| `src/world.js` | `CC.World` | the world registry — which world is live, the id/name/alias table, and `inWorld()` |
| `src/daylight.js` | `CC.Daylight` | the clock: sun altitude and bearing, and the light directions everything reads off them |
| `src/weather_state.js` | `CC.Weather` | the weather director and one preset table per world; `rel()` is the cross-world quantity |
@ -47,9 +62,37 @@ concatenates them in order and the headless harness `require`s them through a sh
| `src/proj.js` | `CC.Proj` | the ONE copy of the element camera — `make()` hands each world-space element file its own basis and the four helpers closed over it |
| `src/control.js` | `CC.Control` | the walk and the input devices; re-anchors to `city.js`'s route on a rebuild |
| `src/elements/*.js` | pushes to `CC.ELEMENTS` | ambient systems, see below |
| `src/render_canvas.js` | `CC.Canvas` | glyph atlas, `drawImage` per cell, bloom. **Only DOM-touching module** |
| `src/render_canvas.js` | `CC.Canvas` | the underlay (`f.under`, one pixel per cell, drawn unsmoothed first), the glyph pass — `drawImage` per cell from the atlas, or on cells of 7 device px and under (`setPixelPath('auto')`, what `main.js` ships) direct pixel writes and one `putImageData`, falling back to drawImage on any context that cannot — and the bloom, which reads the glyph scene only and is sized from the reference cell `dh*frame.D`. **Only DOM-touching module** |
| `src/main.js` | `CC.Main` | loop, resize, fullscreen, seed in hash, prefers-reduced-motion |
**Painter export keys the engine reads**, all optional, all on the painter's own export (the city's
on `CC.Surf`, the others on `CC.SURFACES[id]`) — a world is what its painter file says, and core
never names one:
- `SKY_RGB` — 18 numbers for the underpainting: zenith rgb then horizon rgb at NIGHT, at NOON, and
the DUSK pair the warm term pulls toward. The night horizon is also what far walls haze toward
(at half strength by night), and darkening it is not free: every glyph that steps in front of
the sky steps harder in display terms on a darker backdrop, which is what failed flicker-rate's
still-holo check at 400x120 when the city's was taken from 40,50,96 to 24,30,60. **No table means no sky and
no spill**: that is the Moon, which gets regolith ambient off `P.sun` instead.
- `BARE` — `[wall, floor]`, the share of the underpainting's ambient a blank cell takes when the
painter wrote it in a LIT swatch, meaning "this surface, no glyph on it". A blank written in
`shadow` or `slate` is a hole and takes the defaults whatever the export says (0.1 on a wall, 0.5
on a floor), and so does every blank when the export is absent. The swatch on a blank cell prints
nothing, so this costs the glyph layer nothing; it is the painter's one way of telling core which
of its blanks are openings. Edo is the world that needs it (`[0.8, 1.6]`): its walls and road thin
their glyphs by the light, and read as holes its noon street printed darker than its dusk one.
- `airless` — truthy on a world with no atmosphere. `surfaces.js`'s `refog()` skips its haze floor,
and `raycast.js` hands the painter the TRUE distance rather than the density-scaled apparent one.
- `fogStart` / `fogEnd` — LIVE getters for the weather's ramp (the city's on `CC.Surf`), read by the
underpainting's haze. `fogStart` may be 0; a collapsed ramp is treated as a wall of haze.
**What `CC.Compose.UNDER = 0` restores, exactly.** The frame data (ch/col/lum/dist/kind) and the
glyph layer, byte-for-byte, and the composite's op sequence minus the one underlay draw — `domshim`'s
`print-paths` case asserts that last part. It does NOT roll back the rest of the HD print: the pixel
glyph pass on small cells, the bloom sized from `dh*D`, the density LOD in `raycast.js` and
`main.js`'s cell band all stay, so the browser with the switch off shows this build's glyph layer,
which is not the pre-HD page.
## The palette — 21 swatches, two ladder entries each
`PALETTE` in `core.js` is **append-only**. Slots 0-11 are frozen because a swatch index in this
@ -199,21 +242,34 @@ Rules for elements:
## The build
`node build.js` must exit 0. It fails over **600 KB** and that line has been raised five times and
held once; the essay in `build.js` is the record and it is addressed to whoever lands here next.
**The next pass must split the payload.** Three passes running have now ended at this line with the
same finding — the content is bigger than the headroom and every remaining cut is a rounding error
against it. The last non-content cut in the tree (the duplicated `streetSpan` / `objVisible` /
`corridor` bodies, measured at ~2,350 bytes and banked in `build.js`'s essay) is worth a tenth of a
world.
`node build.js` must exit 0 and prints every shipped file's size and headroom. **The payload is
split per world.** `index.html` holds `core` through `control`, the city's elements, `render_canvas`
and `main`, capped at **600 KB**; `w/west.js`, `w/jp.js` and `w/moon.js` each hold that world's
painter and its prefixed elements (`west_*`, `jp_*`, `moon_*`), capped at **160 KB each**. Routing
is by name, in `build.js`'s `CHUNKS` table; anything no row claims stays inline.
The chunks **define and do not run**: each module is filed as a function under its `src/` path on
a scratch global, and the inline IIFE calls it back at its place in `ORDER`, then deletes the
global. So execution order is exactly what it was as one file — which is load-bearing, because
`CC.ELEMENTS` registration order breaks layer ties and sequences the shared rng — `CC` stays one
lexical `var`, and nothing is left on `window`. A chunk that fails to load costs its world, which
renders as the city; it never costs the city. Do not "simplify" this into two inline tags with the
chunks run between them: that moves the Edo elements behind eleven shared ones and gives the
browser a different frame from `tools/headless.cjs`, with nothing failing.
The 600 KB line was raised five times and held once before the split; the essay in `build.js` is the
record, and its last paragraph is addressed to whoever lands here next: the split bought ~220 KB in
`index.html` and that is not permission. A fifth world is a fourth chunk and a `CHUNKS` row, not a
raise. The last non-content cut in the tree (the duplicated `streetSpan` / `objVisible` /
`corridor` bodies, ~2,350 bytes, banked in the essay) is still there to take.
It also checks that every world's painter global is present, so a painter dropped into `src/` and
never registered fails the build instead of rendering as the city.
The order is: cut something that is not content, then cut content, then move the line, and write
down which one you did. The whitespace has already been spent — `decomment()` halves leading
indentation, worth 42,134 bytes of a measured 84,232 — so a future pass has one fewer option than
this one had. The bundle must also survive `new Function()`, contain none of `require(`,
`module.exports`, ESM syntax or a closing script tag, and still name every global in the
required-globals list.
this one had. Every shipped script — the inline bundle and each chunk, separately — must survive
`new Function()` and contain none of `require(`, `module.exports`, ESM syntax or a closing script
tag; their concatenation must still name every global in the required-globals list.
## Verification (this is not optional)
@ -222,7 +278,9 @@ and dumps `glyph,colourIdx,lum,kind` per cell. `python3 tools/topng.py f.txt out
to an image with the same bloom the canvas does. Every change gets looked at this way before it
ships. `python3 tools/metrics.py f.txt` is the census; its night targets are muddy under 30% and
hot 3.5-5%, and a daylight frame is not expected to meet the first — see the README's table for
what each world actually measures at each hour.
what each world actually measures at each hour. The first is a direction at night, not a line every
world clears: in that table the frontier (40.9% at seed 42) and Edo (37.1% at seed 42) run over it
after dark, and so does the city itself at seed 7 (32.6%).
The gates, in the order they are worth running: `node build.js`, `node tools/domshim.cjs`,
`node tools/flicker-rate.cjs`, `node tools/lightning-rate.cjs`, `node tools/west-flicker.cjs 4`,
@ -231,6 +289,75 @@ The gates, in the order they are worth running: `node build.js`, `node tools/dom
the census, and a determinism check (the same seed, frame, world and hour rendered twice must be
byte-identical).
EVERY PROBE IN THAT LIST NOW RUNS FOUR TIMES, and the list above is only the first of them. Each
takes `--composite`, `--cols=N` and `--rows=N` (one parser, in `tools/composite.cjs`), and a change
ships when all seven pass in all four of: no flag at `--cols=200 --rows=60`, the same at
`--cols=400 --rows=120`, and both again with `--composite` — e.g.
`node tools/flicker-rate.cjs --composite --cols=400 --rows=120`,
`node tools/west-flicker.cjs 4 --composite --cols=400 --rows=120`. The reason is the underpainting.
It never touches ch/col/lum, so every probe written against f.lum was still reading the frame it was
fitted to — and could not see the one part of the new frame that can spread a flicker: the SPILL lays
an emitter over a nine-by-five box of reference cells, so a tube that stepped one cell now steps up
to forty-five cells of wash with it. `--composite` scores the light a cell EMITS instead — glyph ink
by `tools/cov.json` coverage, plus the under block, in linear light — and it is the mode that can see
that. Lum mode (no flag) scores exactly what it always did and switches the underpainting off for the
run, which by construction moves no byte of f.lum. The masked probes (canal, road, sakura) grow their
masks by the spill box in composite mode, because the wash lands beside the cause. `lightning-rate`'s
composite mode is a different SCENE, not just a different sum: its flat wall is white, which does not
emit, so the stroke cannot reach the wash there; composite mode holds the real night world pass at the
start pose instead and measures the light emitted above it.
AND EVERY PROBE NOW CARRIES THE WCAG GENERAL-FLASH RULE, AREA-WEIGHTED, which no per-cell statistic
can stand in for. A transition is a 10%-of-white change in a cell's relative luminance with the
darker side under 0.80; a cell is flashing when it makes seven inside one second; the run FAILS if the
flashing cells cover more than a quarter of any window a third of the screen wide and tall (WCAG's
341x256-on-1024x768 field). It is absolute in every probe, west-flicker's comparative rule
notwithstanding. A synthetic check of the detector: a 60x18-cell azure sign at 6 Hz over cyber night
scores 0.0% on the glyph print and 75.9% on the composite (FAIL), and the same sign at 2 Hz passes —
the composite seeing what the glyph layer cannot is the point of it. Red flashes, WCAG's second
clause, are not measured, and neither is the bloom, which is a blur of glyph ink the glyph term
already carries.
WHAT THEY SAID WHEN THIS LANDED. All seven passed in all four modes but one: lum-mode west-flicker
at 400x120 FAILS at 10.75 big steps a second against the 8.0 backstop (seed 3, every preset), and the
untouched tree at 7425bb2 fails identically, so this is not the underpainting or the density work. It
is `west-wagon` alone — 1.50/s at 200 columns, 3.00/s at 300, 10.00/s at 360 — and the shipped band
reached 360 (main.js MAXC) with this note still open, so it was chased down in the fix pass. It was not the rim: it
was the BED, 27 fixed samples printing as a comb once the wagon spans more columns than that, with
the teeth sliding a sub-cell phase as it moves; and then the team's legs, one cell wide at 25 m on a
400-column grid so a near and far leg crossed a lit road cell as two pulses. Both now scale by
frame.D (identical at 200 columns): 10.75/s -> 3.25/s, 3-20 Hz 3.93% -> 3.07%, backstops passed. It
STILL FAILS the comparative rule at 400x120 — 3.25/s against the city's own 2.75 x 1.15 = 3.16 —
and that residual is the legs crossing the road at all, a solid object passing once, not an
aliasing beat. Composite mode, the light actually emitted, is 0.00 big steps a second at both sizes.
Flash area was 0.0% in every real run. Lightning passes with the underpainting on: on the composite
(2026-10-21, after the composite model learned the pixel path's ink lift — see below) the strongest
stroke is 0.9% of full scale above the held night frame at 200x60 and 1.1% at 400x120, its largest
frame step 28.5% and 29.5% of its peak, maxima 0.667 s apart — the wash moves by at most 9 levels at
the peak, because the mass term reads the snapshot taken before the stroke and only lit EMITTING
cells feed the spill. In composite mode west-flicker judges the project's absolute 1.0/s and 2% and
only PRINTS its city-relative ratio, because the cell average shrinks the city's hairline rain three
times harder than the frontier's solid objects. Measured the day the underpainting landed, at
200x60: 1.18% in band against the city's 0.79% on the composite, 1.14% against 0.80% on the glyph
print with the underpainting off — the wash's share is 0.04 of it. Measured 2026-10-21 on the
composite: 1.02% against 0.78% at 200x60, 1.27% against 0.95% at 400x120.
THE COMPOSITE MODEL WEIGHTS A GLYPH AT THE CELL THE GRID STANDS FOR. `tools/cov.json`'s reference
table is a 9x16 cell, and the canvas prints cells of 7 device px and under through its pixel path,
which lifts each glyph's coverage per pixel (`render_canvas.js`, INK) — +17% of mean ink at 6x11 and
+25% at 5x9, measured in Chromium. A 400-column gate weighted by the 9x16 table understated the glyph
term at exactly the size it exists for. `composite.cjs` now picks the cell from the grid (its width
across a 1920 px panel, so 200 columns is the 9x16 table, unchanged, and 400 is the 5x9 compensated
one) and `--cell=N` asks about another panel; `topng.py --cov` writes the compensated tables. Every
400x120 composite figure in this file dated before 2026-10-21 was taken with the old weights.
`tools/domshim.cjs` runs the page as it ships: every `<script>` in DOM order in one context — the
`w/` chunks and then the inline bundle, each under its own filename — skipping only the baseline's
JSON-LD block, which it parses as JSON instead. It fails if a tag points at a missing chunk or a
built chunk is never loaded, and it reads the column band from `main.js`'s `MAXC`/`MINC` in the
bundle rather than keeping its own copy. `tools/headless.cjs` loads `src/` directly and never
sees the split, which is why the split had to preserve execution order rather than merely load
everything.
THE THIRD TIME THIS RULE BIT, AND THE FIRST TIME IT BIT A FEATURE THAT WAS NOT RUNNING AT ALL.
`surf_japan.js` declared `function water` twice at one scope. Declarations do not shadow by
position — the last one hoists and wins — so every call from the road reached the CANAL's

103
README.md
View file

@ -1,9 +1,9 @@
# CyberCity
Four walkable worlds drawn entirely in text characters, in one self-contained HTML file, with the
sun going round.
Four walkable worlds drawn entirely in text characters, in one HTML page and three small scripts
beside it, with the sun going round.
No build step to run it, no dependencies, no network requests. Open `index.html` and you are
No build step to run it, no dependencies, no requests outside its own folder. Open `index.html` and you are
standing on a street in the rain. Press **2** and you are on a dirt road on the frontier; press
**3** and you are on the Moon; press **4** and you are in a castle town on a wet evening.
@ -64,8 +64,8 @@ still burning after dawn. `T` steps the clock through its six stops — night, d
afternoon, dusk — and `Y` stops and restarts the automatic cycle.
That was not a free feature, and the reason is worth stating: the whole print pipeline is fitted to
a frame that is more than half pure black with a thin scatter of bright glyphs, and daylight is the
inverse of that picture. It is answered with a **second exposure ladder** — one entry per swatch,
a glyph layer that is more than half pure black with a thin scatter of bright glyphs, and daylight
is the inverse of that picture. It is answered with a **second exposure ladder** — one entry per swatch,
twenty of each. By day the two night pillars go out (a sodium lamp at noon is a grey tube, a screen
is a dark rectangle) and the surfaces take the top of the table: white 0.92, sand 0.90, stone 0.82,
slate 0.78, moss 0.74, timber 0.72, because in daylight the bright things are surfaces rather than
@ -90,8 +90,8 @@ and it moves the other way. Both, measured at 200x60 on frame 300 at two seeds,
|---|---|---|---|
| **city** seed 42 | 30.0 / 7.27 | 53.1 / 0.41 | 52.0 / 3.46 |
| **city** seed 7 | 32.6 / 2.32 | 54.5 / 0.27 | 56.1 / 4.03 |
| **frontier** seed 42 | 40.9 / 0.18 | 46.5 / 0.28 | 49.0 / 5.31 |
| **frontier** seed 7 | 26.5 / 0.24 | 38.7 / 1.03 | 40.9 / 7.16 |
| **frontier** seed 42 | 40.9 / 0.18 | 46.5 / 0.28 | 51.2 / 5.34 |
| **frontier** seed 7 | 26.5 / 0.24 | 38.7 / 1.03 | 59.7 / 6.02 |
| **Moonwalk** seed 42 | 5.5 / 1.64 | 6.6 / 2.27 | 5.0 / 2.85 |
| **Moonwalk** seed 7 | 11.8 / 1.27 | 7.2 / 3.88 | 6.2 / 3.60 |
| **Edo** seed 42 | 37.1 / 0.70 | 44.8 / 3.06 | 52.5 / 3.23 |
@ -104,6 +104,14 @@ from a world whose largest wet surface was never drawn. A wet road is mid-lumina
everywhere, which is the muddy band by definition, and that is the honest price of the feature
existing.
The frontier's noon column moved for a different reason, and the same kind of honest price: the
pale band of its noon sky (the two white tiers) is now written at 0.35 of its base luminance in full
day rather than 0.80 (surf_west.js, `dayHz`), because the underpainting carries the sky's colour and a full-strength
white dash added on top of it burned to white. Glyph layer only, at seed 7 that puts the sky's
dashes in the middle of the range — 40.9 / 7.16 became 59.7 / 6.02, and seed 42 49.0 / 5.31 became
51.2 / 5.34 — while the printed composite at seed 7 goes from p99 255 to 248 and loses its white
bars.
Four things in that table are worth saying out loud rather than leaving for someone to notice.
The Moon holds the night target at every hour of its day and at both seeds, 5.0% to 11.8% against
@ -212,9 +220,10 @@ like and it hands them over; stop steering and it picks the walk back up from wh
## What is in Moonwalk
The Moon is the world this renderer was waiting for, and that is not a flourish — it is why the
third world is the Moon and not, say, a jungle. The art direction is a frame that is more than half
pure black with a thin scatter of very bright glyphs, and every other world has to be composed to
deliver that. The Moon delivers it by having no air: a shadow with nothing to fill it is genuinely
third world is the Moon and not, say, a jungle. The art direction is a glyph layer that is more than
half pure black with a thin scatter of very bright glyphs (the printed frame, with the underpainting
under it, keeps at least a third of it black at night), and every other world has to be
composed to deliver that. The Moon delivers it by having no air: a shadow with nothing to fill it is genuinely
lum 0, a sunlit surface under an unfiltered sun is genuinely the brightest thing there is, and the
sky is the same absolute black at noon as at midnight. Measured, a lunar frame prints **5.0% of its
cells in the muddy band** against the project's under-30% target and the city's 30.0%.
@ -488,7 +497,8 @@ an empty 3-20 Hz band, in every weather state.
## Running it
Open `index.html`. That is the whole thing.
Open `index.html` — over `file://` or any static server, as long as the `w/` folder sits next to
it. That is the whole thing.
To rebuild it from `src/`:
@ -496,14 +506,23 @@ To rebuild it from `src/`:
node build.js
```
`index.html` is generated — don't edit it by hand. `build.js` concatenates the modules in
`src/`, strips the CommonJS tails that exist only so the offline tools can `require` the same
files, strips the comments, halves the leading indentation, and writes one file. There is no
bundler and no minifier: the page source stays readable in View Source, which is half the point of
shipping it as a single file.
`index.html` and `w/*.js` are generated — don't edit them by hand. `build.js` concatenates the
modules in `src/`, strips the CommonJS tails that exist only so the offline tools can `require` the
same files, strips the comments, halves the leading indentation, and writes the page plus one
script per secondary world: the engine and the city inline, the frontier, the Moon and Edo in
`w/west.js`, `w/moon.js` and `w/jp.js`. There is no bundler and no minifier: the page source stays
readable in View Source.
It was one self-contained file until the high-definition pass, and that was given up deliberately:
the HD work needed ~9 KB and the single file had 2 KB left under a line that had already been raised
five times. The chunks are loaded by plain synchronous `<script src>` tags and only *define* their
modules; the inline script calls each one back at the place it always ran, so the order the city
boots in — and therefore every frame — is exactly what it was as one file. `build.js`'s essay has
the trade and the alternatives that lost (one compressed file, lazy loading). The lines are now
600 KB for `index.html` and 160 KB for each world.
The half-indent is the only thing in that list that was not always there, and it is a budget note
rather than a formatting preference. `build.js` fails the build over 560 KB, and the essay attached
rather than a formatting preference. `build.js` failed the build over 560 KB at the time, and the essay attached
to that line says in as many words that the next pass over it must **cut** rather than move the
number. This pass went over, at 575.5 KB. The two things the essay names as cuttable are content
(which is the deliverable — the wrong way round) and indentation, which it refuses on the grounds
@ -523,26 +542,56 @@ buildings, all for free and all at character resolution.
Everything after that — rain, people, signage, cars, optics — is an *element*: a small module with
`init`, `update` and `draw`, drawn in layer order onto the same character buffer, depth-tested
against the world so a walker goes behind a lamp post. There are 70 of them. Each one belongs to
against the world so a walker goes behind a lamp post. There are 79 of them. Each one belongs to
one world or to several — an element carries `world: 'cyber'`, or an array of ids, on itself and
`main.js` filters the list on a rebuild, so the city gets 42, the frontier 33 and the Moon 16.
`main.js` filters the list on a rebuild, so the city gets 42, the frontier 33, the Moon 16 and
Edo 26.
The last stage is a print. Each of the twenty colours has **two** exposure weights, night and day,
blended by the clock, then a gamma lift, a knee and a shoulder rolloff, bucketed by distance. It is
the difference between a frame that is technically correct and one that reads as a photograph of a
dark street, and most of the tuning in this repo is about it.
## The underpainting
Under the glyphs sits one more layer: one RGB value per **cell**, `f.under`, written by
`CC.Compose.post` after the print and drawn first, unsmoothed, so every cell is one flat block and
the grid survives. It exists because a glyph inks about a fifth of its cell and half the cells are
blank, so a wall the painters lit at full brightness reached the screen at a fifth of its value. It
is five terms: **mass** (the cell's own colour at a share of its lum — signs capped lower than
walls, and the share falling by day because the day ladder has already lifted the glyphs), **sky**
(a zenith-to-horizon gradient per world and hour, from each painter's `SKY_RGB`; the Moon has none),
**haze** (far cells walking toward the horizon colour, 0.8 of it by day and 0.5 at night), **rim**
(the sky wrapping a roofline) and **spill** (emitters lighting the cells round them, a tent nine by
five reference cells wide). Ambient light is weighted by ink, so a blank doorway stays dark at noon —
unless the painter wrote the blank in a lit swatch, which is how Edo says "plaster with no glyph on
it" rather than "a hole" (its `BARE` export; CONTRACT has the rule).
The bloom reads the glyphs only, so the blacks between lit cells stay black.
What it is held to, measured at 300x95 on 6x11 cells, seeds 7 and 11: night zenith rows stay
under 12 (cyber 8.3 and 6.5); cyber night keeps **46% and 59% of the composite pure black** (target
35%), with the glyph layer alone at 67% and 80%. In the three worlds with air, dusk keeps 8-39%
pure black (the field off: 64-89%) and noon 6-17% (the field off: 28-72%); Edo sits at the bottom of
both ranges because its bare plaster and earth take their share of the ambient rather than printing
as holes. The Moon, which has no ambient, keeps 51-54% at dusk and 49-56% at noon. A lit cell's gaps
never lift toward its own stroke, so signs keep their letters. `CC.Compose.UNDER = 0` is the kill switch: it
restores the frame data and the glyph layer byte-for-byte and removes the underlay draw. It does
not undo the rest of the HD print — the pixel-write glyph pass on small cells, the screen-sized
bloom and the denser cell band stay on, so the browser picture with it off is the glyph layer of
this build, not the page as it was before the HD pass.
## Tools
Everything here runs without a browser, which is how the thing gets verified at all.
| | |
|---|---|
| `tools/headless.cjs` | render any frame of any seed offline, as a text dump — `--west` / `--moon` / `--japan`, `--time=`, `--weather=`, `--yaw=` |
| `tools/topng.py` | turn that dump into a PNG, with the bloom the canvas applies |
| `tools/metrics.py` | the print census — exposure bands, colour split, what each layer costs |
| `tools/headless.cjs` | render any frame of any seed offline, as a text dump — `--west` / `--moon` / `--japan`, `--time=`, `--weather=`, `--yaw=`, `--under=k` (underpainting strength; 0 dumps no `UNDER` line), `--cell=WxH` (the cell the frame will be printed on, so frame.D matches the browser's) |
| `tools/topng.py` | turn that dump into a PNG composited the way the canvas does it — `--u[=k]` draws the underpainting, `--cell=WxH`, `--q=0/1/2` bloom quality, `--bloom=ref/cell`, `--cov` prints the coverage tables (the 9x16 reference and the ink-compensated pixel-path cells; redirect it to `tools/cov.json`). Needs Pillow **and numpy** |
| `tools/metrics.py` | the print census — exposure bands, colour split, what each layer costs; `--composite` adds the census of the printed composite (glyph ink by coverage plus the underpainting), the old one is the glyph layer only |
| `tools/composite.cjs` | shared by every probe below: the `--composite` / `--cols=` / `--rows=` / `--cell=` parser, per-cell emitted light from `tools/cov.json` (weighted at the cell the grid stands for — 1920 px across by default, so a 400-column gate reads the 5x9 ink-compensated table), and the WCAG area-weighted flash check |
| `tools/peds.cjs` | the crowd alone, against an empty frame, at a size you can actually see |
| `tools/flicker-rate.cjs` | the photosensitivity gate, for the city's signage — run it with **no arguments**, see above |
| `tools/flicker-rate.cjs` | the photosensitivity gate, for the city's signage — run it with **no arguments**, see above. It and every probe below also run with `--cols=400 --rows=120` and with `--composite` (CONTRACT has the four-mode rule) |
| `tools/lightning-rate.cjs` | the same, for storms |
| `tools/west-flicker.cjs` | the same, for every world that is not the city — pinned camera, per cell, against the city as its baseline |
| `tools/canal-flicker.cjs` | the same, for Edo's canal — pins the camera **on the water**, which the gate above structurally cannot do |
@ -557,6 +606,8 @@ and in `headless.cjs`, which is what makes any of the above worth running.
They are rendered with `tools/headless.cjs` and `tools/topng.py`, not captured from a browser
window. The frames are the real output of the real renderer at 213×67 cells, and `topng.py`
applies the same bloom the canvas does — but the font is Liberation Mono rather than whatever your
browser picks, so the shapes of individual characters will differ slightly from what you get on
screen.
applies the same bloom the canvas does. They are the **glyph layer only**: they were printed
before the underpainting shipped, so they show the page as `CC.Compose.UNDER = 0` draws it: darker,
and with no sky gradient. A current print is `topng.py f.txt out.png --u`. The font is Liberation
Mono rather than whatever your browser picks, so the shapes of individual characters will differ
slightly from what you get on screen.

198
build.js
View file

@ -1,15 +1,18 @@
/* CyberCity build — concatenate src/ into one self-contained index.html.
/* CyberCity build — concatenate src/ into index.html plus one script per secondary world.
*
* No dependencies, no bundler, no minifier, no source maps. The modules were written to be
* concatenated: each is an IIFE that resolves CC out of lexical scope, so wrapping the lot in one
* more IIFE is the entire "bundling" step. Everything this script does beyond `join('\n')` is
* removing the CommonJS tails that exist only so tools/headless.cjs can require the same files.
* removing the CommonJS tails that exist only so tools/headless.cjs can require the same files,
* and — since the split, see THE SPLIT below — parking three worlds' modules in w/*.js so that
* the one IIFE can call them back in at exactly the place they used to sit.
*
* Run: node build.js
*/
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const ROOT = path.join(__dirname);
const SRC = path.join(ROOT, 'src');
@ -195,51 +198,123 @@ function decomment(src) {
return out.replace(/[ \t]+$/gm, '').replace(/\n{2,}/g, '\n\n').trim();
}
const files = expand(ORDER);
const parts = files.map(p => {
const rel = path.relative(ROOT, p).split(path.sep).join('/');
return '/* ' + rel + ' */\n' + decomment(strip(fs.readFileSync(p, 'utf8'))) + '\n';
});
/* ---- THE SPLIT --------------------------------------------------------------------------------
* Three worlds leave index.html. Each one's painter and its prefixed elements go to w/<world>.js,
* and the page loads those with plain synchronous <script src> tags placed BEFORE the inline
* script — the essay at the bottom of this file is the decision and the reason; this is the how.
*
* THE CHUNKS DEFINE, THEY DO NOT RUN. Each module in a chunk is wrapped as one function filed under
* its src/ path in a single scratch global, self.CCW, and the inline IIFE calls each one back
* (`W(path)`) at exactly the place in ORDER the module used to be pasted. That is the whole design,
* and the obvious alternative — cut the inline script into two tags and let the chunks run between
* them — was measured against it and lost on two counts:
* REGISTRATION ORDER IS STATE. Elements push onto CC.ELEMENTS in file order, main.js sorts by
* layer with ties broken by that order, and every element draws from ONE shared rng in that
* sequence. jp_* sorts between hud.js and market.js; running the chunks as a block would move
* four Edo elements behind eleven shared ones and reseed whatever ties them — a different
* frame in the browser from the one tools/headless.cjs renders, with nothing failing.
* A SECOND TAG IS A SECOND SCOPE. The bundle is one IIFE with one `var CC` and nothing on window;
* two tags cannot share a lexical scope, so CC would have to become a global for good.
* Filed-and-called-back keeps both: execution order is byte-for-byte today's ORDER, and the only
* global is CCW, which the inline script takes a reference to and deletes on its first line.
*
* A MISSING CHUNK DEGRADES, IT DOES NOT BREAK. W() skips a path nobody filed, so a w/ file that
* failed to load costs that world (it renders as the city, see raycast.js) and the default city
* still boots. tools/domshim.cjs runs the real tags in DOM order and fails if any are absent, which
* is where that has to be caught — not in the visitor's browser.
*
* AND A CHUNK THAT THROWS DEGRADES THE SAME WAY, which the sentence above used to promise without
* doing. A module is called back synchronously inside the ONE bundle IIFE, so an exception in it
* aborted every module after it — render_canvas.js and main.js included — and the page stayed
* black. W() now catches, logs, and carries on: the world that threw is lost, the city is not.
* The likeliest way to get there is not a bug but a CACHE: the bundle and its chunks are a matched
* pair (a chunk's body uses whatever CC API its bundle had), and GitHub Pages serves both with
* max-age 600, so for ten minutes after a deploy a visitor can hold a new page and an old chunk.
* Each tag therefore carries ?v=<the chunk's content hash>, so a new bundle always asks for its
* own chunk by a URL no cache has seen; the catch is for whatever still gets through.
*
* Routing is by NAME, matching how @painters and @elements already glob: a world's painter plus
* every element carrying its prefix. A painter or element no rule claims stays inline, so a new
* world lands in index.html until somebody gives it a chunk — the safe default, since inline is
* what has always worked. */
const CHUNKS = [
['west', /^(surf_west\.js|elements\/west_)/],
['jp', /^(surf_japan\.js|elements\/jp_)/],
['moon', /^(surf_moon\.js|elements\/moon_)/]
];
const WDIR = path.join(ROOT, 'w');
const CAP_PAGE = 600 * 1024, CAP_CHUNK = 160 * 1024;
/* One IIFE, one `var CC`. core.js declares CC with `var`, so it is hoisted to the top of this
* function and every later module's `typeof CC !== 'undefined'` guard sees it. Nothing leaks to
* window, which is the point: the page has no API surface to poke at. */
/* ---- one 'use strict', not thirty-three -------------------------------------------------------
* Every module in src/ opens its IIFE with `'use strict';` because every module is also `require`d
* on its own by tools/headless.cjs, where nothing else would supply it. Concatenated, that is 33
* copies of the same 13-byte directive inside one wrapper that is itself sloppy-mode — so the
* directive is doing real work per module and cannot simply be deleted.
const files = expand(ORDER);
const inline = [], chunkParts = {}, chunkFiles = {};
for (const [w] of CHUNKS) { chunkParts[w] = []; chunkFiles[w] = []; }
for (const p of files) {
const rel = path.relative(SRC, p).split(path.sep).join('/');
/* ---- one 'use strict', not thirty-three -----------------------------------------------------
* Every module in src/ opens its IIFE with `'use strict';` because every module is also
* `require`d on its own by tools/headless.cjs, where nothing else would supply it. Concatenated,
* that is 33 copies of the same 13-byte directive inside one wrapper that is itself sloppy-mode —
* so the directive is doing real work per module and cannot simply be deleted.
*
* Hoisting it is the cut. One directive on the wrapper makes the WHOLE bundle strict, which is
* exactly the union of what the 33 were doing individually, and there is no code in the bundle
* outside a module IIFE for it to newly apply to. 481 bytes, and the only non-content cut left
* after the dead-identifier sweep that does not touch a line of source.
* after the dead-identifier sweep that does not touch a line of source. A chunked module's
* wrapper function carries the directive instead, since a w/ file is its own script and would
* otherwise be sloppy.
*
* The match is deliberately narrow: a line whose ENTIRE content is the directive. A `'use strict'`
* inside a string literal or trailing another statement is left alone, because this runs after
* decomment() and has no parser to tell it apart. */
const parts2 = parts.map(p => p.replace(/^[ \t]*(['"])use strict\1;[ \t]*$\n?/gm, ''));
const bundle = "(function () {\n'use strict';\n" + parts2.join('\n') + '\n})();\n';
const body = ('/* src/' + rel + ' */\n' + decomment(strip(fs.readFileSync(p, 'utf8'))) + '\n')
.replace(/^[ \t]*(['"])use strict\1;[ \t]*$\n?/gm, '');
const hit = CHUNKS.find(c => c[1].test(rel));
if (!hit) { inline.push(body); continue; }
chunkFiles[hit[0]].push(p);
chunkParts[hit[0]].push('W[' + JSON.stringify(rel) + '] = function (CC) {\n\'use strict\';\n' + body + '};\n');
inline.push('W(' + JSON.stringify(rel) + ');\n');
}
/* The page must open with ZERO network requests, so nothing may reference a module loader. */
if (/\brequire\s*\(/.test(bundle)) throw new Error('build: a require() survived the strip');
if (/\bmodule\.exports\b/.test(bundle)) throw new Error('build: a module.exports survived the strip');
if (/\bimport\s|\bexport\s/.test(bundle)) throw new Error('build: ESM syntax in the bundle');
/* A literal closing script tag anywhere in the sources would end the inline block early and dump
* the rest of the city into the document as text. */
if (/<\/script/i.test(bundle)) throw new Error('build: source contains a closing script tag');
/* One IIFE, one `var CC`. core.js declares CC with `var`, so it is hoisted to the top of this
* function and every later module's `typeof CC !== 'undefined'` guard sees it. Nothing leaks to
* window, which is the point: the page has no API surface to poke at. W is declared ahead of
* core.js's `var CC` but only ever CALLED after it, so every chunk receives the live object. */
const bundle = "(function () {\n'use strict';\nvar W = (function (o) { delete self.CCW; " +
"return function (k) { if (o[k]) try { o[k](CC); } catch (e) { console.error(k, e); } }; })(self.CCW || {});\n" + inline.join('\n') + '\n})();\n';
const chunks = CHUNKS.filter(([w]) => chunkParts[w].length).map(([w]) => ({
name: w, rel: 'w/' + w + '.js', files: chunkFiles[w],
text: '/* CyberCity — ' + w + ' world. Generated by build.js from src/; loaded by index.html, which\n' +
' * calls each function below back at its place in the build order. Do not edit by hand. */\n' +
"(function (W) {\n" + chunkParts[w].join('\n') + '})(self.CCW || (self.CCW = {}));\n'
}));
/* Every check that used to run on the one bundle now runs on EVERY script that ships, and the
* global list runs on their concatenation: a painter that moved to a chunk still has to be in
* the deliverable, it just no longer has to be in index.html. */
const shipped = [{ rel: 'index.html', text: bundle }].concat(chunks);
for (const c of shipped) {
const t = c.text, at = ' (' + c.rel + ')';
/* The page must open with no module loader, so nothing may reference one. */
if (/\brequire\s*\(/.test(t)) throw new Error('build: a require() survived the strip' + at);
if (/\bmodule\.exports\b/.test(t)) throw new Error('build: a module.exports survived the strip' + at);
if (/\bimport\s|\bexport\s/.test(t)) throw new Error('build: ESM syntax in the bundle' + at);
/* A literal closing script tag anywhere in the sources would end the inline block early and dump
* the rest of the city into the document as text. A chunk is not inline and could survive one,
* and is held to the same rule anyway so a module can move between the two without re-checking. */
if (/<\/script/i.test(t)) throw new Error('build: source contains a closing script tag' + at);
/* Compiles each script without running it. This is what makes the comment scanner safe to
* trust: if it ever mangles a regex literal or a template string, the build stops here. */
try { new Function(t); }
catch (e) { throw new Error('build: ' + c.rel + ' does not parse — ' + e.message); }
}
/* Every module named its global; if one is missing it was dropped, mis-ordered, or the comment
* scanner ate something structural. Cheap, and it has caught both. */
const all = shipped.map(c => c.text).join('\n');
for (const need of ['var CC', 'CC.City', 'CC.Surf', 'CC.Cast', 'CC.Canvas', 'CC.Main',
'CC.World', 'CC.SurfWest', 'CC.SurfMoon', 'CC.SurfJapan',
'CC.Daylight', 'CC.ELEMENTS.push'])
if (!bundle.includes(need)) throw new Error('build: bundle is missing ' + need);
/* Compiles the bundle without running it. This is what makes the comment scanner safe to trust:
* if it ever mangles a regex literal or a template string, the build stops here. */
try { new Function(bundle); }
catch (e) { throw new Error('build: bundle does not parse — ' + e.message); }
if (!all.includes(need)) throw new Error('build: bundle is missing ' + need);
/* The page is black before a single pixel of city is drawn — html, body and canvas all — so that
* entering fullscreen never flashes white and never shows a seam at an edge the canvas overhangs.
@ -294,19 +369,33 @@ ${BASELINE}<style>
<canvas id="cc"></canvas>
<div id="hint">click for fullscreen</div>
<a id="legal" href="https://carino.systems/legal.html">Legal</a>
<script>
${chunks.map(c => '<script src="' + c.rel + '?v=' + crypto.createHash('sha1').update(c.text).digest('hex').slice(0, 10) + '"></script>\n').join('')}<script>
${bundle}</script>
</body>
</html>
`;
fs.writeFileSync(OUT, HTML, 'utf8');
/* w/ is rewritten whole: a chunk this build did not produce (a world renamed or folded back
* inline) would otherwise sit there being published and never loaded. */
fs.mkdirSync(WDIR, { recursive: true });
for (const f of fs.readdirSync(WDIR))
if (f.endsWith('.js') && !chunks.some(c => c.rel === 'w/' + f)) fs.unlinkSync(path.join(WDIR, f));
for (const c of chunks) fs.writeFileSync(path.join(ROOT, c.rel), c.text, 'utf8');
const kb = n => n + ' bytes (' + (n / 1024).toFixed(1) + ' KB)';
const bytes = Buffer.byteLength(HTML, 'utf8');
let over = false;
for (const p of files)
console.log(' + ' + path.relative(ROOT, p).split(path.sep).join('/'));
console.log('index.html ' + bytes + ' bytes (' + (bytes / 1024).toFixed(1) + ' KB) ' +
files.length + ' modules');
console.log('index.html ' + kb(bytes) + ' ' + (files.length - chunks.reduce((n, c) => n + c.files.length, 0)) +
' modules headroom ' + (CAP_PAGE - bytes));
if (bytes > CAP_PAGE) { console.error('build: index.html is over the 600 KB budget'); over = true; }
for (const c of chunks) {
const n = Buffer.byteLength(c.text, 'utf8');
console.log(c.rel.padEnd(11) + ' ' + kb(n) + ' ' + c.files.length + ' modules headroom ' + (CAP_CHUNK - n));
if (n > CAP_CHUNK) { console.error('build: ' + c.rel + ' is over the 160 KB per-world budget'); over = true; }
}
/* THE BUDGET WAS 200 KB AND IT IS NOW 300 KB. That is a raise, not a discovery, and it is being
* written down rather than quietly deleted. src/ went from roughly 190 KB to roughly 530 KB in one
* pass — twelve new ambient elements, a weather director every element reads, four input devices,
@ -545,8 +634,39 @@ console.log('index.html ' + bytes + ' bytes (' + (bytes / 1024).toFixed(1) + '
* tree and it is worth two thousand bytes. A world is thirty thousand. Splitting the payload costs
* the "one self-contained file" property, which is the first line of CONTRACT.md and is a real
* loss — but it is the only remaining answer that is not "ship less", and it should be taken
* deliberately, by someone who has decided that trade, rather than discovered at this line again. */
if (bytes > 600 * 1024) {
console.error('build: index.html is over the 600 KB budget');
process.exit(1);
}
* deliberately, by someone who has decided that trade, rather than discovered at this line again.
*
* ---- AND THE PASS AFTER THAT SPLIT IT. ONE 600 KB LINE -> 600 KB + 3 x 160 KB. ----
* Seventh time at this line, and the first time the answer is the one the last three paragraphs
* asked for. It was DECIDED, by the owner, before a byte of it was written — which is the condition
* the paragraph directly above set — and this is the record of what was traded.
*
* WHY NOW: the high-definition pass (an underpainting behind the glyphs, a pixel-path printer,
* density-correct optics) was costed at 8.5-9 KB against 1,983 bytes of headroom. The banked
* duplication cut is 2.35 KB of it. No ordering of the three moves closes that, and the fourth
* option — the next world — was already known not to fit. So it split.
*
* WHAT WAS SPENT: the "one self-contained file" property. index.html is still the page, still
* opens with no server (file:// runs classic <script src> fine), still makes no request outside
* its own folder — but it is now one file and a w/ directory, and copying index.html alone gets
* you the city and three worlds that render as the city. CONTRACT.md's first line says so now.
*
* WHAT WAS CONSIDERED AND REFUSED:
* ONE FILE, COMPRESSED. A deflate-raw blob inflated by DecompressionStream at boot is ~210 KB and
* roughly triples the headroom while keeping one file. It also turns the page source into a
* base64 wall — the thing the indentation refusal has protected three times — puts an async
* step in front of a boot that has never had one, and drops every browser without that API.
* LAZY CHUNKS. Fetching a world when it is first selected is the smaller first load, and it is
* the one that changes behaviour: init order, the shared rng sequence and the world switch would
* all gain an await. Synchronous tags cost ~220 KB of parse on a first visit and nothing else.
* TWO INLINE TAGS WITH THE CHUNKS RUN BETWEEN THEM, which is the plan's first sketch. It reorders
* CC.ELEMENTS and promotes CC to a global — see THE SPLIT above for why both matter.
*
* WHAT THE LINES ARE NOW, and both are hard stops: index.html at 600 KB (the old number, kept, now
* holding the engine and the city with about 220 KB under it), and each w/*.js at 160 KB — a little
* over twice the biggest world (the frontier, ~94 KB) so one world can double before anyone is here
* again. A fifth world is a fourth chunk and a CHUNKS row, not a raise.
*
* WHAT IS NOT LICENSED: reading 220 KB of headroom as permission. Every essay above that ended with
* room to spare was followed by a pass that spent it. Cut first, still. */
if (over) process.exit(1);

6851
index.html

File diff suppressed because it is too large Load diff

BIN
og.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

View file

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- generated by Carino-Systems/baseline/apply.py — edit the template, not this file -->
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url><loc>https://cybercity.carino.systems/</loc></url>
</urlset>

View file

@ -112,13 +112,19 @@ var CC = (function () {
col: new Uint8Array(n),
lum: new Uint8Array(n),
dist: new Float32Array(n),
kind: new Uint8Array(n)
kind: new Uint8Array(n),
under: new Uint8ClampedArray(n * 3), // the underpainting: see CC.Compose, the one writer
/* Both declared here although other modules write them — D by raycast.js, uon by
* Compose.post — so the frame has its whole shape from birth: a field added on the first
* render changes the object's hidden class under every hot loop that reads it. */
D: 1, uon: false
};
}
function clearFrame(f) {
f.ch.fill(0); f.col.fill(0); f.lum.fill(0); f.kind.fill(0);
f.dist.fill(Infinity);
if (W0 && W0.f === f) W0.f = null; // a new frame: the underpainting's world snapshot is spent
}
// The only sanctioned write. Depth-tests so elements can never punch through a wall.
@ -590,6 +596,14 @@ var CC = (function () {
* from Surf.fog at lum 0 and is skipped below, and every object in elements/sky.js is deliberately
* given a distance beyond it so that it self-occludes against the world pass. */
var SKY_D = FOG_END;
/* THE SOURCE SET, written down ONCE. ladder() below puts these on the squared-sun curve, and the
* underpainting's emitter set EM is built from this same list plus the accent lamps, because the
* two were hand-copied literals for one pass and a list kept in two places is two lists. Being
* in SRC is a statement about the LADDER (holds its gain through dusk) and moves the glyph layer;
* being in EM only is a statement about the WASH (caps its panel, spills on its neighbours) and
* moves nothing but f.under. Do not promote a swatch from one to the other to get the second. */
var SRC = [0, 1, 8, 9, 15, 16, 17], SRCF = new Uint8Array(PALETTE.length);
for (var si = 0; si < SRC.length; si++) SRCF[SRC[si]] = 1;
/* ---- THE DAY LADDER ---------------------------------------------------------------------------
* The table above is fitted to a NIGHT frame and says so at length: LIGHT OUTRANKS STRUCTURE, the
@ -774,9 +788,7 @@ var CC = (function () {
* there is a sun to lift it. Put a surface on the sun curve and it stays at its night gain
* through the whole of dawn — the wall goes bright only after the sky already has, which is
* the dusk fault above running backwards. */
var src = (c === 0 || c === 1 || c === 8 || c === 9 ||
c === 15 || c === 16 || c === 17); // amber azure warm ice + jade rose gold
var m = src ? sunMix * sunMix : mix;
var m = SRCF[c] ? sunMix * sunMix : mix; // amber azure warm ice + jade rose gold: SRC below
return EXPOSURE[c] + (EXPOSURE_DAY[c] - EXPOSURE[c]) * m;
}
@ -875,12 +887,331 @@ var CC = (function () {
* gains its daylight from the sky and a SOURCE loses its advantage only to the sun. See the note
* on `sky` in daylight.js for why that parameter carries a misleading name on an airless world
* and why it is still the right input here. */
/* ---- THE UNDERPAINTING ------------------------------------------------------------------------
* One RGB value per CELL, laid under the glyphs on the character grid and added to them. It exists
* because of a number nobody had looked at: a glyph inks at most ~40% of its cell in this font and
* 21% on average, and about half the cells are blank, so a wall the painters lit at full lum still
* reached the glass at a fifth of its value. The picture had ink and no TONE — no large shapes, no
* sky, no depth — and every resolution increase only made the ink finer. This field is the tone,
* and it is five terms, each one a thing a painter does with a wash before the line work goes on:
*
* MASS the cell's own colour at a fraction of its printed lum, so a lit wall is a lit PANEL
* SKY a zenith-to-horizon gradient per world and hour, behind every open-sky cell
* HAZE aerial perspective: far cells walk toward 0.8 x the horizon colour with depth
* RIM where a roofline meets the sky the sky wraps the edge, which is what a silhouette is
* SPILL the emitters' light on the cells round them, a box in REFERENCE cells (see below)
*
* It is drawn NEAREST, one flat block per cell, and never fed to the bloom. Both are measured
* decisions rather than taste: a bilinear field smeared the cyber street into a violet haze, and a
* bloomed one greyed every black between the lit cells, which is the negative space the night
* frame is built out of.
*
* WHAT IT NEVER TOUCHES is ch/col/lum. The glyph layer is byte-identical with it on or off, so
* every census, fixture and flicker probe fitted to that layer still reads the frame it was
* fitted to, and CC.Compose.UNDER = 0 is a kill switch rather than a setting: nothing is computed,
* nothing is written, and the frame data and glyph layer are today's to the byte (the rest of the
* HD print — pixel pass, screen-sized bloom, cell band — is not this switch's to undo; CONTRACT
* says exactly what it restores). Between 0 and 1 it is the
* strength, applied once at the end so it scales the whole wash without moving its balance.
*
* THE SKY TABLE lives on the painter export as SKY_RGB, not here, because the registry rule says a
* world is everything its painter file says and nothing core has to know the name of: 18 numbers,
* zenith then horizon (rgb, rgb) at NIGHT, at NOON and at the DUSK colour the warm term pulls
* toward. The city's is on CC.Surf, which is the city's painter. A painter with NO table gets no
* sky at all — that is the Moon, which has a black sky and gets regolith ambient instead. */
var UK = [0.12, 0.3, 0.13, 0.3], NG = GLYPHS.length, THIN = new Uint8Array(NG), EM = new Uint8Array(PALETTE.length), SH = P.shadow;
var W0 = null, Z = new Float32Array(9), q = [0, 0, 0], r = [0, 0, 0], KS = ['ch', 'col', 'lum', 'kind', 'dist'], sp, tp, tq, AC;
/* Per-frame terms fld() reads, set once at the top of under(): the ambient, the sun on a figure,
* the sky and wall mass shares, and the haze target's fraction of the horizon colour. */
var DY = 0, SN = 0, M0 = UK[0], M1 = UK[1], HT = 0.8, FE = FOG_END;
/* THE BARE SHARES, and the painter's swatch on a blank cell is what selects them (see fld). BW
* and BF are a bare wall's and a bare floor's share of the ambient; the defaults are the hole
* rule exactly, and a painter overrides them with a BARE = [wall, floor] export beside its
* SKY_RGB. SL is slate, the other unlit swatch. */
var BW = 0.1, BF = 0.5, SL = P.slate;
'.,:;\'"`^~-_=+|/\\'.split('').forEach(function (c) { THIN[GI[c]] = 1; });
/* EM: the swatches that EMIT — SRC, the ladder's source set, plus the four accents that are lamps
* or screens (ember, spring, violet, red). Violet is in because the palette says what it is for —
* "screens and signage only" — and out, it was the one sign that took a surface's 0.30 panel and
* no spill: the flat-slab case the cap below exists for, in the one hue nobody had tested. Two
* things key off EM. Only these spill. And their MASS is capped at 0.18 where a surface gets 0.30,
* because a sign is lit from inside and is already the brightest ink in its neighbourhood: at 0.30
* a near signboard filled its whole rectangle with one saturated value and printed as a flat slab
* with the letters lost on it. At 0.18 the panel is there and the letters still lead it. */
SRC.concat([2, 3, 4, 6]).forEach(function (c) { EM[c] = 1; });
/* The world pass, snapshotted before any element draws. An element is drawn OVER something, and
* the field has to know what: a hairline rain streak over a lit wall keeps the wall's panel, a
* pedestrian over the sky becomes a silhouette. It is also what keeps lightning out of the mass
* term — the flash is an element's lum, and the wall under it is read from before it struck.
*
* STAMPED WITH THE FRAME IT WAS TAKEN FOR, and the stamp is spent: post() clears it after use and
* clearFrame() clears it on the next frame. Unstamped, a caller that never called world() — a
* probe that only wants post()'s tone — was handed whatever the snapshot last held: the first
* time, the finished frame (already toned, so toned twice); every time after, a world from an
* earlier frame with its "toned" flag still set. Nothing read the field in those callers, which
* is the only reason it never showed. */
function world(f) {
if (!Compose.UNDER) return;
var j, n = KS.length;
if (!W0 || W0.n !== f.n) for (W0 = { n: f.n }, j = 0; j < n; j++) W0[KS[j]] = f[KS[j]].slice();
else for (j = 0; j < n; j++) W0[KS[j]].set(f[KS[j]]);
W0.t = 0; W0.f = f;
}
/* One cell's wash into q: mass, then either the row's sky (backdrop) or ambient plus haze (a thing
* in the air). FLOORS ARE GATED ON INK: the road is drawn in commas and full stops, and a mass
* behind a comma is a grey brick — the west street printed as cobbles nobody laid. A floor cell
* earns a mass only when its glyph is not one of the hairlines in THIN — when the ink is already a
* mass ('#', '8', 'o') the panel behind it reads as the same stone, not as a brick round a comma.
*
* THE AMBIENT IS GATED ON INK TOO, and that is what gives the day its blacks back. It was a flat
* share of the horizon colour laid on every world cell, lit or not, and in daylight that is every
* cell in the frame: cyber, west and Edo printed EXACTLY 0.0% black at every hour between dawn and
* dusk, doorways and window holes came out brown-grey, and the dusk street was one sepia veil. A
* blank WALL cell is a hole the painter left on purpose — a doorway, a window, a gap — so it takes
* a tenth of the ambient (a quarter left cyber noon at 3.9% black; a tenth gives 18.7%, against
* 54% with the field off). A blank FLOOR cell is not a hole, it is ground the painter left bare,
* and at a tenth the Edo street at noon printed as night tarmac, so it takes half; an inked
* one takes it in proportion to its lum up to 96, so a dim mullion is a dim panel and a lit one a
* lit panel — and since lum carries the painter's texture and depth fade, the wash carries them
* too. The floor's share also walks from 0.6 at the eye to 1.0 at 60 m (or the fog's end if it is
* nearer), on the TRUE distance rather than the haze ramp (which is flat zero inside fogStart, and
* on the Moon that is the whole near plain): the road nearest the eye is in the canyon's shadow,
* and before this a blank Edo road was one value over a third of the frame.
*
* AND BLANKNESS ALONE DOES NOT MAKE A HOLE; THE PAINTER'S SWATCH SAYS WHICH IT IS. Every painter
* writes a blank in `shadow`, and in the city and the frontier a blank wall cell genuinely is a
* doorway or a window, which is what the tenth was fitted on. Edo's is not. Its header says
* nothing there goes to black but the shadow under an eave, and its walls and road thin their
* glyphs by the light — `cov`, cubed — so most of its blank cells are lit timber, plaster and
* earth the dither left without a glyph. Read as holes, its noon facades printed as black
* perforated camouflage (29.6% of wall cells pure black at seed 7, against the frontier's 4.9%),
* whole kura as solid black blocks under a blue sky, and its road at 0.5 x 0.2 of the horizon
* came out DARKER at noon than at dusk (bottom 40% luma 18.4 against 21.4) with the noon crowd
* at 1.07:1 against it — invisible. So a painter that means "surface, no glyph" writes the blank
* in the surface's own swatch, and a blank in `shadow` or `slate` is still a hole. That swatch
* prints nothing — ch 0 is never drawn — so the glyph layer is the same picture; and a painter
* that never writes one, which today is every painter but Edo's, gets the old rule to the byte,
* BARE export or not. Elements keep the tenth whatever their swatch. A FIGURE (kd 3)
* additionally takes 0.3 of the horizon by the direct sun, because at noon a pedestrian is a lit
* form and not a hole in the street; at night that term is zero.
*
* HAZE IS QUADRATIC in the depth ramp, a^2 rather than an ease-out: air accumulates. On the city's
* ramp the ease-out had already laid 37% of the horizon colour over a wall forty metres off, and in
* the cyber canyon that is most of the frame — night went from black-with-light-in-it to blue-grey.
* a^2 lays 6% there and still reaches the full horizon at the end of the ramp. Its TARGET is HT of
* the horizon: 0.8 by day, 0.5 at night, because at night the horizon colour is the glow the signs
* put in the air low down, and a far unlit tower walked 80% of the way to it printed as a crisp
* periwinkle panel in the middle of the cyber street. */
function fld(c, L, kd, d, a, gc) {
var p = PALETTE[c], w = kd && d < SKY_D, k, v, m = a > 1 ? 1 : a > 0 ? a : 0,
l = L / 255 * (!w ? M0 : kd === 2 ? (THIN[gc] ? 0 : UK[2]) : EM[c] ? 0.18 : M1),
bare = c !== SH && c !== SL,
am = ((kd === 2 ? 0.2 * (0.6 + 0.4 * (d < FE ? d / FE : 1)) : 0.16) * DY + (kd === 3 ? 0.3 * SN : 0)) *
(gc ? (L < 96 ? L / 96 : 1) : kd === 2 ? (bare ? BF : 0.5) : kd === 1 && bare ? BW : 0.1);
for (k = 0; k < 3; k++) {
v = p[k] * l;
if (!w) v += Z[k + 6];
else v += Z[k + 3] * am, v += (Z[k + 3] * HT - v) * m * m;
q[k] = v;
}
}
/* Running-sum box passes, O(1) per cell whatever the width. hbox runs along each row (stride 3,
* three channels interleaved); vbox runs a whole ROW of column sums at once, so it walks memory
* in order too — a per-column vertical pass strides a row's width per step and measured a third
* slower on the whole field at 360 columns. */
function hbox(a, b, R, C, h) {
for (var y = 0; y < R; y++) for (var k = 0; k < 3; k++) {
var o = y * C * 3 + k, s = 0, x;
for (x = 0; x < h && x < C; x++) s += a[o + x * 3];
for (x = 0; x < C; x++) {
if (x + h < C) s += a[o + (x + h) * 3];
if (x > h) s -= a[o + (x - h - 1) * 3];
b[o + x * 3] = s;
}
}
}
function vbox(a, b, R, C3, h) {
var ac = AC && AC.length === C3 ? AC.fill(0) : (AC = new Float64Array(C3)), y, x, o;
for (y = 0; y < h && y < R; y++) for (o = y * C3, x = 0; x < C3; x++) ac[x] += a[o + x];
for (y = 0; y < R; y++) {
if (y + h < R) for (o = (y + h) * C3, x = 0; x < C3; x++) ac[x] += a[o + x];
if (y > h) for (o = (y - h - 1) * C3, x = 0; x < C3; x++) ac[x] -= a[o + x];
for (o = y * C3, x = 0; x < C3; x++) b[o + x] = ac[x];
}
}
function under(f, cam) {
var n = f.n, C = f.cols, R = f.rows, u = f.under || (f.under = new Uint8ClampedArray(n * 3)), G = +Compose.UNDER;
if (!W0.t) tone(W0), W0.t = 1;
if (!sp || sp.length !== n * 3) sp = new Float32Array(n * 3), tp = new Float32Array(n * 3), tq = new Float32Array(n * 3);
var Sf = CC.Surf, Wp = CC.SURFACES && CC.World && CC.SURFACES[CC.World.id], S = CC.Daylight && (Wp ? Wp.SKY_RGB : Sf && Sf.SKY_RGB);
/* DY is the AMBIENT: skylight plus a third of the warm term, which is the low sun's bounce off
* the ground and the facades — without it a dusk street was a black cut-out under a lit sky
* (west dusk mean 33) where the eye sees warm shadow with the walls still in it.
*
* THE MASS SHARES FALL WITH THE SKY: sky glyphs 0.12 -> 0.04 and surface walls 0.30 -> 0.18 at
* noon, both the identity at night. The day ladder has already lifted every glyph's lum by day,
* so a share fitted to the night frame laid a second daylight on top of the first: the cyber
* facades printed as a quilt of flat grey tiles (a third of the frame in identical runs of twelve
* cells or more), and in the frontier's noon sky every dash cell sat 17 levels over its blank
* neighbours, so the 3% of blank cells read as dark squares dotted across the blue. */
var P = CC.Daylight && CC.Daylight.P, sk = P && S ? P.sky : 0, sun = P && !S ? P.sun : 0, k, x, y, i, o, t, v, j, b;
DY = P && S ? sk + 0.3 * P.warm : 0; SN = P && S ? P.sun : 0;
var Bt = Wp ? Wp.BARE : Sf && Sf.BARE;
BW = Bt ? Bt[0] : 0.1; BF = Bt ? Bt[1] : 0.5;
M0 = UK[0] * (1 - 0.7 * sk); M1 = UK[1] * (1 - 0.4 * sk); HT = 0.5 + 0.3 * (DY < 1 ? DY : 1);
/* fogStart may legitimately be 0, so it is tested for presence rather than truth; a ramp that
* has collapsed (end at or before start, which a weather blend could reach) is a wall of haze
* at fogStart rather than a division by zero — the clamp in fld() swallowed the NaN that made
* before, by accident, and the water branch is the record of what accidents like that cost. */
var f0 = Sf && Sf.fogStart >= 0 ? Sf.fogStart : FOG_START, fs = (Sf && Sf.fogEnd > 0 ? Sf.fogEnd : FOG_END) - f0, hz = cam && cam.horizon || R * 0.56;
if (!(fs > 1e-3)) fs = 1e-3;
FE = f0 + fs < 60 ? f0 + fs : 60;
/* Zenith/horizon for this hour: night toward noon on the sky term, then toward the dusk pair on
* the warm term — fully at the horizon and 0.6 at the zenith, because a low sun colours the band
* it sits in and leaves the top of the sky blue, which is the difference between a golden dusk
* and an orange lid on the frame. */
for (k = 0; k < 6; k++) Z[k] = S ? S[k] + (S[k + 6] - S[k]) * P.sky : 0, S && (Z[k] += (S[k + 12] - Z[k]) * P.warm * (k < 3 ? 0.6 : 1));
var Wk = W0.kind, Wc = W0.col, Wh = W0.ch, Wl = W0.lum, Wd = W0.dist, fk = f.kind, fc = f.col, fh = f.ch, fl = f.lum, fd = f.dist, e0 = -1, e1 = -1;
for (y = 0, i = 0; y < R; y++) {
/* this row's sky: sqrt, so the horizon band is narrow and the zenith colour owns most of it */
for (t = Math.sqrt(Math.max(0, Math.min(1, (hz - y) / hz))), k = 0; k < 3; k++) Z[k + 6] = Z[k + 3] + (Z[k] - Z[k + 3]) * t;
for (x = 0; x < C; x++, i++) {
o = i * 3;
var wk = Wk[i], kd = fk[i], c = fc[i], gc = fh[i], L = gc ? fl[i] : 0, d = fd[i], p = PALETTE[c], wd = Wd[i], a = (wd - f0) / fs;
fld(Wc[i], Wh[i] ? Wl[i] : 0, wk, wd, a, Wh[i]);
r[0] = q[0]; r[1] = q[1]; r[2] = q[2];
/* An element: dense ink hides the world and hairlines do not, so rain over a wall keeps the
* wall. Against open sky it IS the sky's silhouette. The visor (HUD, dist < 0.1) is a stencil
* on the glass and gets nothing at all — not a wash, not a spill.
*
* AND AN ELEMENT HIDES THE WALL IN PROPORTION TO WHAT IT PRINTS, full only from lum 24 up.
* The deliberate occluders — a police cordon's body, a cat, a dark figure — are drawn in the
* shadow swatch and stay opaque at any lum; everything else that printed NOTHING used to be
* opaque too, and that is a hologram fogged under the print floor. The holo panel lands
* cells at lum 5 that tone to 0, so its scan band walked a black hole across the hazed
* tower behind it: flicker-rate's still-holo check stepped one cell 1.6 -> 29.2 every time
* the band passed (seed 555, composite, 200x60), 10.8% of full scale against the 10% line,
* for a panel the glyph layer does not show at all. signage.js has already written down the
* right rule — a hologram composites as LIGHT and never darkens what it lands on — and a
* ramp on printed lum is that rule without naming any one element: a thing too dim to see
* is too dim to stand in front of anything, and a lit figure is still a solid one. */
var vis = kd === 3 && d < 0.1, op = vis ? 1 : kd === 3 && d < wd ? (c === SH || !wk ? 1 : (THIN[gc] ? 0.25 : 0.75) * (L < 24 ? L / 24 : 1)) : 0;
if (op && !vis) fld(c, L, wk && 3, d, (d - f0) / fs, gc);
else if (vis) q[0] = q[1] = q[2] = 0;
/* AN EMITTER SPILLS ONLY ONTO SOMETHING. The test is the world under the cell: a sign over a
* wall lights the wall, but an amber cloud-bar dash over open night sky (west, seed 7) has
* nothing within a hundred metres to light, and it was printing hard-edged horizontal slabs
* of (26,29,21) into a sky of (3,5,13). Sky elements carry a distance past SKY_D and are out
* for the same reason. */
var rim = y && wk === 1 && Wk[i - C] === 0, e = S && !vis && wk && d < SKY_D && L > 90 && EM[c] ? (L - 90) / 165 * 0.7 : 0;
/* Lit regolith: grey with a breath of warmth, floors brighter than walls. Only lightly
* ink-weighted on the floor — the plain is one lit surface, and a weight that followed every
* pebble's lum printed it as a grey checkerboard — but walked 0.6 -> 1.0 along the depth
* ramp's end, so it recedes instead of printing 3,555 cells of one value. The WALLS are wholly
* ink-weighted: a shadow face on an airless world is black, and a constant here printed
* every blank cell of every unlit rock face at one identical grey, a slab of cardboard. */
var hk = wk && L ? (EM[c] ? 1.7 : 1.25) * L / 255 : 0;
var mf = sun && kd ? sun * (kd === 2 ? (0.32 + 0.2 * L / 255) * (0.6 + 0.4 * (wd < FE ? wd / FE : 1)) : 0.43 * L / 255) : 0;
for (k = 0; k < 3; k++) {
v = r[k] + (op ? (q[k] - r[k]) * op : 0);
if (rim) v = Math.max(v, Z[k + 6] * 0.9);
if (mf) v += (150 + 4 * (k >> 1) + 2 * (k & 1)) * mf;
/* THE TOE, v^2/(v+8): under ~8 the wash bends toward zero, above ~40 it is nearly linear.
* A dim slate wall at night is UNLIT concrete and the doctrine is that it prints black;
* without the toe every such cell carried a value of 3-6, under the visible threshold
* one at a time and a grey veil over the whole frame together.
*
* THE HEADROOM CAP, 255 - 1.25 x the glyph's own printed channel: the wash may fill a
* cell's gaps but never lift them toward the stroke that is already in it. A white sign
* is not an emitter by swatch (white is what light LANDS on), so its letters took the
* full 0.30 panel and the gaps between strokes filled with near-white: the '####/8888'
* board in cyber night printed as a solid block and the frame's clipped pixels went from
* 0.24% to 1.53%. The cap keys on what prints, not on the swatch id, so it catches every
* bright cell whatever it is painted in and leaves a dim one alone. An EMITTER's cap is
* 1.7 x its stroke, because the bloom is laid over a sign and not over a wall: at 1.25 the
* big amber banner in cyber night (seed 7) still clipped its halo, 1.27% of the frame
* against 0.24% with the field off, and at 1.7 it is 0.29%. And the SKY is never capped:
* a backdrop cell's wash is the sky itself, and capping it under every bright dash
* printed the frontier's noon sky as a field of dark squares where the dashes are. */
v = v * v / (v + 8) * G; t = 255 - p[k] * hk;
u[o + k] = v < t ? v : t; sp[o + k] = p[k] * e;
}
if (e > 0) { if (e0 < 0) e0 = y; e1 = y; }
}
}
/* SPILL: a TENT, built as two box passes per axis, so it stays O(1) per cell whatever its size.
* One box made a flat-topped pool with a step at its edge — around the yellow '888' sign a
* visible rectangle behind the letters and a uniform skirt past them — and two boxes convolved
* fall off linearly to nothing at the same 9 x 5 footprint, which is what light from a panel
* does. That footprint is in REFERENCE cells (a round pool on 9:16 glass) scaled by frame.D, the
* grid's density against the 200-column reference: a lamp lights the same patch of street at
* 360 columns as at 200, rather than a quarter of it. The sum is normalised by the kernel's
* area, so the pool's brightness does not change with density either — only how finely it is
* drawn. Nothing spills on the Moon: there is no air to scatter it.
*
* THE GAIN IS 1.2, down from the box's 1.9, and it was set by a gate rather than by eye. A
* tent the same size as the box puts three times the box's weight on an emitter's nearest
* neighbours, so at 1.9 a cell beside a moving emitter stepped three times as hard: the holo
* scan band, with its drift patched out, went from 9.6% to 10.3% of full scale per frame on the
* composite at 400x120 (seed 555) against flicker-rate's 10% limit. 1.2 puts the nearest
* neighbour back where the box had it and spends the saving at the pool's edge.
*
* ONLY OVER THE ROWS A POOL CAN REACH. The four passes and the sweep ran over the whole grid
* whenever the world had a sky, and on a frame with no emitter that is four full-field box
* filters of zeros: profiled at 400x120, cyber night, the passes were a tenth of the frame's
* CPU and the stage cost 4.5 ms against 0.24 with the field off. e0..e1 are the first and last
* rows that emitted. The pool's support is exactly that band grown by the two vertical radii,
* and sp is zero outside it (every cell writes its sp above, emitting or not), so the passes
* run on that slab as if it were the whole grid — a box truncated at the slab's edge sums the
* same zeros the full grid would have — and every cell outside it is left alone, which is what
* the sweep's threshold did to it anyway. No emitter, no passes at all. The result is the same
* field to the byte (checked on five frames across four worlds); the saving is whatever share
* of the rows carry no light, which is honest about how small it usually is. Measured at
* 400x120: cyber night 4.34 -> 4.36 ms, unchanged, because its signs reach nearly every row;
* west noon 3.86 -> 3.62; Edo dusk 3.86 -> 3.68. What it removes outright is the pathology —
* a frame with nothing lit paying for four filters of nothing. */
if (S && e0 >= 0) {
var Dn = f.D || 1, C3 = C * 3, h1 = Math.floor(2 * Dn), h2 = Math.ceil(2 * Dn), v1 = Math.floor(Dn), v2 = Math.ceil(Dn),
A = 1.2 / ((2 * h1 + 1) * (2 * h2 + 1) * (2 * v1 + 1) * (2 * v2 + 1)), pc,
y0 = e0 - v1 - v2 > 0 ? e0 - v1 - v2 : 0, y1 = e1 + v1 + v2 < R - 1 ? e1 + v1 + v2 : R - 1,
Rb = y1 - y0 + 1, a0 = y0 * C3, a1 = (y1 + 1) * C3,
bs = sp.subarray(a0, a1), bp = tp.subarray(a0, a1), bq = tq.subarray(a0, a1);
hbox(bs, bp, Rb, C, h1); hbox(bp, bq, Rb, C, h2); vbox(bq, bp, Rb, C3, v1); vbox(bp, bq, Rb, C3, v2);
/* Two curves on the pool. A soft ceiling, because a big sign is its own emitter over its
* whole box and the sum inside it climbed to a saturated slab; and the same toe as the mass,
* so a pool's faint skirt dies to black instead of greying the negative space round it. An
* emitter's own cell takes the pool at (1 - its emission): the sign is lit from inside, the
* wall beside it from the sign. The headroom cap again last, over the sum. */
for (i = y0 * C, j = a0; i < (y1 + 1) * C; i++, j += 3) if (tq[j] + tq[j + 1] + tq[j + 2] > 0.02 / A) {
p = PALETTE[fc[i]]; b = Wk[i] && fh[i] ? (EM[fc[i]] ? 1.7 : 1.25) * fl[i] / 255 : 0;
for (k = 0; k < 3; k++) if ((t = tq[j + k] * A) > 0.02) {
pc = p[k]; v = 1 - sp[j + k] / (pc + 1); v *= v * t; v = 72 * v / (v + 72);
v = u[j + k] + v * v / (v + 8) * G; t = 255 - pc * b;
u[j + k] = v < t ? v : t;
}
}
}
return u;
}
var Compose = {
post: function (f, cam, t) {
var D = CC && CC.Daylight;
/* No fresh snapshot for THIS frame means the caller skipped world(f). Take it here, BEFORE
* tone(), so the field is at least computed from an untoned world rather than a twice-toned
* one. It is a degraded field — the elements are in it, lightning included — and it is
* recorded as such: CONTRACT's render order is the thing to follow. */
if (Compose.UNDER && !(W0 && W0.f === f)) world(f);
setDayMix(D ? D.P.sky : 0, D ? D.P.sun : 0);
tone(f);
}
/* Switched off mid-run, the field it last wrote is cleared once rather than left to haunt
* the glass under a frame that no longer asked for it. */
if (Compose.UNDER) under(f, cam), W0.f = null;
else if (f.uon) f.under.fill(0);
f.uon = !!Compose.UNDER;
},
world: world,
UNDER: 1
};
/* HOW WIDE THE PAVEMENT IS, in metres from the building face to the kerb face, and it lives here

View file

@ -174,9 +174,9 @@
for (var s = 0; s < SHAFTS; s++) {
var tgt = s < found ? clamp((this.pkS[s] - 150) / 420, 0, 1) : 0;
if (s < found) {
var dxs = this.pkX[s] - this.sx[s];
var dxs = this.pkX[s] - this.sx[s], jmp = 14 * (this.D || 1);
// A jump of more than a few columns is a different source, not the same one moving.
if (this.ss[s] < 0.06 || dxs > 14 || dxs < -14) {
if (this.ss[s] < 0.06 || dxs > jmp || dxs < -jmp) {
this.sx[s] = this.pkX[s]; this.sy[s] = this.pkY[s];
} else {
this.sx[s] += dxs * eP;
@ -211,6 +211,7 @@
var score = this.score, srcY = this.srcY, srcC = this.srcC, hits = this.hits;
for (x = 0; x < cols; x++) { score[x] = 0; srcY[x] = -1; srcC[x] = 0; hits[x] = 0; }
var D = f.D || 1, iD = 1 / D, w2 = Math.round(2 * D), w9 = Math.round(9 * D);
var yEnd = (hz + rows * 0.12) | 0;
if (yEnd > rows - 1) yEnd = rows - 1;
for (y = 0; y <= yEnd; y++) {
@ -220,7 +221,7 @@
if (l < 150) continue;
var c = f.col[i];
if (!this.isSource(c)) continue;
score[x] += l - 150;
score[x] += (l - 150) * iD; // a column sum: D rows per reference row
if (hits[x] < 255) hits[x]++;
// The shaft hangs below the source, so the anchor is the LOWEST bright row, not the
// brightest: a beam that starts at the middle of a blade sign reads as a mistake.
@ -233,7 +234,7 @@
var sm = this.smooth;
for (x = 0; x < cols; x++) {
var a = 0, n = 0;
for (i = x - 2; i <= x + 2; i++) if (i >= 0 && i < cols) { a += score[i]; n++; }
for (i = x - w2; i <= x + w2; i++) if (i >= 0 && i < cols) { a += score[i]; n++; }
sm[x] = a / n;
}
@ -245,13 +246,13 @@
// The smoothed peak can land a column or two off the actual glyphs, which would leave the
// anchor row unset. Snap back onto the hottest real column inside the window.
var pick = best, pv = -1;
for (i = best - 2; i <= best + 2; i++)
for (i = best - w2; i <= best + w2; i++)
if (i >= 0 && i < cols && srcY[i] >= 0 && score[i] > pv) { pv = score[i]; pick = i; }
if (srcY[pick] < 0 || hits[pick] < 3) { sm[best] = 0; k--; continue; }
if (srcY[pick] < 0 || hits[pick] < 3 * D) { sm[best] = 0; k--; continue; }
this.pkX[found] = pick; this.pkY[found] = srcY[pick];
this.pkC[found] = srcC[pick]; this.pkS[found] = bv;
found++;
for (i = best - 9; i <= best + 9; i++) if (i >= 0 && i < cols) sm[i] = 0;
for (i = best - w9; i <= best + w9; i++) if (i >= 0 && i < cols) sm[i] = 0;
}
// Sorted by column so slot i keeps tracking the same physical source between frames; an
@ -271,6 +272,7 @@
var cols = f.cols, rows = f.rows;
this.sizeTo(cols);
var hz = cam && cam.horizon !== undefined ? cam.horizon : rows * 0.56;
var D = this.D = f.D || 1;
var found = this.detect(f, hz);
/* Handed to update(), which owns the easing. draw() only ever READS the eased slots. */
this.found = found;
@ -317,7 +319,7 @@
if (str < 0.07) continue;
var x0 = this.sx[s], y0 = this.sy[s], hue = this.sc[s], tilt = this.tilt[s];
var L = (8 + 10 * str) * reach;
var L = (8 + 10 * str) * reach * D;
// Rain drifting through the beam. Frozen to a constant under reduced motion — a shaft
// that pulses is the single most distracting thing this file can do.
var moving = !CC.reducedMotion;
@ -331,11 +333,11 @@
* as fast as it widens dies inside six rows and reads as dust round the lamp; keeping a
* floor under it is what makes the beam reach the ground, which is the whole point. */
var along = 0.30 + 0.70 * fall;
var hw = (0.62 + k * 0.22) * spread;
var hw = (0.62 * D + k * 0.22) * spread;
var cxr = x0 + k * tilt;
// Minus t, not plus: the sampling point has to travel DOWN the beam for the thickenings
// to read as rain falling through it rather than as smoke rising out of the street.
var breathe = moving ? 0.70 + 0.44 * vnoise(k * 0.42 - t * 1.7 + s * 13.7, this.seed)
var breathe = moving ? 0.70 + 0.44 * vnoise(k / D * 0.42 - t * 1.7 + s * 13.7, this.seed)
: 0.90;
var xa = Math.ceil(cxr - hw), xb = Math.floor(cxr + hw);
for (x = xa; x <= xb; x++) {
@ -432,9 +434,9 @@
for (var s = 0; s < WASH; s++) {
var tgt = s < found ? clamp((this.pkS[s] - W_ON) / (W_FULL - W_ON), 0, 1) : 0;
if (s < found) {
var dxs = this.pkX[s] - this.sx[s];
var dxs = this.pkX[s] - this.sx[s], WD = this.D || 1;
// Beyond a slot's tracking window this is a different lamp, not the same one moving.
if (this.ss[s] < 0.05 || dxs > 20 || dxs < -20) {
if (this.ss[s] < 0.05 || dxs > 20 * WD || dxs < -20 * WD) {
this.sx[s] = this.pkX[s]; this.sy[s] = this.pkY[s]; this.lead[s] = 0;
} else {
this.sx[s] += dxs * eP;
@ -443,7 +445,7 @@
* gets a symmetric pool; something crossing the frame gets a wedge that runs ahead
* of it, which is what makes a pass read as a sweep rather than as a lamp with a
* glow stuck to it. */
this.lead[s] += (clamp(dxs * 1.7, -10, 10) - this.lead[s]) * eP;
this.lead[s] += (clamp(dxs * 1.7, -10 * WD, 10 * WD) - this.lead[s]) * eP;
}
this.sc[s] = this.pkC[s]; this.sd[s] = this.pkD[s];
}
@ -451,12 +453,16 @@
}
},
sizeTo: function (cols, rows) {
if (this.cols === cols && this.rows === rows) return;
this.cols = cols; this.rows = rows;
sizeTo: function (cols, rows, D) {
if (this.cols === cols && this.rows === rows && this.D === D) return;
this.cols = cols; this.rows = rows; this.D = D;
/* Tile in REFERENCE cells: 6x3 at 200 columns, 6D x 3D on a denser grid, so a tile is the
* same patch of screen and a lamp's energy lands in the same number of tiles. */
this.tX = Math.max(6, Math.round(6 * D)); this.tY = Math.max(3, Math.round(3 * D));
this.iA = 1 / (D * D);
// Resize-time allocation only; a tile is 6x3 cells, which is about the size of a car at
// fifteen metres and small enough that one shopfront does not swallow the whole frame.
this.tw = Math.ceil(cols / 6); this.th = Math.ceil(rows / 3);
this.tw = Math.ceil(cols / this.tX); this.th = Math.ceil(rows / this.tY);
var n = this.tw * this.th;
this.te = new Float32Array(n); this.tx = new Float32Array(n); this.ty = new Float32Array(n);
this.tc = new Uint8Array(n); this.tl = new Uint8Array(n); this.td = new Float32Array(n);
@ -465,11 +471,11 @@
detect: function (f) {
var cols = f.cols, rows = f.rows, tw = this.tw;
var te = this.te, tx = this.tx, ty = this.ty, tc = this.tc, tl = this.tl, td = this.td;
var n = tw * this.th, i, x, y;
var n = tw * this.th, i, x, y, tX = this.tX, tY = this.tY, iA = this.iA;
for (i = 0; i < n; i++) { te[i] = 0; tx[i] = 0; ty[i] = 0; tc[i] = 0; tl[i] = 0; td[i] = 0; }
for (y = 0; y < rows; y++) {
var ry = ((y / 3) | 0) * tw;
var ry = ((y / tY) | 0) * tw;
for (x = 0; x < cols; x++) {
i = y * cols + x;
var l = f.lum[i];
@ -484,8 +490,8 @@
* close. Linear weighting handed the whole frame to the parade of shopfronts at
* fifteen metres, which is exactly the thing that is NOT a passing light. */
var w = 1 - dd / W_NEAR; w *= w;
var e = (l - 150) * w;
var ti = ry + ((x / 6) | 0);
var e = (l - 150) * w * iA; // energy per REFERENCE cell, so W_ON/W_FULL hold
var ti = ry + ((x / tX) | 0);
te[ti] += e; tx[ti] += x * e; ty[ti] += y * e;
if (l > tl[ti]) { tl[ti] = l; tc[ti] = c; td[ti] = dd; }
}
@ -526,8 +532,8 @@
},
draw: function (f, cam, t) {
var cols = f.cols, rows = f.rows;
this.sizeTo(cols, rows);
var cols = f.cols, rows = f.rows, D = f.D || 1;
this.sizeTo(cols, rows, D);
var found = this.detect(f);
this.found = found;
@ -567,7 +573,7 @@
var cx = this.sx[s], cy = this.sy[s], srcD = this.sd[s], hue = this.sc[s];
// Under reduced motion the wedge stops leaning about; the pool stays, the sweep does not.
var lead = CC.reducedMotion ? this.lead[s] * 0.25 : this.lead[s];
var rx = (8 + 10 * str) * reach, ry = (2.4 + 2.6 * str) * reach;
var rx = (8 + 10 * str) * reach * D, ry = (2.4 + 2.6 * str) * reach * D;
var amp = amp0 * str;
var skew = 1 + (lead < 0 ? -lead : lead) / rx * 1.6;
var ya = Math.ceil(cy - ry), yb = Math.floor(cy + ry);
@ -922,7 +928,7 @@
* Twenty is enough for the frame to read as being seen THROUGH something and still small enough
* that the streaks stay countable.
* ===================================================================================== */
var BSRC = 20;
var BSRC = 20, BSRC_MAX = 60;
var lensbloom = {
name: 'lensbloom',
@ -930,8 +936,8 @@
init: function (city, rng) {
this.seed = (rng() * 30011) | 0;
this.bx = new Int32Array(BSRC); this.by = new Int32Array(BSRC);
this.bl = new Int32Array(BSRC); this.bc = new Uint8Array(BSRC);
this.bx = new Int32Array(BSRC_MAX); this.by = new Int32Array(BSRC_MAX);
this.bl = new Int32Array(BSRC_MAX); this.bc = new Uint8Array(BSRC_MAX);
this.n = 0;
// Pan tracking. The smear DIRECTION is the camera's own turn rate and stays that way even
// now that weather.js exports CC.Wind: a streak across a lens is drawn by the lens moving,
@ -965,8 +971,14 @@
/* The streak's length. Wind is in it because wind is what puts the water ON the glass that
* the flare smears through; the pan supplies the direction and a little more length. */
var pan = CC.reducedMotion ? this.pan * 0.3 : this.pan;
var reach = 2.2 + 1.5 * haze + 1.2 * windy * (0.4 + 0.6 * (pan < 0 ? -pan : pan));
var D = f.D || 1;
var reach = (2.2 + 1.5 * haze + 1.2 * windy * (0.4 + 0.6 * (pan < 0 ? -pan : pan))) * D;
var TH = 175;
/* A denser grid resolves more of the same lamps as separate peaks, so the budget grows with
* it — but by sqrt(D), not by the area D^2. Area was tried: the lamps did not multiply, their
* cores just split into neighbouring peaks, and the halo census came out 2.9x the 200-col
* frame. sqrt(D) lands it inside 0.7-1.6 of the reference. */
var NB = Math.min(BSRC_MAX, Math.round(BSRC * Math.sqrt(D)));
// ---- pick the sources: local peaks only, brightest first, at most BSRC of them.
var n = 0, bl = this.bl, bx = this.bx, by = this.by, bc = this.bc;
@ -982,12 +994,12 @@
* equal cells so exactly one of them wins. */
if (f.lum[i - 1] > l || f.lum[i + 1] >= l) continue;
if (f.lum[i - cols] > l || f.lum[i + cols] >= l) continue;
if (n < BSRC) {
if (n < NB) {
k = n++;
} else {
// Full: replace the weakest, and only if this one beats it.
var worst = 0;
for (k = 1; k < BSRC; k++) if (bl[k] < bl[worst]) worst = k;
for (k = 1; k < NB; k++) if (bl[k] < bl[worst]) worst = k;
if (bl[worst] >= l) continue;
k = worst;
}
@ -1002,10 +1014,28 @@
// ---- halo: gain on the ring around the source. Orthogonal neighbours get the full
// scatter, diagonals about half, which is what keeps the halo round rather than square.
var g1 = 1 + halo * s, g2 = 1 + halo * s * 0.45;
if (D <= 1) {
gain(f, sx - 1, sy, g1); gain(f, sx + 1, sy, g1);
gain(f, sx, sy - 1, g1); gain(f, sx, sy + 1, g1);
gain(f, sx - 1, sy - 1, g2); gain(f, sx + 1, sy - 1, g2);
gain(f, sx - 1, sy + 1, g2); gain(f, sx + 1, sy + 1, g2);
} else {
/* The same ring, measured in reference cells: an ANNULUS 0.6-1.5 out, g1 falling to
* g2 at the diagonals' distance. The hole matters. Filling it from the centre gained
* the lamp's own core, which at 2x density is several cells of the source and not the
* glass round it, and the halo came out 1.6-1.75x its 200-col self; with the hole it
* is 0.74-1.58x over eight seeds and worlds. A 0.75 hole cut the diagonals as well and
* sank west dusk to 0.66x. */
var hr = Math.ceil(1.5 * D), oy2, ox2;
for (oy2 = -hr; oy2 <= hr; oy2++)
for (ox2 = -hr; ox2 <= hr; ox2++) {
var rr = Math.sqrt(ox2 * ox2 + oy2 * oy2) / D;
if (rr < 0.6 || rr > 1.5) continue;
var gg = rr <= 1 ? g1 : g1 + (g2 - g1) * (rr - 1) / 0.42;
var sx2 = sx + ox2, sy2 = sy + oy2;
if (sx2 >= 0 && sy2 >= 0 && sx2 < cols && sy2 < rows) gain(f, sx2, sy2, gg);
}
}
// ---- streak: horizontal only, and longer on the side the world is sliding towards.
for (var side = -1; side <= 1; side += 2) {
@ -1024,7 +1054,7 @@
if (f.ch[i] !== 0 && f.lum[i] > lum) continue;
var d = nearer(f.dist[i]);
if (d < 0) continue;
put(f, x, sy, j < 2 ? G_DASH : G_TICK, hue, lum, d, 3);
put(f, x, sy, j < 2 * D ? G_DASH : G_TICK, hue, lum, d, 3);
}
}
}

View file

@ -745,9 +745,11 @@
var rad = 0.22 + age * 0.30;
var rv = rad * vScale / pjW;
var kv = rv < 0.75 ? 0 : 1;
/* The caps are 1 and 2 REFERENCE cells; on a denser grid the puff keeps its world size. */
var DD = frame.D || 1;
var kv = rv < 0.75 ? 0 : Math.min(Math.round(rv), Math.max(1, Math.round(DD)));
var rh = rv / vCellA;
var kh = rh < 0.75 ? 0 : (rh < 1.9 ? 1 : 2);
var kh = rh < 0.75 ? 0 : (rh < 1.9 ? 1 : Math.min(Math.max(2, Math.round(rh)), Math.max(2, Math.round(2 * DD))));
var cx = Math.floor(pjX), cy = Math.floor(pjY), d = pjD;
for (var dy = -kv; dy <= kv; dy++) {

View file

@ -862,9 +862,20 @@
* it is a horizontal mass with a bright top edge, which is what a wagon bed is, and the cap
* rail still reads as the edge because it is nearly twice as bright as the board under it.
*
* The underside stays a cut-out. There is nothing under a wagon but shadow and the road. */
* The underside stays a cut-out. There is nothing under a wagon but shadow and the road.
*
* TWENTY-SIX SAMPLES WERE A GRID SIZE, NOT A WAGON SIZE, and they are scaled by frame.D now.
* Each sample is one column() of board and one of underside, so a bed that spans more columns
* than it has samples prints as a comb — and the teeth sit at a sub-cell phase that moves as
* the wagon translates, the same aliasing beat the wheel's header describes, landing on every
* cell the bed crosses. At 200 columns a wagon at 25 m spans fewer columns than 27 and none of
* that showed; at 400 it spans ~35, and lum-mode west-flicker's worst cell (seed 3, 400x120)
* read 91, 91, 0, 0, 0, 0 on a ~9 Hz loop for two seconds — a lit plant at 31 m seen through
* the holes — which was the whole of the frontier's 10.75 big steps a second against the 8.0
* backstop, and was there in the untouched tree too. 26 x D keeps the samples per reference
* column what they were: identical at 200 columns (D = 1), 4.25/s at 400 on this change alone. */
var deck = 1.02, capY = 1.48;
var n = 26, i;
var n = Math.round(26 * (f.D || 1)), i;
for (i = 0; i <= n; i++) {
var aa = rear + (front - rear) * (i / n);
column(f, wx(axis, aa, cross), wz(axis, aa, cross), deck, capY - 0.06,
@ -947,7 +958,12 @@
B.head = 0; // a horse in draught carries its head up
B.tail = 0;
B.lift = 0; // the wagon's own motion is animation enough
B.legW = objVisible(axis, teamA, cross + lat2, 0.5) < 18 ? 1 : 0;
/* Two-cell legs out to 18 m — 18 REFERENCE metres, so x D. The threshold was fitted at 200
* columns, where it means "legs at least as wide as a cell"; at 400 a leg at 25 m was one
* cell wide again and the near and far leg of a pair, a column apart, crossed a lit road
* cell as two dark pulses instead of one — the residual 3-20 Hz on the same probe after the
* bed fix above (3.93% -> 3.07% against the city's 2.97 x 1.15). */
B.legW = objVisible(axis, teamA, cross + lat2, 0.5) < 18 * (f.D || 1) ? 1 : 0;
hideLight();
beast(f);
}

View file

@ -13,13 +13,13 @@
var STEP = 1 / 60; // simulation tick; elements were written against 60 Hz
var ASPECT = 0.5625; // 9x16 character cell, the proportion surfaces.js was tuned on
var MAXC = 260, MINC = 48, MINR = 22;
var MAXC = 360, MINC = 48, MINR = 22;
var canvas = null, frame = null, city = null, seed = 0;
var cam = { x: 0, z: 0, yaw: 0, eyeY: 1.7, fov: 1.25, horizon: 0, t: 0, cellAspect: ASPECT };
var els = [], cols = 0, rows = 0;
var simT = 0, acc = 0, last = 0, running = false;
var zoom = 1; // adaptive column pressure; 1 = full detail
var zoom = 1; // adaptive column pressure; 1 = full detail (see adapt)
/* ---- seed ----------------------------------------------------------------------------------
* A city is a pure function of its seed, so the fragment IS the artwork's address. Anything that
@ -80,12 +80,21 @@
}
/* ---- viewport ------------------------------------------------------------------------------
* Showing LESS city on a small screen is the correct answer; shrinking the cell until the glyphs
* turn to grey mush is not, because the glyph shapes ARE the texture. So the cell width is
* pinned to a legible band and the column count falls out of it, rather than the other way
* round. 1920px lands near 200 columns, a phone near 60. */
* The band used to be pinned wide (6.4-9.6 CSS px) on the argument that a smaller cell only
* shrinks the ink: a glyph covers about a fifth of its cell, so halving the cell halved the light
* and 400 columns read as grey mush. That argument died with the underpainting. Every cell now
* carries its own colour behind the glyph (core.js, Compose.post), so a smaller cell is more
* PICTURE rather than less ink, and the optics are sized in reference cells (frame.D) so a halo
* does not shrink to a quarter of its area when the grid doubles. What is left of the old rule is
* the floor: under 5 px a glyph stops being a shape, and the shapes are still the texture.
*
* Integer device-pixel cells make the column counts lumpier than the band suggests: 6.4 rounds to
* 6 at dpr 1, so 1920 lands on 320 columns, the ladder's 1.25 and 1.5 steps on 240 and 192, and a
* 390 px phone at dpr 2 on 78. MAXC is set at 360 because the node budget was measured at 300x95
* (world + elements + underpainting under 12 ms) and an ultrawide must not buy a grid nobody
* costed; past it the cell grows instead, which at 2560 dpr 1 means 8 px and 320 columns. */
function cellCSS(vw) {
var w = vw < 560 ? 6.4 : vw < 1000 ? 7.6 : vw < 1700 ? 8.8 : 9.6;
var w = vw < 560 ? 5.0 : vw < 1000 ? 5.6 : 6.4;
return w * zoom;
}
@ -115,6 +124,7 @@
var r = Math.max(MINR, Math.ceil(vh * dpr / dh));
cols = c; rows = r;
calm = nowMs() + 1000; // see adapt: a relayout's own cost is not the frame's
CC.Canvas.setGrid(cols, rows, dw, dh, dpr);
frame = CC.makeFrame(cols, rows);
/* horizonBase is the neutral row; cam.horizon is owned by CC.Control from here on, because
@ -215,35 +225,72 @@
cam.t = t;
CC.clearFrame(frame);
if (CC.Cast) CC.Cast.render(frame, cam, city);
if (CC.Compose && CC.Compose.world) CC.Compose.world(frame);
for (var i = 0; i < els.length; i++) if (els[i].draw) els[i].draw(frame, cam, t);
if (CC.Compose && CC.Compose.post) CC.Compose.post(frame, cam, t);
CC.Canvas.draw(frame);
}
/* ---- adaptive quality ----------------------------------------------------------------------
* Degradation is deliberately reluctant and strictly ordered: bloom first, because a single tap
* still reads as light, and only then columns, because fewer columns means literally less city.
* Recovery needs six sustained good seconds so a one-off GC pause cannot make the frame breathe
* in and out of detail while someone is watching it. */
var ema = 16, badSince = 0, goodSince = 0;
* Degradation is deliberately reluctant and strictly ordered, and the order turned round when the
* cell shrank. Bloom used to go first because it was the fill-rate cost; it is now sized in screen
* pixels and blurred off a downsampled scene, so it costs the same at 200 columns as at 360, while
* the world pass, the elements and the underpainting all scale with the cell count and the glyph
* pass does not scale at all (the pixel path). So columns go first, in two rungs — zoom 1.25 and
* 1.5, which at 1920 is 320 -> 240 -> 192 — because a coarser grid is still the same picture and
* a missing glow is a different one. Bloom drops to one tap only once the grid is as coarse as the
* band allows. Recovery climbs back the same ladder in reverse, one rung per six sustained good
* seconds, so a one-off GC pause cannot make the frame breathe in and out of detail.
*
* The six seconds are not enough on their own. A machine that holds 240 columns at 10 ms and
* drops 320 at 27 would otherwise climb, fall and climb again every seven seconds forever, which
* is exactly the breathing the wait was meant to stop. So a rung that is lost again within twelve
* seconds of being regained doubles the wait for the next climb, up to most of a minute. THAT
* rung and no other: upLv is the level the climb landed on, and only a loss FROM it is a relapse.
* Keyed on the clock alone, every rung a heavy burst took after one good climb doubled it again —
* measured on the ladder lifted out verbatim, a climb at 9.4 s, the regained rung lost at 12.4 s
* (6 -> 12 s, right) and then the bloom rung, never regained, lost at 13.6 s (12 -> 24 s, wrong):
* one burst cost a quarter of a minute of waiting it had not earned. And a
* rung that was held a full minute before it was lost resets the wait to six seconds, because a
* doubling earned by a tab switch or a GC storm at boot is not evidence about the machine an
* hour later, and without the reset every recovery for the rest of the page's life waited 48 s.
*
* And the first second after any layout is not evidence. A relayout rebuilds the atlas, the
* frame and every bloom buffer, and at boot the JIT has not warmed yet: Chromium measured 30-40 ms
* ticks in that second on worlds that then settled at 21-25 ms at 320 columns, and the ladder,
* charged for them, had given away a third of the grid before the page had properly started. */
var ZOOM = [1, 1.25, 1.5, 1.5];
var ema = 16, badSince = 0, goodSince = 0, lv = 0, upAt = -1e9, upLv = -1, hold = 6000, calm = 0;
/* A rung that moves no columns is skipped, not served. Past MAXC the cell is already widened to
* fit, so at 2560 dpr 1 zoom 1 and zoom 1.25 both land on 8 px and 320 columns: the first rung
* there was measured in Chromium spending 1.2 s of bad frames to change nothing. (Climbing back,
* the same no-op is the last rung, 1.25 -> 1; it costs one idle six-second wait and no detail,
* and testing for it would mean a trial relayout, which rebuilds the atlas.) */
function rung(d) {
lv += d;
if (lv > 2) CC.Canvas.setQuality(1);
else {
if (lv === 2 && d < 0) CC.Canvas.setQuality(2);
var c0 = cols;
if (ZOOM[lv] !== zoom) { zoom = ZOOM[lv]; layout(); }
if (cols === c0 && lv === 1 && d > 0) rung(d);
}
}
function adapt(ms, now) {
if (now < calm) { badSince = goodSince = 0; return; }
ema += (ms - ema) * 0.08;
if (ema > 26) {
goodSince = 0;
if (!badSince) badSince = now;
else if (now - badSince > 1200) {
else if (now - badSince > 1200 && lv < 3) {
badSince = now;
if (CC.Canvas.quality > 1) CC.Canvas.setQuality(1);
else if (zoom < 1.3) { zoom = 1.3; layout(); }
hold = now - upAt < 12000 && lv === upLv ? Math.min(hold * 2, 48000) : now - upAt > 60000 ? 6000 : hold;
rung(1);
}
} else if (ema < 11) {
badSince = 0;
if (!goodSince) goodSince = now;
else if (now - goodSince > 6000) {
goodSince = now;
if (zoom > 1) { zoom = 1; layout(); }
else if (CC.Canvas.quality < 2) CC.Canvas.setQuality(2);
}
else if (now - goodSince > hold && lv > 0) { goodSince = upAt = now; rung(-1); upLv = lv; }
} else { badSince = 0; goodSince = 0; }
}
@ -327,6 +374,10 @@
mq.addEventListener('change', function (e) { CC.reducedMotion = !!e.matches; });
CC.Canvas.init(canvas);
/* 'auto', not on: the pixel-write glyph pass (render_canvas.js) only pays at cells of 7 device
* px or less, where drawImage per glyph is what made more columns cost more frames. Above that
* the atlas blit is as fast and the canvas's own antialiasing is the better print. */
if (CC.Canvas.setPixelPath) CC.Canvas.setPixelPath('auto');
layout();
/* World first, seed second, and in that order because city.js resolves CC.World inside make():

View file

@ -26,6 +26,21 @@
* geometric step was tried first and was both SLOWER at 400x100 (5.7 ms vs 4.0) and lossy: it
* strides over one-cell slivers of frontage and drops them out of the skyline. */
var MAXSTEP = 512;
/* DETAIL SCALE. Every painter's LOD ladder is keyed on world distance (13/34 m, 18/44 m...), which
* is only a proxy for how many metres one CELL covers — and it was tuned at 200 columns. At 400
* columns a cell covers half the wall, yet the painter still drops to its coarse tier at the same
* metres, so the extra columns re-print coarse glyphs twice instead of resolving panes. The
* painters are handed an APPARENT distance, dist * SREF/scale, so their tiers follow the cell's
* footprint; fog and frame.dist keep the true distance. SREF is scale at 200 cols, fov 1.25,
* 9x16 cell — the grid every ladder was signed off on — so a 200-col frame is byte-identical AT
* FOV 1.25, and only there. scale carries the fov, so the viewer's wheel zoom (control.js, fovT
* 1.02..1.52) moves it too: zoomed IN, a 200-column frame resolves finer tiers, because a zoomed
* cell really does cover less wall — that is the same rule, not a leak, and it is kept. Zoomed
* out it cannot coarsen past today's tiers (dK is capped at 1). The gates cannot see the zoomed
* case: every probe and fixture pins fov at 1.25. The finest tier a zoom reaches at 200 columns is
* the tier 250 columns gets unzoomed, which the 400x120 gate pass already covers. */
var SREF = 200 * 0.5625 / (2 * Math.tan(0.625));
var dK = 1;
/* ---- the record handed to CC.Surf.facade --------------------------------------------------
* city.js stores `seed` as a 0..1 float and surfaces coerces it with `|0`, which would collapse
@ -246,7 +261,7 @@
if (den < 1e-3) { poke(frame, i, 0, P.shadow, 0, 1e6, 2); mirA[r] = 0; return; }
var w = eyeY * scale / den, d = w * len;
var px = ox + dx * w, pz = oz + dz * w;
var o = swapFloor ? Surf.floorTex(pz, px, d, t) : Surf.floorTex(px, pz, d, t);
var o = swapFloor ? Surf.floorTex(pz, px, d * dK, t) : Surf.floorTex(px, pz, d * dK, t);
poke(frame, i, o.ch, o.col, Surf.fog(o.lum, d), d, 2);
/* Parked for the reflect pass at the end of the column. It cannot run here: the wall this
* cell is going to mirror has not been painted yet. */
@ -377,6 +392,20 @@
* escape hatch for a caller that really does want a different vertical zoom. */
var cellA = cam.cellAspect || 0.5625; // 9x16 cell, as tools/topng.py draws
var scale = cam.scaleY !== undefined ? cam.scaleY : (cols * cellA) / (2 * halfPlane);
/* An AIRLESS painter is handed the true distance. The moon's dist is not an LOD key: its lit
* ramp (+0.62 lum/m to the 125 m cliff) cancels the print's depth bucket, which reads the TRUE
* frame.dist, so an apparent distance there prints a rock at 200 m with the 100 m ramp in the
* brightest bucket — a bright band. Its dither lattice is already solved against screen columns
* at 400 (see qOf), so it needs no help from here either. The flag is the painter's own; the
* engine does not name the world. */
var Wp = CC.SURFACES && CC.World ? CC.SURFACES[CC.World.id] : null;
dK = (CC.DETAIL_SCALE === 0 || (Wp && Wp.airless)) ? 1 : Math.min(1, SREF / scale);
/* frame.D: cells per reference cell (200 cols x 9:16), >= 1. Published on the frame because
* every element draws into the frame after this pass and has no camera-independent way to
* know the grid's density otherwise. 1.0 on every grid up to the reference, so those frames
* do not move. */
var Dd = (cols * cellA) / (200 * 0.5625);
frame.D = (CC.DETAIL_SCALE === 0 || !(Dd > 1)) ? 1 : Dd;
var t = cam.t || 0;
var ox = cam.x, oz = cam.z, yaw = cam.yaw || 0;
@ -465,7 +494,7 @@
}
mirA[r] = 0; // wall, not water: nothing here reflects anything
var v = eyeY + (horizon - rowC) * w / scale;
var o = Surf.facade(u, v, sc, dist, t);
var o = Surf.facade(u, v, sc, dist * dK, t);
var ch = o.ch, cl = o.col, lm = o.lum, sg;
if (sign && (sg = signPixel(rec, u, v, faceX, t))) { ch = sg.ch; cl = sg.col; lm = sg.lum; }
poke(frame, i, ch, cl, Surf.fog(lm, dist), dist, 1);

View file

@ -1,14 +1,25 @@
/* CyberCity canvas renderer — glyph atlas, one drawImage per lit cell, then bloom.
/* CyberCity canvas renderer — underpainting, glyph atlas (or direct pixel writes), then bloom.
*
* This is the ONLY module that touches the DOM or a 2D context. Everything above it produced a
* frame of typed arrays; everything here is about getting those ~13000 cells onto glass at 60 Hz
* and then putting the light back into them.
*
* BLOOM IS NOT DECORATION. The art direction is 55%+ pure black with a thin scatter of very bright
* glyphs; drawn flat, that reads as a text dump. The halo is what makes a sodium lamp look like it
* BLOOM IS NOT DECORATION. The art direction is a glyph layer 55%+ pure black with a thin scatter
* of very bright glyphs (the night composite, underpainting included, holds 35%+); drawn flat, that
* reads as a text dump. The halo is what makes a sodium lamp look like it
* is emitting rather than printed, and it is the only thing that fuses the dim mullion glyphs into
* the massed slab a facade is supposed to be. The offline reference renderer (tools/topng.py) bakes
* the same two-radius glow, so this pass exists to keep the browser honest against it.
*
* THREE LAYERS, ADDED. f.under (CC.Compose's per-cell tone field) goes down first, one flat block
* per cell; the glyph scene is added over it; the bloom is added over that and reads the SCENE
* ONLY. The order is the art direction: a glyph inks ~21% of its cell, so the light a painter
* means for a lit wall never reached the glass until something sat behind the ink — but a halo
* fed by the underpainting would lift every black between lit cells to grey, and the negative
* space is what the whole composition is built on. No f.under, or an all-zero one, prints the
* glyph composite with the underlay op skipped altogether — the same frame, op for op, minus one
* drawImage. It is not the pre-HD print: the pixel path and the reference-cell bloom radii below are
* independent of the field and stay on.
*/
(function (CC) {
'use strict';
@ -36,6 +47,10 @@
var scene = null, sctx = null; // glyph pass lands here, bloom reads it
var b2 = null, b4 = null, b8 = null; // 1/2, 1/4, 1/8 downsample chain
var atlas = null, actx = null;
/* The underpainting buffer: ONE PIXEL PER CELL, scaled up unsmoothed so it stays on the
* character grid. A bilinear upscale was tried in the colour prototype and smeared the street
* into a violet haze; the grid is what keeps it reading as characters rather than a photo. */
var ubuf = null, uctx = null, uimg = null, underOn = false;
var cols = 0, rows = 0, dw = 0, dh = 0, W = 0, H = 0, dpr = 1;
var quality = 2;
@ -43,7 +58,7 @@
* a fixed 1.2px halo is half a glyph wide at dpr 1 and a quarter of one at dpr 2, so the piece
* would look softer on a cheap monitor than on a retina one. Expressed as a fraction of the cell
* they hold the same look at every density and every column count. */
var rTight = 1, rWide = 1, rMid = 1;
var rTight = 1, rWide = 1, rMid = 1, rD = 0;
var advance = 0.6; // measured monospace advance, em units
/* ctx.filter is absent on older WebKit. Probed once: assigning an unsupported value leaves the
@ -125,16 +140,29 @@
b2 = mkCanvas(W >> 1, H >> 1);
b4 = mkCanvas(W >> 2, H >> 2);
b8 = mkCanvas(W >> 3, H >> 3);
ubuf = mkCanvas(cols, rows); uctx = ubuf.getContext('2d');
try { uimg = uctx.createImageData(cols, rows); } catch (e) { uimg = null; } // shim: no underlay
radii(1);
if (reAtlas || !atlas) buildAtlas();
pxImg = pxBuf = gOff = null; // rebuilt lazily, and only if the pixel path engages
}
/* Each radius is expressed in ITS OWN buffer's pixels, so the 0.05/0.045 fractions below are
* the cell-relative full-resolution radii divided by the buffer's downsample factor. Landed on
* by matching tools/topng.py's 1.5px and 5.0px taps at its 9x16 cell, which is the render the
* art direction was signed off against. */
rTight = Math.max(0.6, dh * 0.05); // on b2 (1/2)
rWide = Math.max(0.8, dh * 0.045); // on b8 (1/8)
rMid = Math.max(0.7, dh * 0.06); // on b4 (1/4), degraded mode only
if (reAtlas || !atlas) buildAtlas();
* art direction was signed off against.
*
* They are fractions of the REFERENCE cell, dh*D, not of the cell on glass. D is raycast's
* frame.D (cells per 200-column reference cell, 1 at or below it). Sized off the bare cell, a
* 360-column grid on 5x9 cells glows at a quarter of the area of the same street at 200x60 —
* the halo shrinks with the ink and the extra columns read as a darker, noisier picture rather
* than a finer one. At D=1 this is the old formula to the bit, floors included. */
function radii(D) {
var h = dh * D; rD = D;
rTight = Math.max(0.6, h * 0.05); // on b2 (1/2)
rWide = Math.max(0.8, h * 0.045); // on b8 (1/8)
rMid = Math.max(0.7, h * 0.06); // on b4 (1/4), degraded mode only
}
function init(el) {
@ -175,6 +203,102 @@
c.globalAlpha = 1;
}
/* ---- the pixel path ------------------------------------------------------------------------
* On a dense grid the glyph pass stops being a fill problem and becomes a CALL problem: 360x110
* is ~40k cells, each a drawImage with a state check and a blit of a few dozen pixels, and the
* pass grows with the cell count while the pixels on glass stay the same. Below PX_CELL device
* px of cell width it instead writes the scene's pixels straight from per-glyph sparse coverage
* lists (pixel offset + coverage, baked once per grid from the atlas's own alpha), then one
* putImageData. The cost is the screen, not the cells — flat in the column count. Same model as
* the drawImage path: dst = palette * lum/255 * coverage on black, which is exactly what
* source-over at globalAlpha onto black computes, so the two agree to within a level.
*
* INK COMPENSATION. At 5 px a bold stroke is ~0.8 px wide; antialiasing spreads it over two
* pixels at half value, so the cell's PEAK drops ~20% (measured: p99 128 -> 104 on one frame
* printed at 200 and 400 cols) while its mean holds — the picture prints darker and greyer for
* no reason in the data. Coverage is lifted by cov' = 1-(1-cov)^k, k = 1 + INK*(PX_REF-dw)/PX_REF,
* which only engages on small cells: at 9 px and up it is the identity. It lives in the print,
* not the data, so the lum fixtures and the census never see it.
*
* 'auto' is the shipping mode; true/false force it for the harness. Anything that throws while
* baking (a shim with no getImageData, a tainted context) or a big-endian host, where the packed
* 0xAABBGGRR word below lands in the wrong channels, leaves the drawImage path in charge for good. */
var PX_CELL = 7, PX_REF = 9, INK = 1.6;
var pxMode = false, pxDead = new Uint8Array(new Uint32Array([1]).buffer)[0] !== 1, pxLast = false;
var pxImg = null, pxBuf = null, gIdx = null, gCov = null, gOff = null, pal = null;
function pxReady() {
if (gOff) return true;
if (pxDead) return false;
try {
var tw = NG * dw, d = actx.getImageData(0, 0, tw, dh).data; // palette row 0: alpha IS ink
var k = dw >= PX_REF ? 1 : 1 + INK * (PX_REF - dw) / PX_REF;
var I = [], C = [], off = [0];
for (var gI = 0; gI < NG; gI++) {
for (var y = 0; gI && y < dh; y++)
for (var x = 0; x < dw; x++) {
var v = d[(y * tw + gI * dw + x) * 4 + 3] / 255;
if (v < 0.02) continue;
/* 257, not 256: with the +32768 rounding below a full-ink cell at lum 255 lands on
* 255 exactly, as globalAlpha 1 does, instead of a level short. */
I.push(y * W + x); C.push(Math.round((1 - Math.pow(1 - v, k)) * 257));
}
off.push(I.length);
}
pal = new Uint16Array(NP * 3);
for (var q = 0; q < NP; q++) { pal[q * 3] = PALETTE[q][0]; pal[q * 3 + 1] = PALETTE[q][1]; pal[q * 3 + 2] = PALETTE[q][2]; }
pxImg = sctx.createImageData(W, H);
pxBuf = new Uint32Array(pxImg.data.buffer);
gIdx = new Int32Array(I); gCov = new Uint16Array(C); gOff = new Int32Array(off);
return true;
} catch (e) { pxDead = true; gOff = null; return false; }
}
function glyphPassPx(f) {
var b = pxBuf;
b.fill(0xFF000000);
var ch = f.ch, cl = f.col, lu = f.lum, fc = f.cols;
var nc = cols < fc ? cols : fc, nr = rows < f.rows ? rows : f.rows;
for (var y = 0; y < nr; y++) {
var row = y * fc, base0 = y * dh * W;
for (var x = 0; x < nc; x++) {
var ci = row + x, gI = ch[ci];
if (gI === 0) continue;
var L = lu[ci];
if (L < LUM_FLOOR) continue;
/* lum folded into the colour once per cell; coverage is 0..257, so >>16 is /255 */
var c = cl[ci] * 3, r = pal[c] * L, g = pal[c + 1] * L, bl = pal[c + 2] * L;
var base = base0 + x * dw, e = gOff[gI + 1];
for (var j = gOff[gI]; j < e; j++) {
var cv = gCov[j];
b[base + gIdx[j]] = 0xFF000000 | (((bl * cv + 32768) >> 16) << 16) |
(((g * cv + 32768) >> 16) << 8) | ((r * cv + 32768) >> 16);
}
}
}
sctx.putImageData(pxImg, 0, 0);
}
function setPixelPath(on) { pxMode = on === 'auto' ? on : !!on; }
/* ---- the underlay --------------------------------------------------------------------------
* f.under is RGB per cell (cols*rows*3; the craft prototype's RGBA *4 is accepted too, the
* stride is read off the length). Copied into the one-pixel-per-cell buffer every frame, and the
* copy doubles as the all-zero test: a field with nothing in it (CC.Compose.UNDER = 0) is never
* drawn, so the kill switch restores today's composite op for op, not just to within rounding. */
function underlay(f) {
var u = f.under, fc = f.cols, s = u && u.length / (fc * f.rows);
if (!uimg || (s !== 3 && s !== 4)) return false;
var d = uimg.data, any = 0, nc = cols < fc ? cols : fc, nr = rows < f.rows ? rows : f.rows;
for (var y = 0; y < nr; y++)
for (var x = 0, o = y * cols * 4, i = y * fc * s; x < nc; x++, o += 4, i += s) {
any |= (d[o] = u[i]) | (d[o + 1] = u[i + 1]) | (d[o + 2] = u[i + 2]);
d[o + 3] = 255;
}
if (any) uctx.putImageData(uimg, 0, 0);
return !!any;
}
/* ---- bloom ---------------------------------------------------------------------------------
* 'copy' rather than clearRect-then-draw: it replaces the destination in one op, which both
* clears the buffer and writes it, and it is what makes the fallback path free. */
@ -196,6 +320,14 @@
ctx.imageSmoothingQuality = 'high';
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'copy';
if (underOn) {
/* Unsmoothed, so each cell is one flat block and the grid survives; 'copy' clears and
* writes in one op, then the scene ADDS over it — light on light, as everything above. */
ctx.imageSmoothingEnabled = false;
ctx.drawImage(ubuf, 0, 0, W, H);
ctx.imageSmoothingEnabled = true;
ctx.globalCompositeOperation = 'lighter';
}
ctx.drawImage(scene, 0, 0);
if (quality <= 0) { ctx.globalCompositeOperation = 'source-over'; return; }
@ -229,12 +361,17 @@
function draw(f) {
if (!ctx || !atlas) return;
glyphPass(f);
var D = f.D > 1 ? f.D : 1;
if (D !== rD) radii(D);
underOn = !!f.under && underlay(f);
pxLast = (pxMode === 'auto' ? dw <= PX_CELL : pxMode) && pxReady();
if (pxLast) glyphPassPx(f); else glyphPass(f);
composite();
}
CC.Canvas = {
init: init, setGrid: setGrid, setQuality: setQuality, draw: draw,
init: init, setGrid: setGrid, setQuality: setQuality, draw: draw, setPixelPath: setPixelPath,
get pixelPath() { return pxLast; },
get cellAspect() { return dh ? dw / dh : 0.5625; },
get quality() { return quality; },
get hasFilter() { return HAS_FILTER; },

View file

@ -442,8 +442,12 @@
if (dist < 34 && q < 0.34 && bh < (0.20 + 0.24 * wWet) * (0.25 + 0.75 * cv))
return fset(bh < 0.10 ? G_COMMA : G_QUOTE, P.moss, (24 + 130 * sun) * (0.6 + 0.8 * bh));
/* The block face. Thin: a dressed-stone field at any density is the mush this world cannot
* afford, and the joints above are carrying the picture. */
if (bh > 0.62 * cv) return fset(0, P.shadow, 0);
* afford, and the joints above are carrying the picture. The blank is written in the block's
* own swatch and not in `shadow`: it is dressed stone the dither left without a glyph, not a
* hole, and core.js's underpainting reads the swatch on a blank to tell the two apart (see
* BARE at the bottom of this file). The glyph layer cannot see the difference — ch 0 prints
* nothing in any colour. */
if (bh > 0.62 * cv) return fset(0, mid, 0);
return fset(ink(0.16 + 0.40 * sun + 0.22 * bh),
bh < 0.24 ? lit : (bh < 0.46 ? mid : shd),
(18 + 200 * sun) * (0.72 + 0.5 * bh));
@ -611,7 +615,7 @@
return bu < 0.42 ? fset(G_PIPE, shd, 18 + 60 * L)
: fset(G_COLON, mid, 26 + 104 * L);
}
if (ph > 0.62 * cov) return fset(0, P.shadow, 0);
if (ph > 0.62 * cov) return fset(0, mat, 0); // bare plaster, not a hole: see BARE
return fset(ink(0.10 + 0.46 * L), mat, (30 + 186 * L) * gr);
}
@ -623,7 +627,7 @@
var inPanel = fu > (1 - st.panel) * 0.5 && fu < 1 - (1 - st.panel) * 0.5;
if (!inPanel) {
var wh = hash2(Math.floor(u * 4.3), Math.floor(v * 4.3), sd ^ 0x2E1);
if (wh > 0.56 * cov) return fset(0, P.shadow, 0);
if (wh > 0.56 * cov) return fset(0, mat, 0); // bare infill, not a hole: see BARE
return fset(ink(0.12 + 0.42 * L), mat, (26 + 190 * L) * gr);
}
@ -751,9 +755,16 @@
if (sl < (heavy ? 0.52 : 0.34) && (heavy ? cov > 0.06 : cov > 0.34))
return fset(heavy ? G_PIPE : G_COLON, heavy ? shd : mid,
(14 + 176 * L) * (heavy ? 1 : 0.70) * gr);
if (dFill > 0.02 && hash2(Math.floor(u * 6.1), Math.floor(v * 6.1), sd ^ 0x38B) < 0.62 * dFill)
var hf = hash2(Math.floor(u * 6.1), Math.floor(v * 6.1), sd ^ 0x38B);
if (dFill > 0.02 && hf < 0.62 * dFill)
return fset(ink(0.10 + 0.34 * L), SHD[hue], (22 + 120 * L) * gr);
return fset(0, P.shadow, 0);
/* By night the gap is the dark of the room behind the slats and it is a hole. By day the
* panel is the shutter, and the cells its fill left blank are shutter board with no glyph —
* so they go over to the board's swatch (see BARE) on the SAME hash, a little ahead of the
* ink, so a wall changes over cell by cell as the morning fills in and never all at once:
* a whole frontage of gaps lifting from a tenth of the ambient to half of it in one frame is
* an area step, which is the thing the flash gates exist to catch. */
return fset(0, hf < 0.95 * dFill ? SHD[hue] : P.shadow, 0);
}
/* A horizontal rhythm instead: the tile lattice of a namako wall, or the beam courses of a
@ -772,7 +783,7 @@
return fset(G_X, lit, (34 + 190 * L) * gr);
}
var fh = hash2(Math.floor(u * 4.9), Math.floor(v * 4.9), sd ^ 0x6D1);
if (fh > 0.52 * cov) return fset(0, P.shadow, 0);
if (fh > 0.52 * cov) return fset(0, mat, 0); // bare course, not a hole: see BARE
return fset(ink(0.10 + 0.40 * L), mat, (24 + 190 * L) * gr);
}
@ -979,7 +990,7 @@
* rather than earth and because it is the line that separates the town from the water. */
var qj = hash2(Math.floor(rx * 1.3), Math.floor(rz * 1.3), 0x5C7);
if (qj < 0.14) return rset(G_DASH, SHD[P.stone], 14 + 66 * L);
if (qj > 0.66 * cov) return rset(0, P.shadow, 0);
if (qj > 0.66 * cov) return rset(0, gStone, 0); // bare quay stone: see BARE
return rset(ink(0.12 + 0.32 * L), gStone, (26 + 190 * L) * (0.7 + 0.5 * qj));
}
}
@ -1036,10 +1047,10 @@
* world and is therefore where everybody is standing. Stone slabs where there is a building,
* bare earth where there is not. */
if (al > half - 0.2) {
if (lod === 0) return rset(0, P.shadow, 0);
if (lod === 0) return rset(0, gEarth, 0);
var sj = hash2(Math.floor(wz * 1.4), Math.floor(al * 1.6), 0x4E1);
if (sj < 0.16 * cov) return rset(G_DASH, SHD[P.stone], 12 + 60 * L);
if (sj > 0.58 * cov) return rset(0, P.shadow, 0);
if (sj > 0.58 * cov) return rset(0, gEarth, 0);
/* Slab and earth, not all slab. This strip is the largest lit area on the ground after the
* road and putting the whole of it on the wet-stone swatch took `white` to 47% of the frame's
* lit energy — a wet grey town, which is right, printed as a WHITE one, which is not. A third
@ -1096,8 +1107,12 @@
/* Wet earth. Thin, dark, and mostly nothing — this is the largest single area in the frame and
* every cell written into it comes straight off the print's muddy budget. What is drawn is the
* rut lines and the stones the rain has washed clear. */
if (lod === 0) return rset(0, P.shadow, 0);
* rut lines and the stones the rain has washed clear.
*
* EVERY BLANK ON THE GROUND IS BARE GROUND, so every one is written in the ground's swatch and
* none in `shadow` (see BARE): the glyph is what the dither left out, and the earth is still
* there under it. At a far LOD that is the whole road. */
if (lod === 0) return rset(0, gEarth, 0);
if (inRut && rut > 0.30 && cov > 0.10)
return rset(G_UNDER, SHD[P.timber], 14 + 92 * L);
var eh = hash2(Math.floor(wx * 2.6), Math.floor(wz * 2.6), 0x6C3);
@ -1107,7 +1122,7 @@
* straight off the print's muddy budget, so its fill is gated on the light exactly as the
* walls' is. Under the lanterns it is a real surface; twenty metres up an unlit alley it is
* nothing at all, which is what an unlit dirt road is. */
if (eh > 0.44 * cov) return rset(0, P.shadow, 0);
if (eh > 0.44 * cov) return rset(0, gEarth, 0);
return rset(eh < 0.5 ? G_DOT : G_COMMA, gEarth, (14 + 196 * L) * (0.6 + 0.8 * eh));
}
@ -1357,6 +1372,29 @@
Object.defineProperty(CC.SurfJapan, 'dayFill', { get: function () { return dFill; } });
/* Self-registration: surfaces.js never learns this file's name. */
if (!CC.SURFACES) CC.SURFACES = {};
/* Edo's sky for the underpainting (core.js, CC.Compose): night, noon and dusk, each a zenith then
* a horizon. Wetter air than the frontier, so a softer noon and a dusk that is rose-gold at the
* end of the street rather than orange. */
CC.SurfJapan.SKY_RGB = [3,4,12,24,28,50, 100,132,176,196,200,204, 40,46,96,236,150,80];
/* BARE = [wall, floor]: what a blank cell written in a LIT swatch takes of the
* underpainting's ambient, where a blank in `shadow` is a hole at the city's 0.1 (wall) and 0.5
* (floor). This world is the reason the export exists. Its walls and its road thin their glyphs
* by the light (`cov`, cubed) and so most of its blanks are timber, plaster and earth with no
* glyph on them, and core.js, reading every blank as a hole, printed the noon street as night
* tarmac and the facades as black perforation.
*
* 0.8 on a bare wall: the inked cells still lead it, since they take the whole ambient plus a
* mass panel plus the glyph, but after the underpainting's toe a bare cell at 0.5 printed 11
* against an inked cell's 40 and the facade still read as holes; at 0.8 it prints ~20 and reads
* as the same timber in shade. 1.6 on bare ground, over the whole ambient, and that is this
* file's own physics rather than a lift: the ground takes SKY_UP, the whole hemisphere — "an
* overcast street photograph is always brightest at your feet" (floorTex) — where core.js's floor
* ambient was fitted on the city, a canyon whose road is in the shadow of its towers. Measured,
* seed 7, 300x95: noon bottom-40% luma 18.4 -> 30.2 (dusk 25.7, so noon is lighter than dusk
* again), the crowd against the road 1.07:1 -> 1.99:1, wall cells printing pure black 29.6% ->
* 10.3%, what is left being the eaves and the mid-rail, which are `shadow` by name. Seed 11:
* 1.04:1 -> 1.62:1. */
CC.SurfJapan.BARE = [0.8, 1.6];
CC.SURFACES.japan = CC.SurfJapan;
if (typeof module !== 'undefined') module.exports = CC.SurfJapan;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

View file

@ -1463,8 +1463,22 @@
* blue dome and is nowhere near the line — that version put a point of muddy back on.
*
* On the fill, so night and both twilights are the identity: at dFill 0 this is exactly 1 and
* the sunset ladder above is the one being used anyway. */
var dayHz = 1 - 0.20 * dFill;
* the sunset ladder above is the one being used anyway.
*
* 0.65 SINCE THE UNDERPAINTING, and the reason is that the dome is no longer what carries the
* sky's colour. core.js lays the sky table under every sky cell, and at noon in the low band
* that is already ~(110,137,175); the canvas ADDS the glyph's ink to it, so a white '=' at the
* old 0.80 put (154,161,168) on top and burned every stroke to white — the noon dome printed
* as venetian blinds, and 66% of the frame's clipped pixels were these two tiers (seed 7: 3.02%
* of the frame with the underpainting, 0.03% without). Measured over the low centre sky at seed
* 7 noon, 300x95, 6x11: pixels burned WHITE (every channel >= 240) 6.63% -> 1.80%, with the
* band's mean luma 131 -> 124, so the sky is the same brightness and the strokes are pale-blue
* streaks in it rather than white bars on it. Pixels with any one channel at 250+ only go
* 11.2% -> 8.2%: what is left is the BLUE channel of a pale stroke on a blue sky topping out,
* which is not a burn. 0.45 was tried first and left most of the white (5.46%). Capping the
* UNDERPAINTING under the strokes instead was tried and rejected — per channel it turned the
* ice tiers' sky green, and floored it left the few blank cells as bright specks. */
var dayHz = 1 - 0.65 * dFill;
if (e > 0.80) return sset(G_EQ, P.white, dayHz * 214 * (0.80 + 0.24 * e) * (0.88 + 0.18 * hs2));
if (e > 0.62) return sset(G_DASH, P.white, dayHz * 176 * (0.72 + 0.32 * e) * (0.86 + 0.22 * hs2));
if (e > 0.38) return sset(G_TICK, P.ice, 168 * (0.62 + 0.50 * e) * (0.82 + 0.30 * hs2));
@ -1534,6 +1548,13 @@
CC.SurfWest.dayAt = dayAt;
/* Self-registration: surfaces.js never learns this file's name. */
if (!CC.SURFACES) CC.SURFACES = {};
/* The frontier's sky for the underpainting (core.js, CC.Compose): night, noon and dusk, each a
* zenith then a horizon. Desert air is dry and high, so the noon zenith is a deep saturated blue
* and the horizon pales toward dust rather than toward white, and the dusk horizon is the
* hottest in the fleet — a clear sky over sand is the one place a sunset is that orange. The
* noon pair was 80,130,196 / 214,200,170 and is a step down: the horizon under white sky dashes
* and lit cobbles was clipping 4% of the frame to flat white at noon. */
CC.SurfWest.SKY_RGB = [3,4,12,26,28,48, 74,122,186,180,170,148, 48,52,96,232,132,60];
CC.SURFACES.west = CC.SurfWest;
if (typeof module !== 'undefined') module.exports = CC.SurfWest;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

View file

@ -2803,6 +2803,19 @@
resolveWorld: resolveWorld,
configure: configure, cfg: CFG, beginFrame: beginFrame,
FOG_START: FOG_START, FOG_END: FOG_END,
/* The LIVE ramp, as getters: the underpainting's aerial haze has to fade on the distance the air
* actually hides tonight, and that is refog()'s pair, not the constants above it. */
get fogStart() { return fogStart; }, get fogEnd() { return fogEnd; },
/* The city's sky for the underpainting (core.js, CC.Compose): zenith rgb, horizon rgb at NIGHT,
* at NOON, and the DUSK pair the warm term pulls toward. The night zenith is 2,4,12 and that is
* the whole art direction in three numbers — near-black with blue in it, so the slot between the
* towers is still the negative space the frame is built from and the haze lives low, where the
* signs light it. The night horizon is also what far walls haze toward, and at full strength
* an unlit tower deep in the canyon printed as a flat periwinkle panel — so core.js hazes to
* HALF of it by night rather than this table going darker. Darkening it here (24,30,60) was
* tried and failed a gate: every glyph stepping in front of this sky steps harder on a darker
* backdrop, and flicker-rate's still holo band went from 9.3% to 10.3% against its 10% line. */
SKY_RGB: [2,4,12,40,50,96, 60,96,150,150,172,196, 34,40,84,196,110,70],
/* The share of ground-floor units that are open, published because signage.js's shopSpill has
* to re-derive the SAME test to land its pool under a lit window rather than under a shutter —
* it says so in its own comment and then hardcoded the number, so raising the rate here left

View file

@ -1,11 +1,18 @@
/* west-flicker's method, but with the camera PINNED ON THE CANAL — which is the one place the
shipped gate can never look, because it pins at the map's start and the channel is 100+ m away. */
shipped gate can never look, because it pins at the map's start and the channel is 100+ m away.
node tools/canal-flicker.cjs [--composite] [--cols=120] [--rows=40]
--composite scores the light each cell EMITS (tools/composite.cjs) and grows the water mask by the
underpainting's spill box: a ripple that flickers a reflected sign throws its wash on the bank,
and the bank is where that wash lands. Both modes run the WCAG general-flash check, absolute. */
const R=require('path').join(__dirname,'..')+'/',fs=require('fs');
global.CC=require(R+'src/core.js');global.window=undefined;
['world','proj','daylight','weather_state','city','surfaces','raycast','control'].forEach(m=>require(R+'src/'+m+'.js'));
fs.readdirSync(R+'src').sort().forEach(p=>{if(/^surf_.*\.js$/.test(p))require(R+'src/'+p)});
fs.readdirSync(R+'src/elements').sort().forEach(p=>require(R+'src/elements/'+p));
const COLS=120,ROWS=40,WARM=360,NF=WARM+240,PROBES=[3.5,5,7,9,12,15,19];
const CP=require('./composite.cjs')(CC),M=CP.mode(process.argv,120,40);
const COLS=M.cols,ROWS=M.rows,WARM=360,NF=WARM+240,PROBES=[3.5,5,7,9,12,15,19];
function goertzel(x,f){const n=x.length,w=2*Math.PI*f/60,c=2*Math.cos(w);let s1=0,s2=0,m=0;
for(let i=0;i<n;i++)m+=x[i];m/=n;
for(let i=0;i<n;i++){const v=(x[i]-m)*(0.5-0.5*Math.cos(2*Math.PI*i/(n-1)));const s0=v+c*s1-s2;s2=s1;s1=s0;}
@ -28,18 +35,20 @@ function run(preset,seed,reduced,dOff){
them here measured the pedestrians and called it the canal. */
const drawn=live.filter(e=>e.world&&CC.inWorld(e,'japan')&&!CC.inWorld(e,'cyber'));
const f=CC.makeFrame(COLS,ROWS),N=COLS*ROWS,keep=NF-WARM,s=new Uint8Array(N*keep);
const isWater=new Uint8Array(N);
let isWater=new Uint8Array(N);const V=new Float32Array(N),Y=new Float32Array(N),fl=CP.Flash(COLS,ROWS);
for(let k=0;k<NF;k++){const t=k/60;
if(!CC.Weather.P.forced)CC.Weather.set(preset,t);
CC.Weather.update(1/60,t);
for(const el of live) if(el.update) el.update(1/60,t,cam);
cam.t=t;CC.clearFrame(f);CC.Cast.render(f,cam,city);
if(M.comp)CC.Compose.world(f); // the underpainting's world snapshot, where main.js takes it
for(const el of drawn) if(el.draw) el.draw(f,cam,t);
if(CC.Compose&&CC.Compose.post)CC.Compose.post(f,cam,t);
if(k>=WARM){const b=(k-WARM)*N;for(let i=0;i<N;i++)s[b+i]=f.lum[i];}
if(k>=WARM){const b=(k-WARM)*N,src=M.comp?V:f.lum;CP.light(f,V,Y);fl.push(Y);for(let i=0;i<N;i++)s[b+i]=src[i]+0.5;}
}
let water=0;
for(let i=0;i<N;i++){ const rz=(i/COLS)|0; if(f.kind[i]===2&&rz>ROWS*0.56){isWater[i]=1;water++;} }
if(M.comp)isWater=CP.dilate(isWater,COLS,ROWS,f.D);
let big=0,band=0,worst=0;const x=new Float64Array(keep);
for(let i=0;i<N;i++){ if(!isWater[i]) continue;let b=0,mx=0,prev=s[i];
for(let k=1;k<keep;k++){const v=s[k*N+i],d=Math.abs(v-prev);if(d>mx)mx=d;if(d>85)b++;prev=v;x[k]=v;}
@ -47,7 +56,7 @@ function run(preset,seed,reduced,dOff){
if(b/(keep/60)>big)big=b/(keep/60);
if(mx>worst)worst=mx;
for(const fq of PROBES){const a=goertzel(x,fq);if(a>band)band=a;}}
return {water,worst:(100*worst/255).toFixed(1),big:big.toFixed(2),band:(100*band/255).toFixed(2)};
return {water,worst:(100*worst/255).toFixed(1),big:big.toFixed(2),band:(100*band/255).toFixed(2),flash:fl.result()};
}
/* One sweep, collected as it prints. The verdict below reads THIS array — an earlier cut ran the
same eight configurations a second time to score them, which doubled a 13-second gate's runtime
@ -56,7 +65,7 @@ const ROWS_ALL=[];
for(const [seed,dOff] of [[42,2],[42,8],[3,2],[3,8]])
for(const p of ['kiri','typhoon'])
{ const r=run(p,seed,false,dOff); ROWS_ALL.push(r);
console.log('seed',seed,'dist-to-channel',dOff+'m',p.padEnd(8),r?`waterCells ${String(r.water).padStart(4)} worstStep ${r.worst}% bigSteps ${r.big}/s 3-20Hz ${r.band}%`:'(never reached)'); }
console.log('seed',seed,'dist-to-channel',dOff+'m',p.padEnd(8),r?`waterCells ${String(r.water).padStart(4)} worstStep ${r.worst}% bigSteps ${r.big}/s 3-20Hz ${r.band}%\n ${CP.fmt(r.flash)}`:'(never reached)'); }
const rm=run('typhoon',42,true,2);
console.log('reduced-motion @2m typhoon:', rm?`waterCells ${rm.water} worstStep ${rm.worst}% bigSteps ${rm.big}/s 3-20Hz ${rm.band}%`:'n/a');
@ -72,12 +81,14 @@ if (!measured.length || measured.every(r => r.water === 0)) {
}
const worstBand = Math.max(...measured.map(r => parseFloat(r.band)));
const worstBig = Math.max(...measured.map(r => parseFloat(r.big)));
const worstFl = measured.concat(rm ? [rm] : []).reduce((a, r) => r.flash.area > a.area || (r.flash.area === a.area && r.flash.swing > a.swing) ? r.flash : a, measured[0].flash);
const bad = (worstBand > 2.0 ? ` 3-20Hz ${worstBand}% over 2%` : '') +
(worstBig > 8.0 ? ` big steps ${worstBig}/s over 8/s` : '') +
(worstFl.bad ? ' general flash' : '') +
/* The reduced-motion row was printed and not judged, which is half a gate: the flag's
rule is stricter than the live one — with it on, everything that modulates must be
frozen or slow enough that the band is empty. */
(rm && (parseFloat(rm.big) > 0 || parseFloat(rm.band) > 0.5)
? ` reduced motion is not still (${rm.big}/s, ${rm.band}%)` : '');
console.log(`RESULT: ${bad ? 'FAIL' + bad : 'PASS'} (worst 3-20Hz ${worstBand}%, worst big steps ${worstBig}/s)`);
console.log(`RESULT: ${bad ? 'FAIL' + bad : 'PASS'} (worst 3-20Hz ${worstBand}%, worst big steps ${worstBig}/s; ${CP.fmt(worstFl)}; ${M.tag})`);
process.exit(bad ? 1 : 0);

212
tools/composite.cjs Normal file
View file

@ -0,0 +1,212 @@
/* THE COMPOSITE, FOR THE PHOTOSENSITIVITY PROBES — what a cell actually puts on the glass, and the
* WCAG general-flash rule measured over AREA rather than per cell.
*
* const CP = require('./composite.cjs')(CC);
* const M = CP.mode(argv, 200, 60); // { comp, cols, rows, tag }
* ...render a frame; in composite mode call CC.Compose.world(f) after the world pass and
* CC.Compose.post(f, cam, t) after the elements, exactly as main.js does...
* CP.light(f, V, Y); // per-cell display value 0..255 and linear Y
* fl.push(Y); // fl = CP.Flash(cols, rows)
*
* WHY THIS FILE EXISTS. Every probe in tools/ was written against f.lum, the glyph layer, and the
* underpainting (CC.Compose's `under`) is not in f.lum — it never touches ch/col/lum, which is
* precisely why every census and fixture fitted to the glyph layer still reads the frame it was
* fitted to. But it FOLLOWS lum: its SPILL term spreads every lit emitter over a box nine
* reference cells wide and five tall. A tube that steps half its brightness in one frame was one
* cell of step edge; on the composite it is up to forty-five cells of wash stepping with it. The
* lum probes cannot see that, and CONTRACT's newest rule is that a gate which cannot see the
* feature is not a gate. So every probe now takes `--composite`, and in that mode it measures
* THIS — the light the cell emits — instead of the number the painters wrote.
*
* WHAT A CELL EMITS. The canvas lays the under block first, one flat colour per cell, and adds the
* glyph over it: ink at palette x lum/255 on the pixels the glyph covers, nothing on the rest.
* Averaged over the cell, in LINEAR light because that is what an eye and the WCAG thresholds
* integrate,
*
* Y = (1 - cov) * lin(under) + cov * lin(min(255, under + palette * lum/255))
*
* with cov the glyph's ink share from tools/cov.json — the same table metrics.py --composite
* weights with, measured by topng.py's calibrated rasteriser at the 9x16 reference cell — OR, when
* the grid stands for a cell the canvas prints through its pixel path, that cell's own table with
* the pixel path's ink compensation baked in (see CELL below). The
* display value V is Y re-encoded to sRGB and scaled to 255, so a probe's existing "a third of full
* scale" and "2% of full scale" rules read in the units they always have. Two things are knowingly
* left out and are stated rather than hidden: the BLOOM, which is a wide blur of the glyph scene
* and so moves only where the ink already moved (the glyph term here carries that amplitude, the
* halo spreads it thinner), and per-pixel gamma inside the glyph, which this cell average smooths.
*
* In LUM mode (no --composite) a probe's own per-cell statistics are exactly what they were, and
* light() is still called for the flash check with the under term zeroed — which is the glyph
* layer as it prints, the frame CC.Compose.UNDER = 0 puts on the glass. Lum mode therefore also
* switches the underpainting OFF for the run: it costs a raycast's worth of time per frame and,
* by construction, cannot change one byte of f.lum. */
'use strict';
const fs = require('fs'), path = require('path');
module.exports = function (CC) {
const CJ = JSON.parse(fs.readFileSync(path.join(__dirname, 'cov.json'), 'utf8'));
const G = CC.GLYPHS, PAL = CC.PALETTE;
const cov = new Float32Array(G.length);
function useCov(COV, name) {
for (let i = 1; i < G.length; i++) {
/* A glyph with no coverage is a hole in the measurement, and a probe that weighted it at zero
* would score a flashing new glyph as dark. Refuse, with the line that fixes it. */
if (!COV || !(G[i] in COV)) throw new Error(`composite: no ${name} coverage for ${JSON.stringify(G[i])} — ` +
'regenerate tools/cov.json (python3 tools/topng.py f.txt --cov > tools/cov.json)');
cov[i] = COV[G[i]];
}
}
useCov(CJ.cov, '9x16');
/* sRGB decode per 8-bit level, and the luminance weights folded in per channel, so a cell is
* six table reads and no pow(). ENC is the inverse on a 4096-step linear ramp, fine enough that
* its quantisation is a twentieth of a display level at the dark end where it matters. */
const LIN = new Float32Array(256), LR = new Float32Array(256), LG = new Float32Array(256), LB = new Float32Array(256);
for (let c = 0; c < 256; c++) {
const s = c / 255; LIN[c] = s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
LR[c] = 0.2126 * LIN[c]; LG[c] = 0.7152 * LIN[c]; LB[c] = 0.0722 * LIN[c];
}
const ENC = new Float32Array(4097);
for (let k = 0; k <= 4096; k++) {
const y = k / 4096; ENC[k] = 255 * (y <= 0.0031308 ? 12.92 * y : 1.055 * Math.pow(y, 1 / 2.4) - 0.055);
}
/* ---- MODE. One parser for every probe, so `--composite --cols=400 --rows=120` means the same
* thing on all seven command lines and no probe grows its own spelling of it.
*
* CELL. A glyph's ink share is not one number: render_canvas.js prints cells of PX_CELL (7)
* device px and under through its pixel path, which LIFTS coverage per pixel (cov' = 1-(1-cov)^k,
* k = 1 + 1.6*(9-dw)/9) so a 5 px stroke does not print grey. Measured in Chromium with the
* atlas's own recipe, that is +17% of mean ink at 6x11 and +25% at 5x9; weighting a 400-column
* gate by the 9x16 table understated the glyph's share of every cell's light at exactly the size
* that gate stands for. So the grid names a cell: by default the width it gets across a 1920 px
* panel at dpr 1 (200 columns -> 10 px, the reference table, unchanged; 400 -> 5 px, the 5x9
* compensated table), or `--cell=N` to ask about another panel — a 200-column grid is also what a
* 1280 px window prints at 6 px. topng.py --cov writes the compensated tables (cov.json 'px'). */
const PX_CELL = 7;
function mode(argv, dc, dr) {
const fl = argv.filter(a => a.slice(0, 2) === '--');
const num = k => { const a = fl.find(x => x.indexOf('--' + k + '=') === 0); return a ? parseInt(a.slice(k.length + 3), 10) : NaN; };
const comp = fl.indexOf('--composite') >= 0, cols = num('cols') || dc, rows = num('rows') || dr;
if (!(cols > 8) || !(rows > 8)) { console.error('composite: --cols and --rows must be over 8'); process.exit(2); }
const dw = num('cell') || Math.max(4, Math.round(1920 / cols));
let cell = '9x16';
if (dw <= PX_CELL) {
const key = Object.keys(CJ.px || {}).find(k => parseInt(k, 10) === dw);
if (!key) { console.error(`composite: no pixel-path coverage for a ${dw} px cell in tools/cov.json — regenerate it`); process.exit(2); }
useCov(CJ.px[key], key); cell = key + ' ink-compensated';
} else useCov(CJ.cov, '9x16');
if (CC.Compose) CC.Compose.UNDER = comp ? 1 : 0;
return { comp, cols, rows, cell, tag: `${comp ? 'COMPOSITE (glyph + underpainting)' : 'LUM (glyph layer)'} ${cols}x${rows}, cell ${cell}` };
}
/* ---- THE CELL'S LIGHT. V (display 0..255) and Y (linear 0..1), either may be null. */
function light(f, V, Y) {
const n = f.n, ch = f.ch, col = f.col, lum = f.lum, u = f.under, on = !!(u && CC.Compose && CC.Compose.UNDER);
for (let i = 0; i < n; i++) {
let r = 0, g = 0, b = 0;
if (on) { const o = i * 3; r = u[o]; g = u[o + 1]; b = u[o + 2]; }
let y = LR[r] + LG[g] + LB[b];
const c = ch[i], L = lum[i];
/* lum under 4 is not drawn by the canvas (LUM_FLOOR in render_canvas.js), so it emits nothing */
if (c && L >= 4) {
const p = PAL[col[i]], k = L / 255, w = cov[c];
const R = Math.min(255, r + p[0] * k + 0.5) | 0, Gg = Math.min(255, g + p[1] * k + 0.5) | 0, B = Math.min(255, b + p[2] * k + 0.5) | 0;
y = (1 - w) * y + w * (LR[R] + LG[Gg] + LB[B]);
}
if (Y) Y[i] = y;
if (V) V[i] = ENC[(y >= 1 ? 1 : y) * 4096 + 0.5 | 0];
}
}
/* ---- THE SPILL'S REACH. A probe that scores a SET of cells (the canal's water, the road, the
* crown a walk pinned on) scores, in composite mode, that set grown by the spill box: the wash
* a flickering reflection throws lands on the kerb beside it, and a mask that stops at the water
* would measure the cause and not look at the effect. hx/hy are core.js's own, D-scaled. */
function dilate(mask, cols, rows, D) {
const hx = Math.round(4 * (D || 1)), hy = Math.round(2 * (D || 1)), out = new Uint8Array(mask.length);
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) if (mask[y * cols + x])
for (let yy = Math.max(0, y - hy); yy <= Math.min(rows - 1, y + hy); yy++)
out.fill(1, yy * cols + Math.max(0, x - hx), yy * cols + Math.min(cols - 1, x + hx) + 1);
return out;
}
/* ---- THE GENERAL-FLASH RULE, AREA-WEIGHTED --------------------------------------------------
* Every rule the probes had was PER CELL: one fixture's step, one cell's rate, one cell's band.
* WCAG 2.3.1's general-flash threshold is not: a flash is a hazard when MORE THAN THREE happen in
* one second AND the area flashing together is more than a quarter of any 10-degree field of
* view. That second clause is the one the underpainting changes — the spill turns a one-cell
* event into a forty-five-cell one without changing its rate — and no per-cell statistic can
* see it. So:
*
* TRANSITION a change in a cell's relative luminance of at least 0.10 (10% of white), against
* the extreme since its last transition, with the darker side under 0.80. That is
* WCAG's own definition; the hysteresis against the running extreme is what stops a
* slow ramp being counted as a hundred small ones.
* FLASHING a cell with SEVEN or more transitions inside the last 60 frames — more than three
* and a half flashes a second, which rounds the rule against the viewer's favour.
* AREA the flashing cells' share of the worst window a third of the screen wide and a
* third tall. WCAG's note puts a 10-degree field at 341x256 on a 1024x768 screen,
* which is that third. The rule is a quarter of it; HAZARD_AREA below.
*
* It also prints SWING, the plan's literal measure: the largest share of the whole screen whose
* luminance moved by 0.10 or more inside one third of a second. It is read at four lags, 3, 5, 10
* and 20 frames, and not at 20 alone: a strobe whose period divides 20 frames is in the same phase
* at both ends of the window, and the single-lag first cut scored a 6 Hz test sign at 0.0%. Swing is NOT judged — a
* single lightning stroke moves most of the screen once and that is one flash, not a hazard —
* but it is the number that shows how much area an event moves, so it is reported beside the
* verdict that decides. Red flashes (WCAG's second clause) are not measured here; see CONTRACT. */
const T = 0.10, DARK = 0.80, NTR = 7, WIN = 60, SWING_LAG = 20, HAZARD_AREA = 0.25;
function Flash(cols, rows) {
const n = cols * rows, hi = new Float32Array(n), lo = new Float32Array(n), s = new Int8Array(n);
const ring = new Int32Array(n * 8).fill(-1e9), rp = new Uint8Array(n), hz = new Uint8Array(n);
const lag = []; for (let k = 0; k < SWING_LAG; k++) lag.push(new Float32Array(n));
const wc = Math.max(1, Math.round(cols / 3)), wr = Math.max(1, Math.round(rows / 3));
const sat = new Int32Array((cols + 1) * (rows + 1));
let k = 0, worst = 0, worstAt = -1, worstScreen = 0, swing = 0, swingAt = -1, trans = 0;
function push(Y) {
let any = 0, sw = 0;
const old = lag[k % SWING_LAG], l3 = lag[(k + 17) % SWING_LAG], l5 = lag[(k + 15) % SWING_LAG], l10 = lag[(k + 10) % SWING_LAG];
for (let i = 0; i < n; i++) {
const y = Y[i];
if (k >= SWING_LAG && (Math.abs(y - old[i]) >= T || Math.abs(y - l3[i]) >= T || Math.abs(y - l5[i]) >= T || Math.abs(y - l10[i]) >= T)) sw++;
old[i] = y;
if (!k) { hi[i] = lo[i] = y; continue; }
let tr = 0;
if (s[i] >= 0) { if (y > hi[i]) hi[i] = y; if (hi[i] - y >= T && y < DARK) { s[i] = -1; lo[i] = y; tr = 1; } }
if (!tr && s[i] <= 0) { if (y < lo[i]) lo[i] = y; if (y - lo[i] >= T && lo[i] < DARK) { s[i] = 1; hi[i] = y; tr = 1; } }
if (tr) { trans++; ring[i * 8 + (rp[i] = (rp[i] + 1) & 7)] = k; }
/* the 7th most recent transition is still inside the last second */
const h = ring[i * 8 + ((rp[i] + 8 - (NTR - 1)) & 7)] > k - WIN ? 1 : 0;
hz[i] = h; any += h;
}
if (k >= SWING_LAG && sw / n > swing) { swing = sw / n; swingAt = k; }
if (any) {
if (any / n > worstScreen) worstScreen = any / n;
for (let y = 0; y < rows; y++) for (let x = 0, run = 0; x < cols; x++) {
run += hz[y * cols + x];
sat[(y + 1) * (cols + 1) + x + 1] = sat[y * (cols + 1) + x + 1] + run;
}
let m = 0;
for (let y = 0; y + wr <= rows; y++) for (let x = 0; x + wc <= cols; x++) {
const a = sat[(y + wr) * (cols + 1) + x + wc] - sat[y * (cols + 1) + x + wc] - sat[(y + wr) * (cols + 1) + x] + sat[y * (cols + 1) + x];
if (a > m) m = a;
}
if (m / (wc * wr) > worst) { worst = m / (wc * wr); worstAt = k; }
}
k++;
}
function result() {
return { area: worst, at: worstAt, screen: worstScreen, swing, swingAt, frames: k, transitions: trans,
bad: worst > HAZARD_AREA };
}
return { push, result };
}
/* One line, the same in every probe, so a report can quote it without translating between seven
* spellings. The area is the verdict; swing and transitions are context. */
function fmt(r) {
return `flash area ${(r.area * 100).toFixed(1)}% of a 10° field (limit ${HAZARD_AREA * 100}%)` +
`${r.area > 0 ? ' at f' + r.at : ''}, swing ${(r.swing * 100).toFixed(1)}% of screen per 1/3 s, ` +
`${r.transitions} transitions`;
}
return { mode, light, dilate, Flash, fmt, HAZARD_AREA };
};

256
tools/cov.json Normal file
View file

@ -0,0 +1,256 @@
{
"_": "python3 tools/topng.py f.txt --cov > tools/cov.json -- glyph ink share of the cell; weights metrics.py --composite and composite.cjs",
"cell": "9x16",
"cov": {
".": 0.031,
",": 0.0651,
":": 0.062,
";": 0.0959,
"'": 0.0643,
"\"": 0.1253,
"`": 0.0278,
"^": 0.1641,
"~": 0.0921,
"-": 0.0547,
"_": 0.0465,
"=": 0.1784,
"+": 0.1631,
"*": 0.1315,
"|": 0.1982,
"/": 0.135,
"\\": 0.1357,
"(": 0.208,
")": 0.208,
"[": 0.2494,
"]": 0.2483,
"{": 0.2515,
"}": 0.2514,
"<": 0.1763,
">": 0.1766,
"!": 0.1297,
"?": 0.201,
"#": 0.2521,
"%": 0.2887,
"&": 0.3188,
"$": 0.3161,
"@": 0.3508,
"8": 0.3281,
"O": 0.3331,
"o": 0.2556,
"Q": 0.3986,
"0": 0.3264,
"X": 0.2908,
"Z": 0.2878,
"W": 0.3541,
"M": 0.3647,
"N": 0.3644,
"H": 0.3396,
"U": 0.3182,
"V": 0.2796,
"A": 0.3093,
"K": 0.3344,
"Y": 0.2422
},
"px": {
"4x7": {
".": 0.0541,
",": 0.0833,
":": 0.1213,
";": 0.1543,
"'": 0.0952,
"\"": 0.17,
"`": 0.0502,
"^": 0.2538,
"~": 0.1192,
"-": 0.0675,
"_": 0.0838,
"=": 0.2833,
"+": 0.2496,
"*": 0.1681,
"|": 0.3298,
"/": 0.2155,
"\\": 0.2156,
"(": 0.3017,
")": 0.3029,
"[": 0.3499,
"]": 0.3499,
"{": 0.391,
"}": 0.3908,
"<": 0.2691,
">": 0.2692,
"!": 0.2184,
"?": 0.314,
"#": 0.3864,
"%": 0.441,
"&": 0.4456,
"$": 0.4959,
"@": 0.5756,
"8": 0.4763,
"O": 0.4685,
"o": 0.3953,
"Q": 0.5746,
"0": 0.4661,
"X": 0.415,
"Z": 0.4107,
"W": 0.4716,
"M": 0.5108,
"N": 0.5223,
"H": 0.5113,
"U": 0.4795,
"V": 0.397,
"A": 0.4125,
"K": 0.476,
"Y": 0.3468
},
"5x9": {
".": 0.0483,
",": 0.0904,
":": 0.1006,
";": 0.1435,
"'": 0.066,
"\"": 0.1375,
"`": 0.0507,
"^": 0.2177,
"~": 0.1314,
"-": 0.0826,
"_": 0.0804,
"=": 0.2654,
"+": 0.2028,
"*": 0.1485,
"|": 0.2109,
"/": 0.18,
"\\": 0.1806,
"(": 0.2698,
")": 0.2688,
"[": 0.3254,
"]": 0.3254,
"{": 0.3247,
"}": 0.3249,
"<": 0.2411,
">": 0.2413,
"!": 0.1381,
"?": 0.2595,
"#": 0.3566,
"%": 0.3858,
"&": 0.3946,
"$": 0.4377,
"@": 0.4729,
"8": 0.415,
"O": 0.4068,
"o": 0.3497,
"Q": 0.4987,
"0": 0.4084,
"X": 0.3572,
"Z": 0.3539,
"W": 0.4277,
"M": 0.4611,
"N": 0.4696,
"H": 0.4318,
"U": 0.3983,
"V": 0.3422,
"A": 0.3653,
"K": 0.4124,
"Y": 0.2805
},
"6x11": {
".": 0.0265,
",": 0.0695,
":": 0.0531,
";": 0.0947,
"'": 0.0709,
"\"": 0.1394,
"`": 0.0488,
"^": 0.1686,
"~": 0.1114,
"-": 0.0652,
"_": 0.0648,
"=": 0.19,
"+": 0.1888,
"*": 0.1509,
"|": 0.2268,
"/": 0.1563,
"\\": 0.156,
"(": 0.2282,
")": 0.2293,
"[": 0.2636,
"]": 0.2667,
"{": 0.2715,
"}": 0.2704,
"<": 0.2166,
">": 0.2168,
"!": 0.1523,
"?": 0.2308,
"#": 0.3056,
"%": 0.3383,
"&": 0.3953,
"$": 0.4154,
"@": 0.3968,
"8": 0.3848,
"O": 0.3828,
"o": 0.2704,
"Q": 0.4593,
"0": 0.3685,
"X": 0.346,
"Z": 0.3276,
"W": 0.4264,
"M": 0.4525,
"N": 0.4395,
"H": 0.403,
"U": 0.3732,
"V": 0.3296,
"A": 0.3587,
"K": 0.3945,
"Y": 0.2752
},
"7x12": {
".": 0.0414,
",": 0.0741,
":": 0.0828,
";": 0.1157,
"'": 0.0737,
"\"": 0.1473,
"`": 0.0395,
"^": 0.1847,
"~": 0.1075,
"-": 0.069,
"_": 0.0701,
"=": 0.2103,
"+": 0.1919,
"*": 0.1414,
"|": 0.2383,
"/": 0.1595,
"\\": 0.1593,
"(": 0.2374,
")": 0.2372,
"[": 0.2878,
"]": 0.2878,
"{": 0.2924,
"}": 0.293,
"<": 0.219,
">": 0.2191,
"!": 0.1581,
"?": 0.2477,
"#": 0.302,
"%": 0.353,
"&": 0.3758,
"$": 0.4009,
"@": 0.4448,
"8": 0.3873,
"O": 0.382,
"o": 0.2924,
"Q": 0.4619,
"0": 0.3759,
"X": 0.3335,
"Z": 0.3343,
"W": 0.4099,
"M": 0.4298,
"N": 0.4238,
"H": 0.4009,
"U": 0.3731,
"V": 0.3183,
"A": 0.3462,
"K": 0.3861,
"Y": 0.2711
}
}
}

View file

@ -33,24 +33,73 @@ const ONLY = (function () {
return null;
})();
/* ---- extract the shipped script ------------------------------------------------------------
* The page has exactly one <script> and it is inline; if that ever stops being true the shim is
* testing something other than the deliverable and must say so rather than quietly test less. */
/* ---- extract the shipped scripts -----------------------------------------------------------
* The page ships its code as several <script> tags since the payload split (see THE SPLIT in
* build.js): one synchronous `<script src="w/<world>.js">` per secondary world, then the inline
* bundle that calls their modules back in. They are run here exactly as a browser runs them — one
* vm.Script per tag, in DOM order, in one context, each with its own filename and line offset so a
* stack frame still points into the file that shipped. Concatenating them into one body would be
* simpler and would test a page nobody loads: the chunks only work because they hand their
* functions across a global between two scripts, and that hand-off is exactly what must run.
*
* The one tag that is NOT code is the JSON-LD block baseline/apply.py writes into the head. It is
* data the browser never executes, and it is skipped by its type rather than by position — the old
* "exactly one <script>" rule threw on it and left this shim dead on the shipped tree from the day
* the baseline landed. It is still parsed as JSON, because a block that does not parse is a search
* result that silently stops having a card, and nothing else in the repo would notice.
*
* Anything else is held tight, so the shim cannot quietly test less than ships: exactly one inline
* classic script; every src tag points at a w/*.js that exists; and every w/*.js on disk is loaded
* by the page — a chunk the build wrote and the page forgot is a world that renders as the city. */
const html = fs.readFileSync(PAGE, 'utf8');
const opens = html.match(/<script\b/gi) || [];
if (opens.length !== 1) throw new Error('domshim: expected exactly 1 <script> in index.html, found ' + opens.length);
const m = /<script>\n?([\s\S]*?)<\/script>/.exec(html);
if (!m) throw new Error('domshim: could not find the inline <script> body');
const SCRIPT_LINE = html.slice(0, m.index).split('\n').length; // 1-based line of <script>
/* The bundle leaks nothing to window on purpose, so there is no way to inspect CC from outside.
const TAG = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
const SCRIPTS = [];
const loaded = [];
let inlineCount = 0, MAIN = null, t;
const MARK = '/* src/main.js */';
const lineOf = (i) => html.slice(0, i).split('\n').length; // 1-based line of an offset
while ((t = TAG.exec(html))) {
const attrs = t[1];
if (/\btype\s*=\s*["']?application\/ld\+json/i.test(attrs)) { JSON.parse(t[2]); continue; }
if (/\btype\s*=/i.test(attrs)) throw new Error('domshim: unexpected <script' + attrs + '> in index.html');
const src = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
if (src) {
/* The ?v= is build.js's cache-buster, the chunk's own content hash — and it is CHECKED, not
* just stripped: a tag whose hash disagrees with the file beside it is exactly the stale pair
* the token exists to prevent, so it fails here rather than in a visitor's cache. */
const sm = /^(w\/[\w-]+\.js)(?:\?v=([0-9a-f]+))?$/.exec(src[1]);
if (!sm) throw new Error('domshim: script src outside w/: ' + src[1]);
const file = path.join(ROOT, sm[1]);
if (!fs.existsSync(file)) throw new Error('domshim: index.html loads ' + sm[1] + ', which does not exist');
const body = fs.readFileSync(file, 'utf8');
if (!sm[2] || require('crypto').createHash('sha1').update(body).digest('hex').slice(0, sm[2].length) !== sm[2])
throw new Error('domshim: ' + src[1] + ' does not carry the content hash of ' + sm[1]);
loaded.push(sm[1]);
SCRIPTS.push({ name: sm[1], s: new vm.Script(body, { filename: sm[1] }) });
continue;
}
inlineCount++;
/* The bundle leaks nothing to window on purpose, so there is no way to inspect CC from outside.
* One call is spliced in — with NO newline, so every stack line number still matches index.html —
* immediately before main.js, which means CC is captured even if boot() throws. main.js then
* hangs CC.Main off the same object we already hold. */
const MARK = '/* src/main.js */';
if (html.indexOf(MARK) < 0) throw new Error('domshim: build no longer emits the ' + MARK + ' marker');
const CODE = m[1].replace(MARK, '__export(CC);' + MARK);
const SCRIPT = new vm.Script(CODE, { filename: 'index.html', lineOffset: SCRIPT_LINE });
if (t[2].indexOf(MARK) < 0) throw new Error('domshim: build no longer emits the ' + MARK + ' marker');
MAIN = t[2];
const body = t[2].replace(/^\n/, '');
SCRIPTS.push({ name: 'index.html', s: new vm.Script(body.replace(MARK, '__export(CC);' + MARK),
{ filename: 'index.html', lineOffset: lineOf(t.index + t[0].indexOf('>') + 1 + (t[2].length - body.length)) - 1 }) });
}
if (inlineCount !== 1) throw new Error('domshim: expected exactly 1 inline <script> in index.html, found ' + inlineCount);
const WDIR = path.join(ROOT, 'w');
for (const f of (fs.existsSync(WDIR) ? fs.readdirSync(WDIR) : []))
if (f.endsWith('.js') && loaded.indexOf('w/' + f) < 0)
throw new Error('domshim: w/' + f + ' is built but index.html never loads it');
/* The column band is READ from the bundle, not written down here. A literal 260 in this file was a
* second copy of main.js's constant, and the first pass to raise MAXC would have found the shim
* failing on a page that was right. */
const MAXC = +((/\bMAXC\s*=\s*(\d+)/.exec(MAIN) || [])[1]);
const MINC = +((/\bMINC\s*=\s*(\d+)/.exec(MAIN) || [])[1]);
if (!(MAXC > 0 && MINC > 0)) throw new Error('domshim: could not read MAXC/MINC from the bundle');
/* ---- the fake DOM ---------------------------------------------------------------------------
* Every stub counts. A stub that silently accepts anything turns "the renderer drew nothing" into
@ -191,6 +240,30 @@ function makeEnv(opts) {
env.bounds.push(label + '.drawImage odd arity ' + (a.length + 1));
}
};
/* THE PIXEL PATHS, opt-in. render_canvas.js has two prints that go through ImageData — the
* underlay (one pixel per cell, putImageData'd every frame) and the pixel-write glyph pass
* (getImageData of the atlas once, putImageData of the scene every frame) — and both catch a
* missing method and fall back SILENTLY, by design. So a shim without these was passing 302
* checks on a page with no underlay and no pixel path in it, which is the shipped print on most
* desktops. They are off by default because every older case counts per-glyph drawImage calls
* and the pixel path makes those vanish; the 'print-paths' case turns them on and asserts. The
* fake atlas read is a sparse alpha mask, so every glyph bakes a non-empty coverage list. */
if (opts.imageData) {
const img = (w, h) => ({ width: w, height: h, data: new Uint8ClampedArray(w * h * 4) });
c.createImageData = function (w, h) { op('createImageData'); return img(w, h); };
c.getImageData = function (x, y, w, h) {
op('getImageData');
const r = img(w, h);
for (let i = 3; i < r.data.length; i += 28) r.data[i] = 200;
return r;
};
c.putImageData = function (im) {
op('putImageData');
if (!im || !im.data || im.data.length !== im.width * im.height * 4) env.bounds.push(label + '.putImageData malformed image');
else if (im.width > canvas.width || im.height > canvas.height)
env.bounds.push(label + '.putImageData ' + im.width + 'x' + im.height + ' onto ' + canvas.width + 'x' + canvas.height);
};
}
env.contexts.push(c);
return c;
}
@ -411,8 +484,12 @@ function makeEnv(opts) {
env.run = function () {
const sandbox = win;
vm.createContext(sandbox);
try { SCRIPT.runInContext(sandbox); }
catch (e) { env.err('script evaluation', e); }
/* One context, tags in DOM order — and a tag that throws does not stop the next, which is the
* browser's rule too: a broken chunk costs its world, it does not take the city with it. */
for (const S of SCRIPTS) {
try { S.s.runInContext(sandbox); }
catch (e) { env.err('script evaluation (' + S.name + ')', e); }
}
return env;
};
return env;
@ -533,7 +610,7 @@ testCase('resize', function (ok) {
env.tick(40);
const cols = CC.Main.cols, rows = CC.Main.rows;
const cellW = env.cc.width / cols, cellH = env.cc.height / rows;
ok(cols >= 48 && cols <= 260, label + ': column count inside its band', cols);
ok(cols >= MINC && cols <= MAXC, label + ': column count inside its band', cols);
ok(rows >= 22, label + ': row count above the floor', rows);
ok(cellW === Math.round(cellW) && cellH === Math.round(cellH),
label + ': cell is a whole number of device pixels', cellW + 'x' + cellH);
@ -1106,27 +1183,69 @@ testCase('reduced-motion', function (ok) {
});
/* ============================================================================================
* 11. adaptive quality — degrade to one bloom tap, then to fewer columns, then recover
* 11. adaptive quality — two rungs of columns, then one bloom tap, then the same ladder back
*
* The order is main.js's: columns go before bloom now that the bloom is sized in screen pixels and
* the cell count is what the frame pays for. A step every 1.2 s of bad frames from the moment the
* EMA crosses 26 ms, and the second after any layout (boot included) is not counted at all, so the
* first rung lands near tick 140, the second near 275 (its own relayout buys another quiet
* second), the bloom near 410; recovery is one rung per 6 s of good frames, plus that quiet second
* after each relayout, three rungs back.
* Each intermediate state is checked, not just the ends — a ladder that skipped its middle rung
* would arrive at the same two end states and still have taken twice the detail out at once.
* ========================================================================================== */
testCase('adaptive-quality', function (ok) {
const env = makeEnv({ frameCost: 40 }).run();
const CC = env.CC;
if (!ok(!!CC, 'booted')) return env;
const cols0 = CC.Main.cols;
env.tick(120);
ok(CC.Canvas.quality === 1, 'a 40 ms frame dropped the bloom to one tap first', CC.Canvas.quality);
env.tick(170);
const cols1 = CC.Main.cols;
ok(cols1 < cols0 && CC.Canvas.quality === 2, 'a 40 ms frame gave up columns first, bloom kept',
cols0 + ' -> ' + cols1 + ' q' + CC.Canvas.quality);
env.tick(130);
const cols2 = CC.Main.cols;
ok(cols2 < cols1 && CC.Canvas.quality === 2, 'then a second rung of columns, bloom still kept',
cols1 + ' -> ' + cols2 + ' q' + CC.Canvas.quality);
env.tick(150);
ok(CC.Main.cols === cols2 && CC.Canvas.quality === 1, 'and only then did the bloom drop to one tap',
CC.Main.cols + ' q' + CC.Canvas.quality);
const drewAtQ1 = env.get('cc.drawImage');
env.tick(60);
ok(env.get('cc.drawImage') - drewAtQ1 >= 60 * 2, 'the degraded composite still draws scene + one tap',
env.get('cc.drawImage') - drewAtQ1);
env.tick(120);
ok(CC.Main.cols < cols0, 'and only then did it give up columns', cols0 + ' -> ' + CC.Main.cols);
ok(env.bounds.length === 0, 'the mid-loop relayout left no bad draws', env.bounds.slice(0, 2).join(' | '));
ok(CC.Main.cols === cols2, 'the ladder stops at its last rung', CC.Main.cols);
ok(env.bounds.length === 0, 'the mid-loop relayouts left no bad draws', env.bounds.slice(0, 2).join(' | '));
env.frameCost = 4;
env.tick(900); // two 6 s recovery windows
ok(CC.Main.cols === cols0, 'columns came back first', CC.Main.cols);
ok(CC.Canvas.quality === 2, 'then the full bloom', CC.Canvas.quality);
env.tick(420); // one 6 s window plus the EMA's fall
ok(CC.Canvas.quality === 2 && CC.Main.cols === cols2, 'the bloom came back first',
CC.Main.cols + ' q' + CC.Canvas.quality);
env.tick(370);
ok(CC.Main.cols === cols1, 'then one rung of columns', CC.Main.cols);
env.tick(430);
ok(CC.Main.cols === cols0 && CC.Canvas.quality === 2, 'then the full grid', CC.Main.cols);
/* The breathing guard: the grid just regained is lost again inside twelve seconds, so the next
* climb must wait twelve good seconds rather than six. At 500 ticks a six-second wait would have
* climbed already (quiet second + EMA fall + 360); a doubled one has not. */
env.frameCost = 40;
env.tick(170);
ok(CC.Main.cols === cols1, 'a relapse right after recovery takes one rung', CC.Main.cols);
env.frameCost = 4;
env.tick(500);
ok(CC.Main.cols === cols1, 'and the climb back now waits the doubled hold', CC.Main.cols);
env.tick(400);
ok(CC.Main.cols === cols0, 'but does come back', CC.Main.cols);
/* And the doubling is not for life: a rung held a full minute before it is lost again resets the
* wait, so the next climb back is the plain six seconds — the 500 ticks that were too few above. */
env.tick(3700);
env.frameCost = 40;
env.tick(170);
ok(CC.Main.cols === cols1, 'a relapse a minute later takes one rung', CC.Main.cols);
env.frameCost = 4;
env.tick(500);
ok(CC.Main.cols === cols0, 'and the climb back is six seconds again, not the doubled hold', CC.Main.cols);
// quality 0 is reachable only by hand; it must still put the frame on the glass.
CC.Canvas.setQuality(0);
@ -1136,6 +1255,16 @@ testCase('adaptive-quality', function (ok) {
CC.Canvas.setQuality(2);
env.tick(30);
ok(env.errors.length === 0, 'no exceptions across the quality ladder');
/* Past MAXC the 1.25 rung lands on the cell the cap already chose (2560 at dpr 1: 8 px, 320
* columns either way), so the first degrade has to go straight on to 1.5 rather than spend a
* rung on nothing. */
const wide = makeEnv({ w: 2560, h: 1440, dpr: 1, frameCost: 40 }).run();
const w0 = wide.CC.Main.cols;
wide.tick(170);
ok(wide.CC.Main.cols < w0 && wide.CC.Canvas.quality === 2, 'a capped grid skips the rung that moves no columns',
w0 + ' -> ' + wide.CC.Main.cols + ' q' + wide.CC.Canvas.quality);
ok(wide.errors.length === 0 && wide.bounds.length === 0, 'and the skip left no bad draws');
return env;
});
@ -1276,6 +1405,44 @@ testCase('denied-permissions', function (ok) {
return [env, old];
});
/* ============================================================================================
* 17. the print paths — underlay, kill switch, pixel path
*
* The three things the shipped print does that the drawImage-only shim above could never see:
* (a) with the underpainting on, every frame copies f.under into its one-pixel-per-cell buffer
* (putImageData) and draws it first on the page canvas — scene + 2 bloom taps + 1 underlay;
* (b) with CC.Compose.UNDER = 0 neither happens, so the kill switch removes the op, not just its
* pixels;
* (c) at a dw <= 7 layout (1280 at dpr 1: 6 px cells) 'auto' engages the pixel path, and at a
* coarse one (dpr 2: 13 px) it does not.
* ========================================================================================== */
testCase('print-paths', function (ok) {
const env = makeEnv({ w: 1280, h: 800, dpr: 1, imageData: true }).run();
const CC = env.CC;
if (!ok(!!CC, 'booted')) return env;
env.tick(30);
ok(CC.Canvas.pixelPath === true, "'auto' engaged the pixel path on 6 px cells", CC.Canvas.pixelPath);
let p0 = env.get('putImageData'), d0 = env.get('cc.drawImage');
env.tick(60);
const put1 = env.get('putImageData') - p0, cc1 = env.get('cc.drawImage') - d0;
ok(put1 >= 120, 'UNDER=1: scene and underlay both putImageData each frame', put1);
ok(cc1 >= 240, 'UNDER=1: the page draws underlay + scene + 2 taps each frame', cc1);
CC.Compose.UNDER = 0;
env.tick(2); // the one frame that clears the old field
p0 = env.get('putImageData'); d0 = env.get('cc.drawImage');
env.tick(60);
const put0 = env.get('putImageData') - p0, cc0 = env.get('cc.drawImage') - d0;
ok(put0 === 60, 'UNDER=0: only the scene is put, no underlay copy', put0);
ok(cc0 === cc1 - 60, 'UNDER=0: exactly one page draw per frame fewer — the underlay op is gone', cc0 + ' vs ' + cc1);
ok(env.errors.length === 0 && env.bounds.length === 0, 'no exceptions or bad draws on the pixel path',
env.bounds.slice(0, 2).join(' | '));
const hi = makeEnv({ w: 1280, h: 800, dpr: 2, imageData: true }).run();
hi.tick(30);
ok(hi.CC.Canvas.pixelPath === false, "and 'auto' leaves 13 px cells on drawImage", hi.CC.Canvas.pixelPath);
ok(hi.errors.length === 0 && hi.bounds.length === 0, 'no exceptions or bad draws there either');
return [env, hi];
});
/* ---- run ------------------------------------------------------------------------------------ */
let failed = 0, passed = 0;
const allErrors = [];

View file

@ -3,6 +3,12 @@
*
* node tools/flicker-rate.cjs [signage.js path] [seconds] [phases]
* node tools/flicker-rate.cjs [seconds] [phases] — a bare number first IS the window
* ... [--composite] [--cols=200] [--rows=60] — see tools/composite.cjs
*
* --composite scores sections 2-4 on the light each cell EMITS (glyph plus underpainting) instead
* of the element's raw lum, and both modes now also run the area-weighted WCAG general-flash rule
* on what prints. --cols/--rows size the fixture frame: a fixture that is fine at 200 columns can
* spill over more CELLS at 400, and the spill box is the part of the composite that scales.
*
* RUN IT WITH NO ARGUMENTS to get a verdict. The default 60 s window is the one the 3-20 Hz limit
* was fitted at; below it that rule is printed but not judged and the process exits 3, because a
@ -121,6 +127,9 @@ const BAND_JUDGED = SECS >= BAND_CALIBRATION_SECS;
global.CC = require(path.join(root, 'src/core.js'));
global.window = undefined;
const CC = global.CC;
/* --composite, --cols=, --rows=: see tools/composite.cjs. Section 1 is a function and has no frame,
* so only sections 2-4 change with them. */
const CP = require('./composite.cjs')(CC), M = CP.mode(process.argv, 200, 60);
/* ---- lift flick() out of the shipped source ------------------------------------------------ */
function lift(file, name) {
@ -143,7 +152,7 @@ function lift(file, name) {
}
const lifted = lift(SRC, 'flick');
const flick = lifted.fn;
console.log(`source: ${path.relative(root, SRC)} ${SECS}s @60Hz x ${PHASES} phases`);
console.log(`source: ${path.relative(root, SRC)} ${SECS}s @60Hz x ${PHASES} phases frames: ${M.tag}`);
console.log('lifted flick():\n' + lifted.text.split('\n').map(l => ' ' + l).join('\n') + '\n');
/* ---- the personalities, as the draw loops call them ----------------------------------------- */
@ -348,20 +357,28 @@ const NAMES = ['neon', 'shopSpill', 'signals', 'holo', 'police', 'ads', 'skylane
* skylanes is the expected answer under mist. A NOT_APPLICABLE naming anything else, or any FAIL,
* is a finding. */
const MAX_CELL_RATE = 1.0; // big steps a second in one cell, above which it is flicker
const COLS = 200, ROWS = 60;
const COLS = M.cols, ROWS = M.rows;
/* The worst general-flash area any fixture reached, per tools/composite.cjs. Judged in sections 2
* and 3; section 4's rule (nothing moves at all) is already stricter than it. */
let flashWorst = { area: 0, swing: 0, transitions: 0, at: -1 }, flashWhat = 'nothing measured';
/* One element, one seed, eight compass bearings, 20 s each at 60 Hz. */
function fixture(name, seed, els, secsEach) {
const el = els.find(e => e.name === name);
if (!el) return null;
const f = CC.makeFrame(COLS, ROWS);
const big = new Uint32Array(f.n);
let worst = 0, worstYaw = 0, worstT = 0, painted = 0, rate = 0;
/* The density the raycast would have published for this grid (raycast.js, frame.D), written by
* hand because there is no world pass here to publish it — without it the spill box stays nine
* cells wide at 400 columns and the composite measures a lamp lighting a quarter of its street. */
f.D = Math.max(1, COLS / 200);
const big = new Uint32Array(f.n), V = new Float32Array(f.n), Y = new Float32Array(f.n);
let worst = 0, worstYaw = 0, worstT = 0, painted = 0, rate = 0, fla = null;
for (let yi = 0; yi < 8; yi++) {
const yaw = yi * Math.PI / 4;
/* Per bearing: a cell index is a different fixture in every direction, so the counts cannot be
* pooled across them without diluting the one view that has a sign in it. */
big.fill(0);
const fl = CP.Flash(COLS, ROWS);
const cam = { x: city_.startX, z: city_.startZ, yaw: yaw, eyeY: 1.7, fov: 1.25,
horizon: ROWS * 0.56, cellAspect: 0.5625, t: 0 };
let prev = null;
@ -371,10 +388,24 @@ function fixture(name, seed, els, secsEach) {
// Every tick, exactly as main.js does it: the element reads the live P block from update().
if (CC.Weather) { CC.Weather.update(1 / 60, t); pinSky(); }
for (let i = 0; i < f.n; i++) { f.ch[i] = 1; f.col[i] = 5; f.lum[i] = 0; f.dist[i] = 1e6; f.kind[i] = 1; }
/* The empty far wall is the world pass here, so it is what the underpainting's snapshot has
* to hold: the element is drawn OVER it, and its mass and spill are read against it. */
if (M.comp) CC.Compose.world(f);
if (el.update) el.update(1 / 60, t, cam);
el.draw(f, cam, t);
const cur = Float64Array.from(f.lum);
for (let i = 0; i < f.n; i++) if (cur[i] > 0) painted++;
/* LUM mode scores the element's raw lum, as this section always has, and is copied BEFORE
* the print pass tones it. Composite mode scores the light the cell emits. The print pass runs
* in both, because the flash rule is about what reaches the glass — the glyph layer alone in
* lum mode (the underpainting is off there), glyphs plus wash in composite. The frame is
* refilled at the top of every tick, so toning it in place costs the next tick nothing. */
const raw = M.comp ? null : Float64Array.from(f.lum);
/* PAINTED is what the ELEMENT wrote, in both modes. Counted on the composite it would be every
* cell of the frame — the wash lies behind all of them — and the NOT MEASURED check below
* would never fire again, which is the exact hole this file's exit code 3 exists to close. */
for (let i = 0; i < f.n; i++) if (f.lum[i] > 0) painted++;
CC.Compose.post(f, cam, t);
CP.light(f, V, Y); fl.push(Y);
const cur = M.comp ? Float64Array.from(V) : raw;
if (prev) {
let fw = 0;
for (let i = 0; i < f.n; i++) {
@ -388,8 +419,10 @@ function fixture(name, seed, els, secsEach) {
}
let mx = 0; for (let i = 0; i < big.length; i++) if (big[i] > mx) mx = big[i];
if (mx / secsEach > rate) rate = mx / secsEach;
const fr = fl.result(); fr.yaw = yaw;
if (!fla || fr.area > fla.area || (fr.area === fla.area && fr.swing > fla.swing)) fla = fr;
}
return { worst, rate, painted, worstYaw, worstT };
return { worst, rate, painted, worstYaw, worstT, flash: fla };
}
let city_ = null;
@ -415,13 +448,17 @@ for (const seed of SEEDS) {
if (r.painted === 0)
notApplicable.push(`2. seed ${seed} ${name}: painted no cell in any of the 8 bearings, nothing measured`);
if (r.painted > 0 && r.worst > liveWorst) { liveWorst = r.worst; liveWorstWhat = `seed ${seed} ${name}, yaw ${r.worstYaw.toFixed(2)}, t=${r.worstT.toFixed(2)}s, sky '${SKY}'`; }
const bad = r.painted > 0 && r.worst > MAX_FRAME_STEP && r.rate > MAX_CELL_RATE;
const flBad = r.painted > 0 && r.flash.bad;
const bad = r.painted > 0 && r.worst > MAX_FRAME_STEP && r.rate > MAX_CELL_RATE || flBad;
if (bad) ok = false;
if (r.painted > 0 && (r.flash.area > flashWorst.area || r.flash.swing > flashWorst.swing))
flashWorst = r.flash, flashWhat = `seed ${seed} ${name}, yaw ${r.flash.yaw.toFixed(2)}`;
console.log(` seed ${String(seed).padStart(3)} ${name.padEnd(10)} cells painted ${String(r.painted).padStart(7)}` +
` worst per-cell frame step ${(r.worst * 100).toFixed(1)}% of 255` +
` busiest cell over-${MAX_FRAME_STEP * 100 | 0}% ${r.rate.toFixed(3)}/s` +
` (yaw ${r.worstYaw.toFixed(2)}, t=${r.worstT.toFixed(2)}s) ` +
(r.painted === 0 ? 'NOT MEASURED — no fixture in view' : bad ? 'FAIL' : 'ok'));
(r.painted === 0 ? 'NOT MEASURED — no fixture in view' : bad ? 'FAIL' + (flBad ? ' (general flash)' : '') : 'ok') +
`\n ${CP.fmt(r.flash)}`);
}
}
@ -458,11 +495,12 @@ if (src.indexOf(bobLine) < 0) {
}
if (r.painted === 0)
notApplicable.push(`3. seed ${seed} holo (still): no panel in view, nothing measured`);
const bad = r.painted > 0 && r.worst > HOLO_STILL_MAX;
const bad = r.painted > 0 && (r.worst > HOLO_STILL_MAX || r.flash.bad);
if (bad) ok = false;
console.log(` seed ${String(seed).padStart(3)} holo (still) worst per-cell frame step ` +
`${(r.worst * 100).toFixed(1)}% of 255 busiest cell ${r.rate.toFixed(3)}/s ` +
(r.painted === 0 ? 'NOT MEASURED — no panel in view' : bad ? `FAIL (> ${HOLO_STILL_MAX * 100}%)` : 'ok'));
(r.painted === 0 ? 'NOT MEASURED — no panel in view' : bad ? `FAIL (> ${HOLO_STILL_MAX * 100}% or general flash)` : 'ok') +
`\n ${CP.fmt(r.flash)}`);
}
fs.unlinkSync(tmp);
}
@ -510,8 +548,9 @@ if (notApplicable.length) {
* live build and section 4 is reduced motion, and a report has already quoted the second as if it
* were the first. See the note at the top of this file. */
console.log(`\nSUMMARY: live worst per-cell step ${(liveWorst * 100).toFixed(1)}% of 255 (${liveWorstWhat}) | ` +
`reduced-motion worst ${(rmWorst * 255).toFixed(0)}/255`);
`reduced-motion worst ${(rmWorst * 255).toFixed(0)}/255 | ${M.tag} | ` +
`${CP.fmt(flashWorst)} (${flashWhat})`);
const verdict = !ok ? 'FAIL' : (notApplicable.length ? 'NOT_APPLICABLE' : 'PASS');
console.log(verdict === 'NOT_APPLICABLE' ? 'NOT APPLICABLE' : verdict);
console.log(`RESULT: ${verdict} ${SKY}`);
console.log(`RESULT: ${verdict} ${SKY} ${M.comp ? 'composite' : 'lum'} ${COLS}x${ROWS}`);
process.exit(verdict === 'PASS' ? 0 : verdict === 'FAIL' ? 1 : 3);

View file

@ -1,5 +1,5 @@
/* Render one frame with no browser. Usage:
node tools/headless.cjs [seed] [frame] [cols] [rows] [--cold] > f.txt
node tools/headless.cjs [seed] [frame] [cols] [rows] [--cold] [--cell=WxH] [--under=k] > f.txt
Loads whatever src modules exist, so it stays useful while the build is half-written.
THIS HARNESS REPLAYS THE WHOLE FRAME, NOT JUST THE UPDATES. See the replay loop below: until
@ -66,6 +66,8 @@ if (wxArg && CC.Weather) CC.Weather.set(wxArg.slice(10), 0);
clock runs on a 420 s cycle, so a fixture that wants noon cannot wait for it. */
const tmArg = flags.find(a => a.slice(0, 7) === '--time=');
const TIME = tmArg ? tmArg.slice(7) : null;
const unArg = flags.find(a => a.slice(0, 8) === '--under=');
if (unArg && CC.Compose) CC.Compose.UNDER = parseFloat(unArg.slice(8)) || 0;
const f = CC.makeFrame(cols, rows);
const t = frameN / 60;
@ -78,6 +80,14 @@ const cam = {
z: city && city.startZ !== undefined ? city.startZ : 0.5,
yaw: 0, eyeY: 1.7, fov: 1.25, horizon: rows * 0.56, scale: rows * 0.9, t: t
};
/* --cell=WxH: the cell the frame will be PRINTED on, which the caster needs as well as the printer
— raycast reads cam.cellAspect for the vertical scale and frame.D, and D sizes the spill box, the
bloom radii and the optics. Left at the 9x16 default, a 300-column dump was cast at D 1.50 while
the browser's 6x11 cell (cellCSS 6.4, dpr 1) casts it at 1.45 and topng --cell=6x11 prints it at
1.45. Pass the same --cell to both tools and the three agree. Unlike --yaw this is the browser's
own frame, just at a cell this harness does not assume. */
const cellArg = flags.find(a => a.slice(0, 7) === '--cell=');
if (cellArg) { const m = /^(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)$/.exec(cellArg.slice(7)); if (m) cam.cellAspect = m[1] / m[2]; }
// The camera advance MUST come from the city itself, exactly as main.js drives it. An earlier
// version of this harness advanced cam.z here on its own, which faked motion the browser never
// had and hid a shipped bug where the walk never started at all.
@ -104,6 +114,7 @@ function renderAt(kt) {
cam.t = kt;
CC.clearFrame(f);
if (CC.Cast) CC.Cast.render(f, cam, city);
if (CC.Compose && CC.Compose.world) CC.Compose.world(f);
for (const el of els) if (el.draw) el.draw(f, cam, kt);
if (CC.Compose && CC.Compose.post) CC.Compose.post(f, cam, kt);
}
@ -192,6 +203,16 @@ for (let y = 0; y < rows; y++) {
}
out.push(line.join(' '));
}
/* THE UNDERPAINTING, as one line after the cells: cols*rows `r,g,b` triples, row-major, the format
tools/topng.py --u reads. Written ONLY when the field is non-zero, so a frame rendered with
CC.Compose.UNDER = 0 (the kill switch) dumps byte-for-byte what this harness dumped before the
field existed, and every fixture diffed against an old dump still diffs clean. --under=<k> sets
the strength for a tuning render; it is a browser knob too, so unlike --yaw it is a real frame. */
if (f.under && f.under.some(v => v)) {
const u = f.under, s = [];
for (let i = 0; i < f.n; i++) s.push(u[i * 3] + ',' + u[i * 3 + 1] + ',' + u[i * 3 + 2]);
out.push('UNDER ' + s.join(' '));
}
process.stdout.write(out.join('\n') + '\n');
/* The exposure gain is reported on stderr because it is the one thing about this frame that no
census of the dump can recover: it is a scalar already multiplied into every lum, so a reader

View file

@ -1,6 +1,19 @@
/* PHOTOSENSITIVITY REGRESSION TEST for src/elements/weather.js's lightning.
*
* node tools/lightning-rate.cjs [seed] [seconds]
* node tools/lightning-rate.cjs [seed] [seconds] [--sky=storm] [--composite] [--cols=60] [--rows=20]
*
* --composite IS A DIFFERENT SCENE, NOT JUST A DIFFERENT SUM, and that is deliberate. The flat wall
* below is white structure, and white does not emit: on it the underpainting cannot move at all —
* its mass term reads the world snapshot taken before the stroke, and its spill only fires on the
* emitting swatches — so a composite measured there would be a green light about a wall the stroke
* cannot reach through the wash. The way a stroke DOES reach it is a lit sign: the flash adds lum
* to an amber or azure cell, the cell crosses the spill's threshold, and the pool round it brightens
* with the stroke. So in composite mode the backdrop is the REAL world pass at the start pose, at
* night (the darkest baseline is the largest relative flash), rendered once and held, and only the
* lightning element is drawn over it. The series is the mean light the screen EMITS above that
* held frame, per tools/composite.cjs, and the same two envelope rules are applied to it. Both
* modes also run the area-weighted WCAG general-flash check on what prints, because lightning is
* the one event in the build that lights the whole viewport at once.
*
* Drives the real element against a synthetic uniform wall, so what comes out is the element's own
* intensity envelope with no city geometry modulating it, sampled once per 60 Hz frame. It prints
@ -59,6 +72,10 @@ for (const rel of ['src/world.js', 'src/proj.js', 'src/daylight.js', 'src/weathe
const edir = path.join(root, 'src/elements');
for (const fn of fs.readdirSync(edir).sort()) if (fn.endsWith('.js')) require(path.join(edir, fn));
const CC = global.CC;
const CP = require('./composite.cjs')(CC), M = CP.mode(process.argv, 60, 20);
/* init() sees the dimensions the shipped run has always handed it unless a size was asked for: the
* elements share one rng, and a different deal upstream would be a different storm seed here. */
const SIZED = process.argv.some(a => /^--(cols|rows)=/.test(a));
const MIN_PEAK_GAP = 0.34; // seconds
const MAX_FRAME_STEP = 0.34; // fraction of the stroke's peak
@ -86,33 +103,59 @@ function pinSky() {
P.name = P.from = P.to = PIN.name; P.blend = 1;
}
const els = CC.ELEMENTS.filter(function (e) { return CC.inWorld(e, CC.World.id); }).sort((a, b) => (a.layer | 0) - (b.layer | 0));
for (const el of els) if (el.init) el.init(city, rng, { cols: 200, rows: 60 });
for (const el of els) if (el.init) el.init(city, rng, SIZED ? { cols: M.cols, rows: M.rows } : { cols: 200, rows: 60 });
const lg = els.find(e => e.name === 'lightning');
if (!lg) { console.error('no lightning element'); process.exit(2); }
/* A flat wall at 8 m filling the frame. Every cell is eligible, so the sum of what the element adds
* is proportional to its intensity and nothing else. */
const f = CC.makeFrame(60, 20);
const f = CC.makeFrame(M.cols, M.rows);
const cam = { x: city.startX, z: city.startZ, yaw: 0, eyeY: 1.7, fov: 1.25,
horizon: 11.2, cellAspect: 0.5625, t: 0 };
horizon: M.rows * 0.56, cellAspect: 0.5625, t: 0 };
const N = SECS * 60, S = new Float64Array(N);
/* COMPOSITE: the held backdrop (see the header). Rendered once, at night, through the same caster
* main.js uses, and copied into the frame each tick so the stroke is the only thing that changes. */
const KS = ['ch', 'col', 'lum', 'dist', 'kind'], HELD = CC.makeFrame(M.cols, M.rows);
const V = new Float32Array(f.n), Y = new Float32Array(f.n), Y0 = new Float32Array(f.n), fl = CP.Flash(M.cols, M.rows);
function fill() {
if (M.comp) { for (const k of KS) f[k].set(HELD[k]); f.D = HELD.D; CC.Compose.world(f); }
else for (let i = 0; i < f.n; i++) { f.ch[i] = 1; f.col[i] = 5; f.lum[i] = 40; f.dist[i] = 8; f.kind[i] = 1; }
}
let base = 0;
if (M.comp) {
if (CC.Daylight) CC.Daylight.set('night', 0);
CC.clearFrame(HELD); CC.Cast.render(HELD, cam, city);
}
fill(); CC.Compose.post(f, cam, 0); CP.light(f, V, Y0);
for (let i = 0; i < f.n; i++) base += V[i];
base /= f.n;
for (let k = 0; k < N; k++) {
const t = k / 60;
/* The director is ticked in lockstep, exactly as main.js does it, because the element reads the
* live P block every frame and a stale one would freeze the storm ramp mid-transition. */
if (CC.Weather) { CC.Weather.update(1 / 60, t); pinSky(); }
lg.update(1 / 60, t, cam);
for (let i = 0; i < f.n; i++) { f.ch[i] = 1; f.col[i] = 5; f.lum[i] = 40; f.dist[i] = 8; f.kind[i] = 1; }
fill();
lg.draw(f, cam, t);
let sum = 0; for (let i = 0; i < f.n; i++) sum += f.lum[i] - 40;
S[k] = sum / f.n;
/* A frame the stroke did not touch is the held frame, and its light is already known: the print
* pass runs only when something moved, which is one tick in fifty under a storm. */
let moved = false;
if (M.comp) { for (let i = 0; i < f.n && !moved; i++) moved = f.lum[i] !== HELD.lum[i] || f.ch[i] !== HELD.ch[i]; }
else { let sum = 0; for (let i = 0; i < f.n; i++) sum += f.lum[i] - 40; S[k] = sum / f.n; moved = sum !== 0; }
if (!moved) { fl.push(Y0); continue; }
CC.Compose.post(f, cam, t); CP.light(f, V, Y); fl.push(Y);
if (M.comp) { let sum = 0; for (let i = 0; i < f.n; i++) sum += V[i]; S[k] = sum / f.n - base; }
}
const FL = fl.result();
console.log(`frames: ${M.tag}${M.comp ? ', held night backdrop at the start pose, light emitted above it' : ''}`);
console.log(CP.fmt(FL) + (FL.bad ? ' FAIL (general flash)' : ' ok'));
let bi = 0; for (let k = 0; k < N; k++) if (S[k] > S[bi]) bi = k;
/* An empty window is NOT a pass, and it used to exit 0 right here — see the exit-code table at the
* top. The flag is carried down instead so that the sky-rate census below still runs and still
* prints (it reports the honest zeros), and the verdict is decided once, at the bottom. */
const NOSTRIKE = S[bi] <= 0;
const UNIT = M.comp ? 'added light emitted per cell, display 0..255' : 'added luminance per cell';
const a = Math.max(0, bi - 8), b = Math.min(N, bi + 84);
/* HOW OFTEN, across the WHOLE window, not just inside the one stroke printed below. The per-stroke
@ -150,12 +193,12 @@ if (NOSTRIKE) {
`NOT exercised — nothing to measure, so nothing is verified. Try another seed, or a ` +
`sky whose P.storm is non-zero (storm, rain, drizzle) if you meant to test them.`);
console.log('NOT APPLICABLE');
console.log(`RESULT: NOT_APPLICABLE ${SKY}`);
console.log(`RESULT: NOT_APPLICABLE ${SKY} ${M.comp ? 'composite' : 'lum'} ${M.cols}x${M.rows}`);
process.exit(3);
}
console.log(`seed ${seed}: strongest stroke peaks at t=${(bi / 60).toFixed(2)}s.`);
console.log('added luminance per cell, one value per 60 Hz frame:');
console.log(UNIT + ', one value per 60 Hz frame:');
const ser = []; for (let k = a; k < b; k++) ser.push(S[k].toFixed(2).padStart(6));
for (let i = 0; i < ser.length; i += 12) console.log(' ' + ser.slice(i, i + 12).join(''));
@ -164,7 +207,7 @@ for (let k = a + 1; k < b - 1; k++)
if (S[k] >= S[k - 1] && S[k] > S[k + 1] && S[k] > S[bi] * 0.05) pk.push(k);
console.log('maxima above 5% of peak: ' + (pk.map(k => (k / 60).toFixed(3) + 's').join(', ') || 'one only'));
let ok = !rateBad;
let ok = !rateBad && !FL.bad;
for (let i = 1; i < pk.length; i++) {
const dt = (pk[i] - pk[i - 1]) / 60;
const bad = dt < MIN_PEAK_GAP;
@ -184,5 +227,5 @@ console.log(`largest single-frame step ${(ms * 100).toFixed(1)}% of peak at t=${
console.log(` stroke peak ${(100 * S[bi] / 255).toFixed(1)}% of full scale; that step is ` +
`${(100 * ms * S[bi] / 255).toFixed(2)}% of full scale`);
console.log(ok ? 'PASS' : 'FAIL');
console.log(`RESULT: ${ok ? 'PASS' : 'FAIL'} ${SKY}`);
console.log(`RESULT: ${ok ? 'PASS' : 'FAIL'} ${SKY} ${M.comp ? 'composite' : 'lum'} ${M.cols}x${M.rows}`);
process.exit(ok ? 0 : 1);

View file

@ -12,6 +12,20 @@ the current tools/headless.cjs writes. Two agents worked around it with throwawa
rather than fixing it; the fix is the two lines below and a kind breakdown for free.
python3 tools/metrics.py f.txt [more.txt ...]
python3 tools/metrics.py --composite [--cell=WxH] [--u=k] f.txt [more.txt ...]
Everything main() prints is the GLYPH-LAYER census: lum x swatch per cell, scored as if every
glyph were a solid block. It is kept byte-for-byte as it was, because every target in core.js and
every historical report is written in its units. It cannot see two things the screen does: a
glyph covers about a fifth of its cell, and an underpainting (the dump's UNDER line) lights cells
that have no glyph at all. --composite therefore adds a second census per file, in two halves:
ink what the data says will print -- coverage(glyph) x lum x swatch (tools/cov.json), plus the
UNDER field's brightest channel -- as a per-cell mean, so a change can be judged before
anyone renders it;
print what the browser shows, measured on tools/topng.py's composite (calibrated against a
Chromium screenshot): luma mean/p50/p90/p99, black share, the zenith band (top tenth of
the frame, where night must stay dark) and the mean by cell kind.
The UNDER line is drawn at strength 1 when present; --u=k scales it and --u=0 leaves it out.
"""
import sys, json
@ -94,5 +108,47 @@ def main(srcs):
f"{KINDS[i]} {kinds[i]/tot_cell*100:.1f}% (lit {kindLit[i]/tot_cell*100:.1f}%)"
for i in range(len(KINDS))))
def composite(srcs, cell=(9, 16), u=1.0):
"""The composite census. Imported lazily: the glyph census must keep running where numpy and
PIL are not installed, which is everywhere the old script ran."""
import os
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import topng
cov = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cov.json')))['cov']
print(f"COMPOSITE census cell {topng.cw_s(cell)} UNDER x{u:g}")
for src in srcs:
a, I = topng.render(src, cell, u if u > 0 else None, 2, True)
cells, pal, G, U = I['cells'], I['pal'], I['glyphs'], I['U']
miss = sorted({G[c] for c in np.unique(cells[..., 0]) if c and G[c] not in cov})
if miss: sys.exit(f"metrics: no coverage for {miss!r} -- regenerate tools/cov.json "
"(python3 tools/topng.py f.txt --cov > tools/cov.json)")
cv = np.array([cov.get(g, 0.0) for g in G]); g, lu = cells[..., 0], cells[..., 2]
solid = pal[cells[..., 1] % len(pal)].max(axis=2) * lu / 255 * ((g > 0) & (lu >= 4))
ink = solid * cv[g]
und = U.max(axis=2) * u if U is not None and u > 0 else np.zeros_like(ink)
s = topng.stats(a)
y = a.astype(float) @ np.array([0.2126, 0.7152, 0.0722])
zen = y[:max(1, y.shape[0] // 10)].mean()
# Per-cell print, by the cell's kind: mean luma of each cell's own block of pixels.
rows, cols = cells.shape[:2]; H, W = y.shape
cy = (np.arange(H) * rows // H)[:, None]; cx = (np.arange(W) * cols // W)[None, :]
kd = cells[..., 3][cy, cx]
byk = " ".join(f"{KINDS[k]} {y[kd == k].mean():.1f}" for k in range(len(KINDS)) if (kd == k).any())
print(f"{src}")
print(f" ink glyph {ink.mean():6.2f} under {und.mean():6.2f} total {ink.mean()+und.mean():6.2f}"
f" (ink/solid {ink.sum()/max(solid.sum(), 1):.3f} under share "
f"{und.sum()/max(ink.sum()+und.sum(), 1e-9)*100:.0f}%{'' if U is not None else ' no UNDER line'})")
print(f" print {topng.fmt(s)} zenith {zen:.1f}")
print(f" print by kind (mean luma): {byk}")
if __name__ == '__main__':
main(sys.argv[1:])
A = sys.argv[1:]; srcs = [a for a in A if not a.startswith('--')]
fl = dict((a[2:].split('=', 1) + [None])[:2] for a in A if a.startswith('--'))
if 'composite' in fl:
print("GLYPH-LAYER census (lum x swatch, every glyph scored as a solid cell)")
main(srcs)
if 'composite' in fl:
c = (fl.get('cell') or '9x16').split('x')
composite(srcs, tuple(float(v) if '.' in v else int(v) for v in c),
float(fl['u']) if fl.get('u') else 1.0)

View file

@ -53,6 +53,9 @@ for (let k = 0; k <= N; k++) ped.update(1 / 60, k / 60, cam(k / 60));
CC.clearFrame(f);
ped.draw(f, cam(N / 60), N / 60);
/* Lum only: this tool counts printed glyphs and never reads f.under, so the underpainting is off
for the run — and it draws no world pass, so post() would otherwise snapshot the crowd itself. */
CC.Compose.UNDER = 0;
CC.Compose.post(f);
let lit = 0;

View file

@ -26,14 +26,19 @@
* 0.00 for a feature that was not on screen — the failure CONTRACT.md's newest rule is about. The
* reduced-motion row must come back exactly still: `rp` is gated on CC.reducedMotion at source.
*
* node tools/road-flicker.cjs
* node tools/road-flicker.cjs [--composite] [--cols=120] [--rows=40]
*
* --composite scores the light each cell EMITS (tools/composite.cjs) and grows the road mask by the
* underpainting's spill box, because a puddle that flickers a reflected sign lights the kerb and
* the wall foot with it. Both modes run the WCAG general-flash check, absolute.
*/
const R=require('path').join(__dirname,'..')+'/',fs=require('fs');
global.CC=require(R+'src/core.js');global.window=undefined;
['world','proj','daylight','weather_state','city','surfaces','raycast','control'].forEach(m=>require(R+'src/'+m+'.js'));
fs.readdirSync(R+'src').sort().forEach(p=>{if(/^surf_.*\.js$/.test(p))require(R+'src/'+p)});
fs.readdirSync(R+'src/elements').sort().forEach(p=>require(R+'src/elements/'+p));
const COLS=120,ROWS=40,WARM=360,NF=WARM+600,PROBES=[3.5,5,7,9,12,15,19];
const CP=require('./composite.cjs')(CC),M=CP.mode(process.argv,120,40);
const COLS=M.cols,ROWS=M.rows,WARM=360,NF=WARM+600,PROBES=[3.5,5,7,9,12,15,19];
const BIG=255/3, RATE_CAP=1.00, BAND_CAP=2.00;
function goertzel(x,f){const n=x.length,w=2*Math.PI*f/60,c=2*Math.cos(w);let s1=0,s2=0,m=0;
for(let i=0;i<n;i++)m+=x[i];m/=n;
@ -57,18 +62,21 @@ function run(preset,seed,reduced){
if(!found) return null;
const drawn=live.filter(e=>e.world&&CC.inWorld(e,'japan')&&!CC.inWorld(e,'cyber'));
const f=CC.makeFrame(COLS,ROWS),N=COLS*ROWS,keep=NF-WARM,s=new Uint8Array(N*keep);
const V=new Float32Array(N),Y=new Float32Array(N),fl=CP.Flash(COLS,ROWS);
for(let k=0;k<NF;k++){const t=(pin+k)/60;
if(!CC.Weather.P.forced)CC.Weather.set(preset,t);
CC.Daylight.update(1/60,t);CC.Weather.update(1/60,t);
for(const el of live) if(el.update) el.update(1/60,t,cam);
cam.t=t;CC.clearFrame(f);CC.Cast.render(f,cam,city);
if(M.comp)CC.Compose.world(f); // the underpainting's world snapshot, where main.js takes it
for(const el of drawn) if(el.draw) el.draw(f,cam,t);
if(CC.Compose&&CC.Compose.post)CC.Compose.post(f,cam,t);
if(k>=WARM){const b=(k-WARM)*N;for(let i=0;i<N;i++)s[b+i]=f.lum[i];}
if(k>=WARM){const b=(k-WARM)*N,src=M.comp?V:f.lum;CP.light(f,V,Y);fl.push(Y);for(let i=0;i<N;i++)s[b+i]=src[i]+0.5;}
}
/* The road is the FLOOR below the horizon, which is what kind 2 means here. */
let road=0,lit=0;const isRoad=new Uint8Array(N);
let road=0,lit=0,isRoad=new Uint8Array(N);
for(let i=0;i<N;i++){const rz=(i/COLS)|0; if(f.kind[i]===2&&rz>ROWS*0.56){isRoad[i]=1;road++;}}
if(M.comp)isRoad=CP.dilate(isRoad,COLS,ROWS,f.D);
let big=0,band=0,worst=0;const x=new Float64Array(keep);
for(let i=0;i<N;i++){ if(!isRoad[i]) continue;
let b=0,mx=0,prev=s[i];x[0]=prev;let anyLit=0;
@ -79,15 +87,15 @@ function run(preset,seed,reduced){
const r=b/(keep/60); if(r>big)big=r;
for(const pf of PROBES){const a=goertzel(x,pf); if(a>band)band=a;}
}
return {road,lit,worst:100*worst/255,big,band:100*band/255,pin};
return {road,lit,worst:100*worst/255,big,band:100*band/255,pin,flash:fl.result()};
}
console.log(`road puddle rate gate — ${COLS}x${ROWS}, ${(NF-WARM)/60}s measured, ${WARM} discarded, pinned >28 m from the channel\n`);
console.log(`road puddle rate gate — ${M.tag}, ${(NF-WARM)/60}s measured, ${WARM} discarded, pinned >28 m from the channel\n`);
const rows=[];
for(const seed of [42,3,404]) for(const p of ['tsuyu','typhoon']){
const r=run(p,seed,false); rows.push(r);
console.log(` seed ${String(seed).padStart(4)} ${p.padEnd(8)}` + (!r ? '(never left the channel)' :
`roadCells ${String(r.road).padStart(4)}(${String(r.lit).padStart(4)} lit) worstStep ${r.worst.toFixed(1).padStart(5)}% ` +
`bigSteps ${r.big.toFixed(2).padStart(5)}/s 3-20Hz ${r.band.toFixed(2).padStart(5)}% pinned f${r.pin}`));
`bigSteps ${r.big.toFixed(2).padStart(5)}/s 3-20Hz ${r.band.toFixed(2).padStart(5)}% pinned f${r.pin}\n ${CP.fmt(r.flash)}`));
}
const rm=run('typhoon',42,true);
console.log(`\n reduced motion: ` + (!rm ? '(not reached)' :
@ -95,9 +103,11 @@ console.log(`\n reduced motion: ` + (!rm ? '(not reached)' :
const seen=rows.filter(r=>r&&r.lit>0);
if(!seen.length){console.log('\nRESULT: NOT_MEASURED — no pose put lit road in frame; this is the probe failing, not a PASS');process.exit(3);}
const wBig=Math.max(...seen.map(r=>r.big)),wBand=Math.max(...seen.map(r=>r.band));
/* the flash rule is absolute and is judged on every row that rendered, the reduced-motion one included */
const wFl=rows.concat([rm]).filter(Boolean).reduce((a,r)=>r.flash.area>a.area||(r.flash.area===a.area&&r.flash.swing>a.swing)?r.flash:a,seen[0].flash);
const rmBad=rm&&(rm.big>0||rm.band>0.5);
const bad=(wBig>RATE_CAP?` big steps ${wBig.toFixed(2)}/s over ${RATE_CAP.toFixed(2)}/s`:'')+
(wBand>BAND_CAP?` 3-20Hz ${wBand.toFixed(2)}% over ${BAND_CAP.toFixed(2)}%`:'')+
(rmBad?' reduced motion is not still':'');
console.log(`\nRESULT: ${bad?'FAIL'+bad:'PASS'} (worst big steps ${wBig.toFixed(2)}/s, worst 3-20Hz ${wBand.toFixed(2)}%, ${seen.length}/${rows.length} rows measured)`);
(rmBad?' reduced motion is not still':'')+(wFl.bad?' general flash':'');
console.log(`\nRESULT: ${bad?'FAIL'+bad:'PASS'} (worst big steps ${wBig.toFixed(2)}/s, worst 3-20Hz ${wBand.toFixed(2)}%, ${seen.length}/${rows.length} rows measured; ${CP.fmt(wFl)})`);
process.exit(bad?1:0);

View file

@ -37,6 +37,11 @@
* unjudged run is the defect this scheme exists to prevent. The RESULT line always says which.
*
* usage: node tools/sakura-flicker.cjs [seconds] [element] [--time=<hour>] [--cells=<n>]
* [--composite] [--cols=120] [--rows=40]
* --composite scores the light each cell EMITS (tools/composite.cjs) over the owned cells GROWN by
* the underpainting's spill box; the pin threshold and the lit count stay on what the glyphs print,
* because those two answer "is the tree in shot", which the wash behind it cannot. Both modes run
* the WCAG general-flash check, absolute, over the whole frame.
* --cells is how many cells of the target must PRINT (v >= 9) before the walk pins. It counts
* what prints and NOT what the element owns — see the note above the search loop — and it is a
* REQUIRED knob rather than a constant because the two things this probe is aimed at differ by
@ -73,9 +78,10 @@ if (SECONDS < 4) console.error('sakura-flicker: WARNING — under 4 s the 3-20 H
global.CC = require(R + 'src/core.js');
global.window = undefined;
const CP = require('./composite.cjs')(CC), M = CP.mode(process.argv, 120, 40);
/* ---- the wrapper, installed before ANY consumer caches it ---------------------------------- */
let TAG = null, OWNED = null, COLS = 120, ROWS = 40;
let TAG = null, OWNED = null, COLS = M.cols, ROWS = M.rows;
const rawPut = CC.put;
/* ATTRIBUTION IS CC.put's OWN RETURN VALUE and nothing else. put depth-tests, and it already tells
* the caller whether the write landed, so "did this element end up owning this cell" is answered
@ -243,7 +249,9 @@ function run(preset, seed, reduced, pinned) {
Nothing else moves: Control.update is not called in this loop, so the camera stays pinned;
`keep`, `WARM` and the sampling index are untouched; and the pinned baseline run has
pinFrame = 0, so its numbers are byte-identical to before. */
const keep = NF - WARM, s = new Uint8Array(N * keep), mask = new Uint8Array(N);
const keep = NF - WARM, s = new Uint8Array(N * keep), litc = new Uint8Array(N);
let mask = new Uint8Array(N);
const V = new Float32Array(N), Y = new Float32Array(N), fl = CP.Flash(COLS, ROWS);
for (let k = 0; k < NF; k++) {
const t = (pinFrame + k) / 60;
if (!CC.Weather.P.forced) CC.Weather.set(preset, t);
@ -251,6 +259,7 @@ function run(preset, seed, reduced, pinned) {
CC.Daylight.update(1 / 60, t); CC.Weather.update(1 / 60, t);
for (const el of live) if (el.update) el.update(1 / 60, t, cam);
cam.t = t; CC.clearFrame(f); CC.Cast.render(f, cam, city);
if (M.comp) CC.Compose.world(f); // the underpainting's world snapshot, where main.js takes it
for (const el of rest) if (el.draw) el.draw(f, cam, t);
OWNED.fill(0); TAG = TARGET;
for (const el of tgt) if (el.draw) el.draw(f, cam, t);
@ -259,20 +268,26 @@ function run(preset, seed, reduced, pinned) {
leaves is precisely the transient this gate is for, and a per-frame mask would drop it. */
for (let i = 0; i < N; i++) if (OWNED[i]) mask[i] = 1;
if (CC.Compose && CC.Compose.post) CC.Compose.post(f, cam, t);
if (k >= WARM) { const b = (k - WARM) * N; for (let i = 0; i < N; i++) s[b + i] = f.lum[i]; }
if (k >= WARM) {
const b = (k - WARM) * N, src = M.comp ? V : f.lum;
CP.light(f, V, Y); fl.push(Y);
for (let i = 0; i < N; i++) { s[b + i] = src[i] + 0.5; if (f.lum[i] >= 9) litc[i] = 1; }
}
}
const own = mask;
if (M.comp) mask = CP.dilate(mask, COLS, ROWS, f.D);
let cells = 0, lit = 0, big = 0, band = 0, worst = 0;
const x = new Float64Array(keep);
for (let i = 0; i < N; i++) {
if (!mask[i]) continue;
cells++;
if (own[i]) cells++;
/* OWNED IS NOT THE SAME AS SEEN, WHICH IS WHY THE PIN THRESHOLD COUNTS PRINTING CELLS AND
NOT OWNED ONES (see the search loop). proj.js's
emit() calls put for a cell fogged to lum 0 — real occluding mass that the element does own —
so about half a crown's owned cells print nothing, and a threshold met on those is met on
something invisible. Both counts are printed so the row cannot overstate what is on screen. */
for (let k = 0; k < keep; k++) if (s[k * N + i] >= 9) { lit++; break; }
if (own[i] && litc[i]) lit++;
let b = 0, mx = 0, prev = s[i];
for (let k = 1; k < keep; k++) {
const v = s[k * N + i], d = Math.abs(v - prev);
@ -286,10 +301,10 @@ function run(preset, seed, reduced, pinned) {
if (mx > worst) worst = mx;
for (const fq of PROBES) { const a = goertzel(x, fq); if (a > band) band = a; }
}
return { cells, lit, worst: 100 * worst / 255, big, band: 100 * band / 255, pinFrame };
return { cells, lit, worst: 100 * worst / 255, big, band: 100 * band / 255, pinFrame, flash: fl.result() };
}
console.log(`sakura rate gate — ${TARGET}, ${COLS}x${ROWS}, ${SECONDS}s measured of ${NF} frames, ` +
console.log(`sakura rate gate — ${TARGET}, ${M.tag}, ${SECONDS}s measured of ${NF} frames, ` +
`${WARM} discarded, pin at >=${NEED} PRINTING cells (v>=9)` +
`${HOUR !== '' ? ', hour ' + HOUR : ''}\n`);
const rows = [];
@ -302,7 +317,7 @@ for (const seed of [42, 3, 404])
? `(no crown reached — best ${r.cells} cells)`
: `cells ${String(r.cells).padStart(4)}(${String(r.lit).padStart(3)} lit) worst step ${r.worst.toFixed(1).padStart(5)}% ` +
`big steps ${r.big.toFixed(2).padStart(5)}/s 3-20Hz ${r.band.toFixed(2).padStart(5)}% ` +
`pinned f${String(r.pinFrame).padStart(5)}${r.pinFrame === 0 ? ' (DID NOT WALK)' : ''}`));
`pinned f${String(r.pinFrame).padStart(5)}${r.pinFrame === 0 ? ' (DID NOT WALK)' : ''}\n ${CP.fmt(r.flash)}`));
}
const pin = run('kiri', 42, false, true);
console.log(`\n pinned at start (what west-flicker sees): cells ${pin.cells}`);
@ -331,6 +346,10 @@ if (thin.length) {
}
const wBig = Math.max(...seen.map(r => r.big)), wBand = Math.max(...seen.map(r => r.band));
const rmBad = !rm.notFound && (rm.big > 0 || rm.band > 0.5);
/* The flash rule is ABSOLUTE and has no reference window: it counts transitions inside each
second, so it is judged at any length — every measured row, the reduced-motion one included. */
const wFl = seen.concat(rm.notFound ? [] : [rm]).reduce((a, r) => r.flash.area > a.area ||
(r.flash.area === a.area && r.flash.swing > a.swing) ? r.flash : a, seen[0].flash);
const judging = SECONDS === REF_WINDOW;
/* A BIG-STEP RATE IS NOT A FLASH RATE, and the RESULT line has to say so or the two get quoted
as if they were the same number. `big` counts frame-to-frame jumps over 85/255 on the worst
@ -345,15 +364,17 @@ const bad = judging
`${RATE_CAP.toFixed(2)}/s (~${impliedHz.toFixed(2)} Hz of switching; the project's own ` +
`backstop is 8.0/s and its flash band starts at 3 Hz)` : '') +
(wBand > BAND_CAP ? ` 3-20Hz ${wBand.toFixed(2)}% over ${BAND_CAP.toFixed(2)}%` : '') +
(rmBad ? ' reduced motion is not still' : ''))
: '';
(rmBad ? ' reduced motion is not still' : '') + (wFl.bad ? ' general flash' : ''))
: (wFl.bad ? ' general flash' : '');
const walked = seen.filter(r => r.pinFrame > 0).length;
const wLit = Math.min(...seen.map(r => r.lit)); // the thinnest row a verdict was taken on
console.log(`\nRESULT: ${!judging ? 'NOT_JUDGED' : bad ? 'FAIL' + bad : 'PASS'} ` +
console.log(`\nRESULT: ${bad ? 'FAIL' + bad : !judging ? 'NOT_JUDGED' : 'PASS'} ` +
`(worst big steps ${wBig.toFixed(2)}/s, worst 3-20Hz ${wBand.toFixed(2)}%` +
`${judging ? '' : `; both PRINTED NOT JUDGED — a verdict is only taken at the ${REF_WINDOW}s reference window`}` +
`, i.e. ~${impliedHz.toFixed(2)} Hz of switching on the worst cell` +
`, over a ${SECONDS}s window; thinnest row ${wLit} lit cells; ${walked}/${seen.length} rows walked off the start pose` +
`${rm.notFound ? '; reduced-motion row found nothing — frozen by design, NOT a measured pass' : ''})`);
`${rm.notFound ? '; reduced-motion row found nothing — frozen by design, NOT a measured pass' : ''}` +
`; ${CP.fmt(wFl)}; ${M.tag})`);
if (bad) process.exit(1);
if (!judging) process.exit(3);
process.exit(bad ? 1 : 0);

View file

@ -1,16 +1,83 @@
#!/usr/bin/env python3
"""Render a headless CyberCity frame to a PNG, with the same bloom the canvas applies."""
import sys, json
from PIL import Image, ImageDraw, ImageFont, ImageFilter
"""Render a headless CyberCity frame to a PNG the way the browser canvas prints it, and say what
it printed.
CW, CH = 9, 16
# Liberation Mono Bold at 15 px in a 9x16 cell is the reference print, and it is what
# render_canvas.js's atlas bakes and what surf_west.js's INK ramp was measured against — so it is
# tried FIRST and every fallback below is a degradation that changes the ink census. The list
# exists because this file is the standing verification procedure ("every change gets looked at
# this way before it ships") and it was unrunnable on macOS, where that path does not exist: a
# gate nobody can run is not a gate. Order is exact match, then the same metrics under another
# name, then anything monospace, then PIL's bitmap default.
python3 tools/topng.py f.txt out.png [--cell=WxH] [--u[=k]] [--q=0|1|2] [--bloom=ref|cell]
python3 tools/topng.py f.txt --cov > tools/cov.json
THIS IS THE ONE VERIFICATION PRINTER. Every lever that ever argued about "how bright is the night"
argued from a PNG this file made, and until it was rebuilt this file did not composite the way the
browser does: it alpha-blended the glow over the scene at 0.5, which halves every glyph core,
while render_canvas.js ADDS the glow ('lighter') on top of a full-strength scene. Two prototypes
measured the same cyber night at mean 4.3 and 22.9 because each had patched that blend its own way,
and a design decision taken from either number would have been taken from a printing artefact. So
the pipeline below is a transcription of render_canvas.js, step for step, and it is held to a real
Chromium screenshot of the same frame (±2 mean, ±5 p99 -- see "calibration" below):
1. glyph pass. A coverage mask per glyph is baked exactly as buildAtlas() bakes its tiles: font px
= min(cellW / advance('M'), cellH * 0.98), centred on the advance, baseline centring the ink
box of 'Xg', clipped to the cell. A cell prints PALETTE[col] * coverage * lum/255 onto black,
which is what source-over with globalAlpha does on a black destination. lum < 4 is skipped
(LUM_FLOOR). The background is #000, not the old print's (2,3,6): that tint alone pinned the
old black share at 0% and made every "negative space" number unmeasurable.
2. bloom reads the SCENE only (never the underpainting, so the blacks between lit cells stay
black): b2 = scene at 1/2, blurred rTight; b4 = b2 at 1/2; b8 = b4 at 1/2, blurred rWide;
out = scene + 0.55*up(b2) + 0.85*up(b8). --q=1 is the canvas's degraded single tap (b4 blurred
rMid, 0.95), --q=0 the bare scene -- which is the cleanest way to check glyph rasterisation
against the browser with no blur hiding the difference.
3. radii are the canvas's cell fractions (0.05 / 0.045 / 0.06 of the cell height, in each
buffer's own pixels, with its floors) computed from the REFERENCE cell height dh*D, where
D = max(1, cols*(cellW/cellH) / (200*0.5625)) is raycast's frame.D. A 360-column frame on a
5x9 cell therefore glows at the same physical size as a 200-column one on 9x16 instead of a
quarter of the area, which is the screen-relative bloom the HD plan ships. --bloom=cell uses
the bare cell height, i.e. the canvas as it was before that change; at 200 columns or fewer
D is 1 and the two are identical.
4. --u draws the frame's UNDER line first, nearest-neighbour upscaled (one flat block per cell:
a bilinear underpainting was tried and smeared the street into a violet haze), and the scene
and bloom are added over it. --u=k scales the field by k, for judging a strength by eye
without re-rendering the dump.
THE UNDER LINE. tools/headless.cjs appends it after the last cell row, only when the frame carries
a non-zero underpainting (CC.Compose.UNDER = 0 writes no line, so the dump stays byte-identical to
the pre-underpainting format):
UNDER r,g,b r,g,b ... cols*rows triples, row-major, 0..255 each, additive under glyphs
It is the craft prototype's format unchanged. A --u render of a dump with no UNDER line prints the
glyph composite and says so rather than failing, because "no line" legitimately means "UNDER=0".
Without --u the UNDER line is ignored and the print is the glyph composite alone -- the browser
with CC.Compose.UNDER = 0 -- which is the frame the calibration below holds to Chromium.
--cell=WxH may be fractional (5.6x10). The browser floors its cell to whole device pixels, so a
fractional cell is drawn at the smallest whole supersample (x5 for 5.6) and box-filtered down. It
is a sizing tool, not a browser match: only integer cells are calibrated.
Calibration, 2026-10-21: the same dumps screenshotted from Chromium's 2D canvas (headless, dpr 1,
pristine render_canvas.js at 7425bb2), luma mean / p99 / black, Chromium -> this file:
9x16, 200x60, quality 2 cyber dusk 16.7/209/66.4% -> 16.9/207/65.6% cyber night 17.7/217/66.6%
-> 18.0/216/65.8% west dusk 2.7/44/92.3% -> 2.8/45/92.1% west noon 27.7/202/28.6% ->
29.2/204/26.7% jp dusk 12.1/145 -> 12.4/144 jp night 11.5/161 -> 11.7/160 moon 10.0/181
-> 10.1/183. Bare glyph pass (--q=0) 7.45/141.2 -> 7.52/141.2, per-pixel error 0.6 levels.
small cells, 360x110, --bloom=cell 5x9 7.5/118 -> 7.3/107 6x11 7.5/122 -> 7.0/116
The means hold everywhere; p99 does NOT at cells under 9 px: Chromium hints tiny glyphs into
crisper, fuller stems than FreeType-in-PIL draws, so the brightest pixels print 5-11 levels short.
Judge HD frames by mean and black share, and confirm a p99 claim at those sizes in a browser.
Stats line: luma (Rec.709) mean / p50 / p90 / p99 of the printed pixels, and black = share of
pixels whose BRIGHTEST channel is under 8 -- the same cut the browser harness uses, so the two
can be compared line for line.
"""
import sys, json, math
import numpy as np
from PIL import Image, ImageDraw, ImageFont
# Liberation Mono Bold is the reference print, and it is what render_canvas.js's FAMILY resolves to
# first and what surf_west.js's INK ramp was measured against -- so it is tried FIRST and every
# fallback below is a degradation that changes the ink census. The list exists because this file
# is the standing verification procedure and it was unrunnable on macOS, where that path does not
# exist: a gate nobody can run is not a gate. Order is exact match, then the same metrics under
# another name, then anything monospace, then PIL's bitmap default.
_FONT_PATHS = [
"/usr/share/fonts/liberation-mono-fonts/LiberationMono-Bold.ttf",
"/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf",
@ -19,44 +86,161 @@ _FONT_PATHS = [
"/System/Library/Fonts/Menlo.ttc",
"/System/Library/Fonts/Supplemental/Courier New Bold.ttf",
]
FONT = None
_FP = None
for _p in _FONT_PATHS:
try:
FONT = ImageFont.truetype(_p, 15)
break
except OSError:
continue
if FONT is None:
try: ImageFont.truetype(_p, 15); _FP = _p; break
except OSError: continue
if _FP is None:
sys.stderr.write("topng: no mono TTF found, falling back to the bitmap default; "
"glyph ink will not match the print\n")
FONT = ImageFont.load_default()
def main(src, dst):
lines = open(src).read().split('\n')
assert lines[0].startswith('CCFRAME'), 'not a CCFRAME dump'
cols, rows = map(int, lines[1].split())
pal = [tuple(map(int, c.split(','))) for c in lines[2].split(' ', 1)[1].split()]
glyphs = json.loads(lines[3].split(' ', 1)[1])
im = Image.new('RGB', (cols * CW, rows * CH), (2, 3, 6))
d = ImageDraw.Draw(im)
lit = 0
def font(px):
return ImageFont.truetype(_FP, px) if _FP else ImageFont.load_default()
def load(src):
"""-> cols, rows, palette (N,3 float), glyph string, cells (rows,cols,4 int), under or None."""
L = open(src).read().split('\n')
assert L[0].startswith('CCFRAME'), 'not a CCFRAME dump'
cols, rows = map(int, L[1].split())
pal = np.array([tuple(map(int, c.split(','))) for c in L[2].split(' ', 1)[1].split()], float)
glyphs = json.loads(L[3].split(' ', 1)[1])
cells = np.zeros((rows, cols, 4), int)
for y in range(rows):
parts = lines[4 + y].split(' ')
for x in range(cols):
fld = parts[x].split(',') # CCFRAME 2 appends a kind byte; ignore it here
ch, ci, lu = int(fld[0]), int(fld[1]), int(fld[2])
if ch == 0 or lu == 0: continue
r, g, b = pal[ci % len(pal)]
k = lu / 255.0
d.text((x * CW, y * CH), glyphs[ch], font=FONT,
fill=(int(r * k), int(g * k), int(b * k)))
lit += 1
g1 = im.filter(ImageFilter.GaussianBlur(1.5))
g2 = im.filter(ImageFilter.GaussianBlur(5.0))
glow = Image.blend(g1, g2, 0.5)
im = Image.blend(im, Image.eval(glow, lambda v: min(255, int(v * 2.0))), 0.5)
im.save(dst)
print(f"{dst} {cols}x{rows} cells {lit/(cols*rows)*100:.1f}% lit")
for x, p in enumerate(L[4 + y].split(' ')[:cols]):
v = p.split(',') # CCFRAME 1 has three fields, 2 adds the kind byte
cells[y, x, :len(v)] = [int(t) for t in v[:4]]
U = next((l for l in L[4 + rows:] if l.startswith('UNDER ')), None)
if U is not None:
U = np.array([tuple(map(float, c.split(","))) for c in U.split(" ")[1:]], float)
U = U.reshape(rows, cols, 3)
return cols, rows, pal, glyphs, cells, U
def masks(glyphs, cw, ch):
"""Per-glyph coverage (NG, ch, cw) in 0..1 for an INTEGER cell, baked as buildAtlas bakes it."""
adv = font(100).getlength('M') / 100 or 0.6
px = min(cw / adv, ch * 0.98)
b = font(px).getbbox('Xg', anchor='ls') # (l, -ascent, r, descent) about the baseline
# floor(x+.5), not round(): Python rounds halves to even and JS's Math.round rounds them up,
# and at 5x9 the baseline lands exactly on a half -- the whole lattice printed a row high.
base = min(ch - 1, max(1, math.floor((ch + b[1] - b[3]) * 0.5 - b[1] + 0.5)))
# PIL snaps the font to a WHOLE ppem (8.33 px prints at 8, 11.66 at 12) where Skia keeps the
# fraction. px is cellW*5/3 for this family, so a fractional size is drawn at 3x -- an exact
# ppem -- and box-filtered down. A whole size is drawn natively: the 3x path softens the fully
# covered stem pixels and cost the 9x16 reference 4-5 levels of p99 against Chromium.
K = 1 if abs(px - round(px)) < 0.02 else 3; f = font(px * K)
M = np.zeros((len(glyphs), ch, cw))
for i, g in enumerate(glyphs):
if i == 0: continue # 0 is blank by contract; never drawn
im = Image.new('L', (cw * K, ch * K), 0)
# Pen at centre minus half the ADVANCE, as textAlign 'center' places it. PIL's own 'm'
# anchor centres narrow glyphs on their ink instead and landed every '.' a pixel right.
ImageDraw.Draw(im).text((cw * K * 0.5 - f.getlength(g) / 2, base * K), g, font=f,
fill=255, anchor='ls')
M[i] = np.asarray(im.resize((cw, ch), Image.BOX), float) / 255
# Skia lifts partial text coverage (its mask gamma/contrast hack) and FreeType-in-PIL does not.
# Fitted on a sheet of every glyph screenshotted from Chromium at seven cell sizes (4x7..10x18):
# ^0.85 gives the lowest pixel error at every size and 1.01 of Chromium's ink at 9x16. Cells
# under 7 px wide still print ~6-10% less ink than Chromium -- its hinter fattens tiny stems.
return M ** 0.85
def render(src, cell=(9, 16), u=None, q=2, ref=True):
"""-> (uint8 HxWx3 composite, info dict). u is the UNDER strength (None = glyph print only)."""
cols, rows, pal, glyphs, cells, U = load(src)
cw, ch = cell
# A fractional cell is rasterised at the smallest supersample that makes it whole (5.6 -> x5),
# so the glyph lattice does not drift a pixel every few cells, then box-filtered to size.
ss = next((s for s in range(1, 9) if abs(cw * s - round(cw * s)) < 0.02 and
abs(ch * s - round(ch * s)) < 0.02), 4)
mw, mh = round(cw * ss), round(ch * ss)
M = masks(glyphs, mw, mh)
g, ci, lu = cells[..., 0], cells[..., 1], cells[..., 2]
on = (g > 0) & (lu >= 4) # LUM_FLOOR
col = pal[ci % len(pal)] * (lu * on / 255.0)[..., None]
# One cell row at a time: the whole-frame gather is rows*cols*mh*mw*3 floats, which at a
# supersampled 360x110 is over a gigabyte on a machine other renders are sharing.
M = M.astype(np.float32); S = np.empty((rows * mh, cols * mw, 3), np.uint8)
for y in range(rows):
r = M[g[y]][..., None] * col[y, :, None, None, :].astype(np.float32)
S[y * mh:(y + 1) * mh] = np.clip(np.rint(r.transpose(1, 0, 2, 3).reshape(mh, -1, 3)), 0, 255)
W, H = round(cols * cw), round(rows * ch)
sc = Image.fromarray(S)
if ss > 1: sc = sc.resize((W, H), Image.BOX)
out = np.asarray(sc, float)
D = max(1.0, cols * (cw / ch) / 112.5) if ref else 1.0
dh = (ch if ss > 1 else int(ch)) * D
# Bloom in float, never through PIL's 8-bit GaussianBlur: its fixed-point box passes round
# every dim pixel UP, and on a frame that is mostly faint ink that bias alone added ~7% to the
# wide tap and cost three points of black share against Chromium. Zero padding, because the
# canvas blurs into a transparent border rather than smearing the edge row outwards.
def half(a): # one mip level: what a 'high' 2:1 drawImage reads
h, w = a.shape[0] // 2 * 2, a.shape[1] // 2 * 2; a = a[:h, :w]
return (a[0::2, 0::2] + a[1::2, 0::2] + a[0::2, 1::2] + a[1::2, 1::2]) * 0.25
def blur(a, sd):
r = max(1, math.ceil(3 * sd)); k = np.exp(-0.5 * (np.arange(-r, r + 1) / sd) ** 2); k /= k.sum()
for ax in (0, 1):
p = np.pad(a, [(r, r) if i == ax else (0, 0) for i in range(3)]); n = a.shape[ax]
a = sum(k[i] * (p[i:i + n] if ax == 0 else p[:, i:i + n]) for i in range(2 * r + 1))
return a
def up(a): # the composite's stretch back to full size
return np.stack([np.asarray(Image.fromarray(a[..., c].astype(np.float32), 'F')
.resize((W, H), Image.BILINEAR)) for c in range(3)], 2)
if q >= 2:
b2 = blur(half(out), max(0.6, dh * 0.05))
out = out + 0.55 * up(b2) + 0.85 * up(blur(half(half(b2)), max(0.8, dh * 0.045)))
elif q == 1:
out = out + 0.95 * up(blur(half(half(out)), max(0.7, dh * 0.06)))
if u is not None and U is not None:
Ui = Image.fromarray(np.clip(np.rint(U * u), 0, 255).astype(np.uint8))
out = out + np.asarray(Ui.resize((W, H), Image.NEAREST), float)
out = np.clip(np.rint(out), 0, 255).astype(np.uint8)
return out, dict(cols=cols, rows=rows, cw=cw, ch=ch, D=D, lit=on.mean(),
under=U is not None, cells=cells, pal=pal, glyphs=glyphs, U=U)
def stats(a):
y = a.astype(float) @ np.array([0.2126, 0.7152, 0.0722])
p50, p90, p99 = np.percentile(y, [50, 90, 99])
return dict(mean=y.mean(), p50=p50, p90=p90, p99=p99, black=(a.max(axis=2) < 8).mean())
def fmt(s):
return (f"mean {s['mean']:.1f} p50 {s['p50']:.0f} p90 {s['p90']:.0f} p99 {s['p99']:.0f}"
f" black(<8) {s['black']*100:.1f}%")
def main(argv):
pos = [a for a in argv if not a.startswith('--')]
fl = dict((a[2:].split('=', 1) + [None])[:2] for a in argv if a.startswith('--'))
cell = tuple(float(v) if '.' in v else int(v) for v in (fl.get('cell') or '9x16').split('x'))
if 'cov' in fl:
# Coverage of each glyph as the 9x16 reference print lays it down (clipped to the cell):
# the 'ink' metrics.py --composite weights a cell by. Regenerate when GLYPHS changes.
#
# And 'px': the same table for each small cell the canvas's PIXEL PATH prints (dw 4..7 at
# dh = dw / 0.5625, as main.js sizes them), with render_canvas.js's ink compensation applied
# per pixel exactly as pxReady() bakes it: cov' = 1-(1-cov)^k, k = 1 + 1.6*(9-dw)/9. On those
# cells a glyph prints up to a quarter more ink than the reference table says, and
# composite.cjs weights a 400-column gate by these rather than by the 9x16 table, or it
# would understate the glyph's share of every cell's light at the very size it stands for.
# This rasteriser prints 6-10% less ink than Chromium under 7 px (see masks()), so these
# are a floor on the lift, not its exact value.
G = load(pos[0])[3]; M = masks(G, *cell)
px = {}
for dw in range(4, 8):
dh = max(7, int(math.floor(dw / 0.5625 + 0.5))); k = 1 + 1.6 * (9 - dw) / 9
Mk = 1 - (1 - masks(G, dw, dh)) ** k
px['%dx%d' % (dw, dh)] = {g: round(float(Mk[i].mean()), 4) for i, g in enumerate(G) if i}
print(json.dumps({'_': 'python3 tools/topng.py f.txt --cov > tools/cov.json -- glyph ink '
'share of the cell; weights metrics.py --composite and composite.cjs',
'cell': '%sx%s' % cell, 'cov': {g: round(float(M[i].mean()), 4)
for i, g in enumerate(G) if i}, 'px': px}, ensure_ascii=False, indent=0))
return
u = float(fl['u'] or 1) if 'u' in fl else None
a, I = render(pos[0], cell, u, int(fl.get('q') or 2), fl.get('bloom') != 'cell')
Image.fromarray(a).save(pos[1])
note = '' if u is None else (' +UNDER x%g' % u if I['under'] else ' (no UNDER line: glyphs only)')
print(f"{pos[1]} {I['cols']}x{I['rows']} cells @ {cw_s(cell)} D {I['D']:.2f} "
f"{I['lit']*100:.1f}% lit{note} {fmt(stats(a))}")
def cw_s(c): return '%gx%g' % c
if __name__ == '__main__':
main(sys.argv[1], sys.argv[2])
main(sys.argv[1:])

View file

@ -1,7 +1,15 @@
/* PHOTOSENSITIVITY GATE FOR THE FRONTIER — the third of its kind, after tools/flicker-rate.cjs
* (signage fixtures) and tools/lightning-rate.cjs (storm strokes).
*
* node tools/west-flicker.cjs [seconds] [cols] [rows]
* node tools/west-flicker.cjs [seconds] [cols] [rows] [--composite] [--cols=N] [--rows=N]
*
* --composite scores every series on the light the cell EMITS, glyph plus underpainting, per
* tools/composite.cjs; without it the series is the printed lum, as it always was. Both modes now
* also run the area-weighted WCAG general-flash check on every row, and that one is ABSOLUTE, not
* comparative: "no worse than the city" is the right question for a cell's step rate, which the
* city cannot get to zero either, and the wrong one for a flash over a quarter of the visual field,
* which nothing on this screen is entitled to. --cols/--rows are the same as the positionals and
* exist so every probe in tools/ takes the same spelling.
*
* WHY A THIRD TOOL. The other two measure named cyberpunk objects: flicker-rate lifts `flick()`
* out of signage.js and drives it directly, lightning-rate integrates one stroke over the frame.
@ -66,9 +74,9 @@
const fs = require('fs'), path = require('path');
const root = path.join(__dirname, '..');
const SECONDS = parseFloat(process.argv[2] || '4');
const COLS = parseInt(process.argv[3] || '120', 10);
const ROWS = parseInt(process.argv[4] || '40', 10);
const POS = process.argv.slice(2).filter(a => a.slice(0, 2) !== '--');
const SECONDS = parseFloat(POS[0] || '4');
const PC = parseInt(POS[1] || '120', 10), PR = parseInt(POS[2] || '40', 10);
/* A SHORT RUN IS NOT A CHEAP RUN, it is a wrong one, and this warning exists because a one-second
run was believed for twenty minutes. The 3-20 Hz figure comes from a Goertzel over the measured
window: at 1 s that is 60 samples, so the bin spacing is 1 Hz and a single step edge leaks across
@ -76,7 +84,7 @@ const ROWS = parseInt(process.argv[4] || '40', 10);
second number means anything. Under two seconds the spectral half of this tool is noise. */
if (SECONDS < 2) console.error('west-flicker: WARNING — under 2 s the 3-20 Hz figure is noise; ' +
'the step and rate figures are still valid.');
if (!(SECONDS > 0) || !(COLS > 8) || !(ROWS > 8)) {
if (!(SECONDS > 0) || !(PC > 8) || !(PR > 8)) {
console.error('usage: node tools/west-flicker.cjs [seconds] [cols] [rows]');
process.exit(2);
}
@ -108,6 +116,8 @@ for (const rel of ['src/raycast.js', 'src/control.js', 'src/compose.js']) {
const edir = path.join(root, 'src/elements');
for (const f of fs.readdirSync(edir).sort()) if (f.endsWith('.js')) require(path.join(edir, f));
const CC = global.CC;
const CP = require('./composite.cjs')(CC), M = CP.mode(process.argv, PC, PR);
const COLS = M.cols, ROWS = M.rows;
/* Goertzel at seven probes across the band. Seven and not a full FFT because the question is
* "is there anything in 3-20 Hz", not "what is the spectrum", and seven single-bin evaluations
@ -166,6 +176,7 @@ function run(presetName, reduced, seed, world, scope) {
const N = COLS * ROWS;
const keep = NF - WARM;
const series = new Uint8Array(N * keep);
const V = new Float32Array(N), Y = new Float32Array(N), fl = CP.Flash(COLS, ROWS);
for (let k = 0; k < NF; k++) {
const t = k / 60;
@ -179,11 +190,16 @@ function run(presetName, reduced, seed, world, scope) {
cam.t = t;
CC.clearFrame(f);
CC.Cast.render(f, cam, city);
/* The snapshot the underpainting reads the world from, taken where main.js takes it. Without
* it the field would keep the first frame's world for the whole run. */
if (M.comp) CC.Compose.world(f);
for (const el of drawn) if (el.draw) el.draw(f, cam, t);
if (CC.Compose && CC.Compose.post) CC.Compose.post(f, cam, t);
if (k >= WARM) {
const base = (k - WARM) * N;
for (let i = 0; i < N; i++) series[base + i] = f.lum[i];
CP.light(f, V, Y); fl.push(Y);
const src = M.comp ? V : f.lum;
for (let i = 0; i < N; i++) series[base + i] = src[i] + 0.5;
}
}
@ -215,7 +231,7 @@ function run(presetName, reduced, seed, world, scope) {
step: worstStep / 255 * 100,
rate: worstBigRate,
band: worstBand / 255 * 100,
cell: worstCell, bandCell: worstBandCell
cell: worstCell, bandCell: worstBandCell, flash: fl.result()
};
}
@ -243,8 +259,14 @@ const STEP_RATE_CAP = 8.0, BAND_CAP = 9.0;
const TOLERANCE = 1.15;
let fail = 0;
console.log(`frontier flicker gate — ${COLS}x${ROWS}, ${SECONDS}s measured of ${NF} frames, ` +
console.log(`frontier flicker gate — ${M.tag}, ${SECONDS}s measured of ${NF} frames, ` +
`pinned camera, ${WARM} discarded\n`);
let flashWorst = null, flashWhat = '';
function flashRow(r, what) {
if (!flashWorst || r.flash.area > flashWorst.area || (r.flash.area === flashWorst.area && r.flash.swing > flashWorst.swing))
flashWorst = r.flash, flashWhat = what;
return `\n ${CP.fmt(r.flash)}${r.flash.bad ? ' FAIL (general flash)' : ''}`;
}
console.log(' live');
let liveStep = 0, liveRate = 0, liveBand = 0;
for (const world of TEST_WORLDS) {
@ -253,7 +275,7 @@ for (const world of TEST_WORLDS) {
for (const p of PRESETS) {
const r = run(p, false, seed, world, 'own');
const bad = (r.rate > STEP_RATE_CAP ? ' BIG-STEP RATE OVER CAP' : '') +
(r.band > BAND_CAP ? ' 3-20Hz OVER CAP' : '');
(r.band > BAND_CAP ? ' 3-20Hz OVER CAP' : '') + (r.flash.bad ? ' GENERAL FLASH' : '');
if (bad) fail++;
if (r.step > liveStep) liveStep = r.step;
if (r.rate > liveRate) liveRate = r.rate;
@ -261,7 +283,8 @@ for (const world of TEST_WORLDS) {
console.log(` ${world.padEnd(6)} seed ${String(seed).padStart(3)} ${p.padEnd(9)}` +
`worst step ${r.step.toFixed(1).padStart(5)}% ` +
`big steps ${r.rate.toFixed(2).padStart(5)}/s ` +
`3-20Hz ${r.band.toFixed(2).padStart(5)}% ${bad ? 'FAIL' + bad : 'ok'}`);
`3-20Hz ${r.band.toFixed(2).padStart(5)}% ${bad ? 'FAIL' + bad : 'ok'}` +
flashRow(r, `${world} seed ${seed} ${p}`));
}
}
}
@ -271,17 +294,38 @@ let cityRate = 0, cityBand = 0, cityStep = 0;
for (const seed of SEEDS) {
for (const p of CITY_PRESETS) {
const r = run(p, false, seed, DEFAULT_WORLD, 'own');
/* The city's own row is the baseline for the comparative rules, and it is still a screen
* somebody watches: the absolute flash rule applies to it exactly as to the worlds above. */
if (r.flash.bad) { fail++; console.log(' FAIL: general flash in the city\'s own elements'); }
if (r.step > cityStep) cityStep = r.step;
if (r.rate > cityRate) cityRate = r.rate;
if (r.band > cityBand) cityBand = r.band;
console.log(` seed ${String(seed).padStart(3)} ${p.padEnd(9)}` +
`worst step ${r.step.toFixed(1).padStart(5)}% ` +
`big steps ${r.rate.toFixed(2).padStart(5)}/s ` +
`3-20Hz ${r.band.toFixed(2).padStart(5)}%`);
`3-20Hz ${r.band.toFixed(2).padStart(5)}%` + flashRow(r, `${DEFAULT_WORLD} seed ${seed} ${p}`));
}
}
if (liveRate > cityRate * TOLERANCE) { fail++; console.log(' FAIL: the frontier steps more often than the city'); }
if (liveBand > cityBand * TOLERANCE) { fail++; console.log(' FAIL: the frontier carries more 3-20 Hz than the city'); }
/* IN COMPOSITE MODE THE COMPARISON IS PRINTED AND NOT JUDGED, and the project's own absolute limits
* judge instead — 1.0 big steps a second and 2% in band, flicker-rate's, eight and four times
* stricter than the backstops above. The ratio stops meaning what it was written to mean once the
* series is light averaged over a cell: the city's own moving parts are mostly RAIN, hairline
* glyphs inking 5-13% of their cells, and the frontier's are solid objects inking 25-35%, so the
* cell average shrinks the baseline three times harder than the thing compared to it. Measured
* the day this landed, 200x60: the frontier's own 1.18% in band against the city's 0.79% on the
* composite — and 1.14% against 0.80% on the glyph print with the underpainting OFF, so the wash
* contributes 0.04 of it and the inversion is the averaging. Gating that ratio would be gating
* on how thin rain is. The lum run keeps the comparative rule, where it was fitted. */
const cmpRate = liveRate > cityRate * TOLERANCE, cmpBand = liveBand > cityBand * TOLERANCE;
if (M.comp) {
console.log(` comparison (printed, not judged in composite mode): rate ${liveRate.toFixed(2)} vs ${cityRate.toFixed(2)}/s` +
`${cmpRate ? ' — over' : ''}, band ${liveBand.toFixed(2)}% vs ${cityBand.toFixed(2)}%${cmpBand ? ' — over' : ''}`);
if (liveRate > 1.0) { fail++; console.log(` FAIL: big-step rate ${liveRate.toFixed(2)}/s over the absolute 1.0/s`); }
if (liveBand > 2.0) { fail++; console.log(` FAIL: 3-20 Hz ${liveBand.toFixed(2)}% over the absolute 2%`); }
} else {
if (cmpRate) { fail++; console.log(' FAIL: the frontier steps more often than the city'); }
if (cmpBand) { fail++; console.log(' FAIL: the frontier carries more 3-20 Hz than the city'); }
}
console.log('\n reduced motion');
let rmBand = 0, rmRate = 0;
@ -291,13 +335,14 @@ for (const p of presetsOf(world)) {
/* Stricter: with the flag on, the danger band must be empty outright — a quarter of the limit is
* the same margin lightning-rate holds itself to. */
/* ABSOLUTE, and strict: with the flag on the frontier's own elements must be silent. */
const bad = (r.band > 0.5 ? ' 3-20Hz' : '') + (r.rate > 0.05 ? ' BIG-STEP RATE' : '');
const bad = (r.band > 0.5 ? ' 3-20Hz' : '') + (r.rate > 0.05 ? ' BIG-STEP RATE' : '') + (r.flash.bad ? ' GENERAL FLASH' : '');
if (bad) fail++;
if (r.band > rmBand) rmBand = r.band;
if (r.rate > rmRate) rmRate = r.rate;
console.log(` ${world.padEnd(6)} ${p.padEnd(9)}worst step ${r.step.toFixed(1).padStart(5)}% ` +
`big steps ${r.rate.toFixed(2).padStart(5)}/s ` +
`3-20Hz ${r.band.toFixed(2).padStart(5)}% ${bad ? 'FAIL' + bad : 'ok'}`);
`3-20Hz ${r.band.toFixed(2).padStart(5)}% ${bad ? 'FAIL' + bad : 'ok'}` +
flashRow(r, `${world} ${p} reduced motion`));
}
CC.reducedMotion = false;
@ -313,7 +358,8 @@ for (const [w, p] of CTX) {
const r = run(p, false, 3, w, 'all');
ctx[w] = r;
console.log(` ${w.padEnd(9)}worst step ${r.step.toFixed(1).padStart(5)}% ` +
`big steps ${r.rate.toFixed(2).padStart(5)}/s 3-20Hz ${r.band.toFixed(2).padStart(5)}%`);
`big steps ${r.rate.toFixed(2).padStart(5)}/s 3-20Hz ${r.band.toFixed(2).padStart(5)}%` +
`\n ${CP.fmt(r.flash)} (context, ungated)`);
}
console.log(' (a moving silhouette alternates a cell at character resolution in every world with');
console.log(' objects in it; the gate above is the one that means something — see the header)');
@ -338,6 +384,7 @@ console.log(`\nSUMMARY: frontier's own — worst step ${liveStep.toFixed(1)}% of
`| reduced-motion 3-20 Hz ${rmBand.toFixed(2)}%, ` +
`big-step rate ${rmRate.toFixed(2)}/s` +
` | context: full list, ` +
CC.World.LIST.map(w => w.id + ' ' + ctx[w.id].rate.toFixed(2) + '/s').join(' vs '));
console.log('RESULT: ' + (fail ? 'FAIL' : 'PASS'));
CC.World.LIST.map(w => w.id + ' ' + ctx[w.id].rate.toFixed(2) + '/s').join(' vs ') +
` | ${M.tag} | worst gated ${CP.fmt(flashWorst)} (${flashWhat})`);
console.log('RESULT: ' + (fail ? 'FAIL' : 'PASS') + ` ${M.comp ? 'composite' : 'lum'} ${COLS}x${ROWS}`);
process.exit(fail ? 1 : 0);

1750
w/jp.js Normal file

File diff suppressed because it is too large Load diff

2019
w/moon.js Normal file

File diff suppressed because it is too large Load diff

2744
w/west.js Normal file

File diff suppressed because it is too large Load diff