In this section
- Cosmic — Index Page render · cosmic / index.html lines 1–700
Cosmic — Index Page
A web page that makes accumulator (`makeAccumulator`), loads rows (`loadRows`), finds ordinal (`findByOrdinal`) and calculates planar distances. Published at https://ventusltd.github.io/cosmic/.
rendercosmic / index.html · lines 1–700 of 1018 · Entry point · pattern stepTween (shared by 2 files)
- What it does
- It draws its content. Defines 31 functions or classes, including fmt, words, build, mk, makeAccumulator. Side effects: changes the web page (DOM); makes network requests.
- Inputs & outputs
- In: JSON file universe.json; form fields (user input). Out: web page; WebGL/WebGPU drawing.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/cosmic/.
- What it achieves
- It makes accumulator (`makeAccumulator`), loads rows (`loadRows`) and finds ordinal (`findByOrdinal`). Defines `fmt`, `words`, `build` and 26 more. It responds to webglcontextlost, resize and pointerdown events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · / · page
- Uses
- none found
- Used by
- none found
- Produces
- fmt, words, build, mk, makeAccumulator, whitePoint, U, restart, sizes, loadRows, requestChildren, ensureChildren
- Defines here
- fmt, words, build, mk, makeAccumulator, whitePoint, U, restart, sizes, loadRows, requestChildren, ensureChildren, cumulate, findByOrdinal, leafPosition, collapseTo, resize, travelTo, stepTween, viewOf, walk, unresolvedInto, classify, scanFrame, dur, frame
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 index.html:1-700 · blob 41a9007eb8480538552240829c5cf7a137e0445c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>cosmic</title>
<style>
:root{--ink:#e8e6e1;--dim:#8b919c;--line:#171a20;--warn:#e8b36a}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:#000;color:var(--ink);
font:12px/1.55 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow:hidden}
canvas{position:fixed;inset:0;width:100%;height:100%;display:block;image-rendering:pixelated}
#c{background:#000;z-index:1}
#o{background:transparent;z-index:4;pointer-events:none}
/* a 90s display: scanlines, and nothing smoothed anywhere */
#crt{position:fixed;inset:0;pointer-events:none;z-index:5;
background:repeating-linear-gradient(to bottom,rgba(0,0,0,0) 0 2px,rgba(0,0,0,.28) 2px 3px)}
#top{position:fixed;top:0;left:0;right:0;padding:10px 14px;pointer-events:none;z-index:10}
#big{font-size:20px;letter-spacing:.02em;line-height:1.2}
#sub{color:var(--dim);margin-top:2px}
#hud{position:fixed;top:12px;right:14px;color:var(--dim);z-index:10;text-align:right;
white-space:pre-line}
#lawnote{position:fixed;left:0;right:0;bottom:58px;padding:10px 14px;color:#d8c9a8;
background:#000e;border-top:1px solid var(--line);z-index:9;font-size:12px;line-height:1.65;
max-height:32vh;overflow:auto}
#lawnote a{color:#66ccff}
#foot{position:fixed;left:0;right:0;bottom:0;padding:8px 14px;color:var(--dim);
border-top:1px solid var(--line);background:#000c;z-index:10;line-height:1.7}
b{color:var(--ink);font-weight:600}
.warn{color:var(--warn)}
#goto{position:fixed;left:50%;top:38%;transform:translateX(-50%);z-index:20;display:none;
background:#000;border:1px solid var(--dim);padding:10px 12px;min-width:min(560px,86vw)}
#goto input{width:100%;background:#000;color:var(--ink);border:0;outline:0;
font:14px/1.4 ui-monospace,Consolas,monospace}
#goto div{color:var(--dim);margin-top:6px}
</style>
</head>
<body>
<canvas id="c"></canvas>
<canvas id="o"></canvas>
<div id="top">
<div id="big">loading</div>
<div id="sub"> </div>
</div>
<div id="goto">
<input id="gotoin" autocomplete="off" spellcheck="false"
placeholder="ordinal, or repository, or repository/commit">
<div>enter to collapse · escape to cancel · any point is one fetch away</div>
</div>
<div id="crt"></div>
<div id="hud">starting</div>
<div id="foot">
<b>x</b> x-ray: every pixel counts · <b>s</b> scan: show every one · <b>r</b> collapse to a random point ·
<b>/</b> collapse to an address ·
<b>click</b> to travel in · <b>backspace</b> to pull back · drag to steer ·
scroll to zoom · <b>l</b> names · positions are computed from the ordinal, never
stored · provided as is, without warranty of any kind; a chart, not a design
</div>
<script type="module">
// COSMIC IS THE ENGINE, AND IT KNOWS NOTHING.
//
// It has never heard of git, of wafers or of grids. It is handed a cartridge (universe.json): a
// hierarchy that somebody measured, a placement law for each level, and the total those levels
// must sum to. Swap the cartridge and the same engine draws a CPU, a solar farm or a network.
//
// WHAT IT IS FOR. A number like 37.93 billion cannot be read and cannot be drawn: on a million
// pixels it is forty thousand to a pixel, a white flash carrying no information. The way through
// is the way the night sky works, and it is two rules:
//
// CLUSTERING. Things are bound to other things. Every level is placed by the same law as the
// level above it, so the structure is self similar and the black between is
// structural, not decorative. The void is data. No body may take more than a
// third of the gap to its neighbour, so there is always space, at every level,
// for any number of children.
//
// RESOLUTION. A telescope does not resolve the whole sky at once. Beyond its reach an object
// is an unresolved source: you know it is there, you know its brightness, you
// cannot see inside. The criterion is one thing per pixel, which is the surface
// brightness limit that stops a telescope resolving a galaxy into stars.
//
// Travelling collapses the data to what is relevant, which is the only way to compute against
// something this size. THE WHOLE IS NEVER LOST WHILE THIS HAPPENS. Every frame the engine
// accounts for every unit in the cartridge as resolved, held, or outside the field, and checks
// that the three sum to the total. If they ever do not it says MISACCOUNTED and does not pretend.
//
// SEE IT AS IT IS. Nothing is coloured in, nothing is invented to fill a space, nothing is
// thinned to make a picture, no number is softened.
const GOLDEN = 2.399963229728653;
// 0.6180339887... over 2^32: the golden angle as an exact integer ratio, so the angle is computed
// in wrapping uint arithmetic and every ordinal gets its own, past 2^32 and beyond.
const GOLD32 = 2654435769;
const cv = document.getElementById('c');
const ov = document.getElementById('o');
const o2 = ov.getContext('2d');
const gl = cv.getContext('webgl2', {
antialias:false, alpha:false, powerPreference:'high-performance',
// the exposure accumulates ACROSS frames. Without this the browser may discard the drawing
// buffer after each composite and every frame but the last is thrown away, while the instrument
// goes on reporting a whole exposure. Required, not an optimisation.
preserveDrawingBuffer:true });
const hud = document.getElementById('hud');
const big = document.getElementById('big');
const sub = document.getElementById('sub');
const fmt = n => n.toLocaleString('en-GB');
// NOBODY READS 37929011953, AND POWERS OF TEN ARE WORSE. The headline is said the way a person
// says it. The exact figure is never thrown away; it just stops being the first thing you see.
function words(n) {
if (n >= 1e12) return (n / 1e12).toFixed(2) + ' trillion';
if (n >= 1e9) return (n / 1e9 ).toFixed(2) + ' billion';
if (n >= 1e6) return (n / 1e6 ).toFixed(2) + ' million';
if (n >= 1e3) return (n / 1e3 ).toFixed(1) + ' thousand';
return String(Math.round(n));
}
if (!gl) {
hud.textContent = 'WebGL2 is not available here. Refusing rather than drawing a fraction.';
throw new Error('no webgl2');
}
// -------------------------------------------------------------------------------- the shaders
const MAXB = 128;
const VS_BODY = `#version 300 es
precision highp float;
uniform vec4 u_body[${MAXB}]; // clip x, clip y, radius in pixels, unused
out float v_px;
void main() {
vec4 b = u_body[gl_VertexID];
v_px = b.z;
gl_Position = vec4(b.xy, 0.0, 1.0);
gl_PointSize = max(1.0, b.z * 2.0);
}`;
const FS_BODY = `#version 300 es
precision highp float;
in float v_px;
out vec4 o;
void main() {
// BINARY. Inside the source or outside it, hard edged, the way a monochrome display drew a
// disc. No glow, no falloff, nothing added that was not counted.
if (v_px > 1.5 && length(gl_PointCoord - 0.5) > 0.5) discard;
o = vec4(0.87, 0.89, 0.86, 1.0);
}`;
const VS_LEAF = `#version 300 es
precision highp float;
uniform vec2 u_c; // the object's centre, in world units
uniform float u_rho; // its radius, in world units
uniform float u_invn; // 1 / its leaf count
uniform uint u_stride;
uniform uint u_pass;
uniform uint u_seed; // the object's own phase, so two objects never share a pattern
uniform float u_scale;
uniform vec2 u_pan;
uniform float u_aspect;
uniform float u_shape; // 0 a disc, 1 a rectangle
uniform vec2 u_half; // half extents, when it is a rectangle
void main() {
// THE ORDINAL DOES NOT FIT IN A FLOAT. At 3.5e10 a float32 step is 4096, so building k as a
// float would quantise it and every pass would land on the same positions. The fraction comes
// from float(gl_VertexID), exact below 2^24; the angle is built in wrapping uint arithmetic,
// exact mod 2^32.
float frac = (float(gl_VertexID) * float(u_stride) + float(u_pass)) * u_invn;
if (frac >= 1.0) { gl_Position = vec4(2.0, 2.0, 0.0, 1.0); return; }
uint k32 = u_seed + uint(gl_VertexID) * u_stride + u_pass;
vec2 p;
if (u_shape > 0.5) {
// A RECTANGLE IS NOT A DISC, AND A SPIRAL INSIDE ONE WOULD BE A LIE ABOUT THE OBJECT. This is
// the R2 sequence, the two dimensional generalisation of the golden ratio: two irrational
// multipliers held as exact ratios over 2^32, which fills a rectangle at uniform density with
// no clumping and no visible lattice. Same discipline as the golden angle, one dimension up.
float fx = float(k32 * 3242174889u) * (1.0 / 4294967296.0);
float fy = float(k32 * 2447445413u) * (1.0 / 4294967296.0);
p = u_c + (vec2(fx, fy) - 0.5) * 2.0 * u_half;
} else {
float r = u_rho * sqrt(frac); // uniform areal density: AREA is the share
float a = 6.283185307179586 * float(k32 * ${GOLD32}u) * (1.0 / 4294967296.0);
p = u_c + vec2(cos(a), sin(a)) * r;
}
p = p * u_scale + u_pan;
p.x /= u_aspect;
gl_Position = vec4(p, 0.0, 1.0);
gl_PointSize = 1.0;
}`;
const FS_LEAF = `#version 300 es
precision highp float;
out vec4 o;
void main() {
// A thing either exists at this position or it does not. One or zero, no partial brightness.
o = vec4(0.87, 0.89, 0.86, 1.0);
}`;
function build(vs, fs) {
const mk = (t, src) => {
const s = gl.createShader(t); gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
return s;
};
const p = gl.createProgram();
gl.attachShader(p, mk(gl.VERTEX_SHADER, vs));
gl.attachShader(p, mk(gl.FRAGMENT_SHADER, fs));
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
return p;
}
// SHOW EVERYTHING. The confusion limit is a limit on one FRAME, not on a display. A screen's
// capacity is resolution elements multiplied by frames, so completeness was never impossible,
// only slow. This draws the whole population in order, a screenful at a time, every thing in its
// own resolution element at the confusion spacing, so nothing shares a pixel with anything and
// nothing is thinned. Run it to the end and every single one has been shown.
const VS_SCAN = `#version 300 es
precision highp float;
uniform float u_cols;
uniform vec2 u_step;
uniform vec2 u_origin;
void main() {
float i = float(gl_VertexID);
vec2 p = u_origin + vec2(mod(i, u_cols), floor(i / u_cols)) * u_step;
gl_Position = vec4(p, 0.0, 1.0);
gl_PointSize = 1.0;
}`;
// THE X-RAY. A pixel that can only be lit or unlit wastes its other bits and turns density into
// a white flash. This counts instead: every thing lands in a float buffer that adds one, so each
// pixel ends up holding the EXACT number of things at that position, and a second pass turns that
// count into a shade. The picture is then a measurement and it is invertible: read the shade, get
// the count back. Nothing is thinned and nothing is dropped, and the whole population can sit in
// one frame, because the frame is no longer limited to saying yes or no.
const VS_FULL = `#version 300 es
precision highp float;
void main() {
vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
}`;
const FS_TONE = `#version 300 es
precision highp float;
uniform sampler2D u_tex;
uniform float u_white; // the count that maps to full white. Stated on screen, so invertible.
out vec4 o;
void main() {
float n = texelFetch(u_tex, ivec2(gl_FragCoord.xy), 0).r;
if (n <= 0.0) { o = vec4(0.0, 0.0, 0.0, 1.0); return; }
// logarithmic, because density here spans five orders of magnitude and a linear ramp would show
// one bright core and nothing else. The mapping is printed so it can be read backwards.
float v = clamp(log(1.0 + n) / log(1.0 + u_white), 0.06, 1.0);
o = vec4(vec3(0.87, 0.89, 0.86) * v, 1.0);
}`;
const PB = build(VS_BODY, FS_BODY), PL = build(VS_LEAF, FS_LEAF),
PT = build(VS_FULL, FS_TONE),
PS = build(VS_SCAN, FS_LEAF);
const tTex = gl.getUniformLocation(PT, 'u_tex'), tWhite = gl.getUniformLocation(PT, 'u_white');
// counting past 255 needs a float target. Without it the x-ray refuses rather than counting wrong.
const FLOATOK = !!gl.getExtension('EXT_color_buffer_float');
let acc = null, accFB = null, xray = false;
function makeAccumulator() {
if (!FLOATOK) return;
if (acc) { gl.deleteTexture(acc); gl.deleteFramebuffer(accFB); }
acc = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, acc);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, cv.width, cv.height, 0, gl.RED, gl.FLOAT, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
accFB = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, accFB);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, acc, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
// the count that maps to full white. The mean density over the drawn area, lifted so the crowded
// parts do not all clip to one shade. Printed on screen, never hidden.
function whitePoint() {
const R = cv.height / 2 * scale;
return Math.max(4, (drawn || TOTAL) / Math.max(1, Math.PI * R * R) * 16);
}
const sCols = gl.getUniformLocation(PS, 'u_cols'),
sStep = gl.getUniformLocation(PS, 'u_step'),
sOrig = gl.getUniformLocation(PS, 'u_origin');
const uBody = gl.getUniformLocation(PB, 'u_body[0]');
const U = n => gl.getUniformLocation(PL, n);
const lC=U('u_c'), lRho=U('u_rho'), lInv=U('u_invn'), lStr=U('u_stride'), lPas=U('u_pass'),
lSeed=U('u_seed'), lSca=U('u_scale'), lPan=U('u_pan'), lAsp=U('u_aspect'),
lShape=U('u_shape'), lHalf=U('u_half');
gl.bindVertexArray(gl.createVertexArray()); // no attributes, no buffers, nothing uploaded
gl.disable(gl.BLEND); // coverage shows density, the way a CRT had to
gl.clearColor(0, 0, 0, 1);
// THE INSTRUMENT REFUSES RATHER THAN APPROXIMATES, and that includes its own failure. A driver
// reset loses the context and every draw after it silently does nothing, so an unguarded exposure
// races to 100% and prints COMPLETE over an empty frame. Loss is caught, stated, and stops it.
let lost = false;
cv.addEventListener('webglcontextlost', e => {
e.preventDefault(); lost = true;
hud.textContent = 'CONTEXT LOST · the GPU dropped this exposure. Nothing on screen is a '
+ 'complete count. Reload to point the instrument again.';
});
// ------------------------------------------------------------------------ the exposure's state
const PER_CALL = 600000; // nine million points in one call trips the driver watchdog
let pass = 0, maxStride = 1, started = 0, fence = null, fenceAt = 0, perFrame = 1, retired = 0;
function restart() {
pass = 0; retired = 0;
if (fence) { gl.deleteSync(fence); fence = null; }
if (xray && accFB) { // a new camera means a new count
gl.bindFramebuffer(gl.FRAMEBUFFER, accFB);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
}
// ----------------------------------------------------------------------------- the placement
// ONE LAW PER LEVEL, CHOSEN BY THE CARTRIDGE. Children are laid inside their parent's disc and
// scaled by the parent's radius, so the same law applies all the way down and the structure is
// self similar. An unknown law is refused, never quietly replaced by a default.
const RHO_MAX = 0.085, ORBIT_FILL = 0.88, GAP_SHARE = 0.32;
// THE VOID IS GUARANTEED, NOT HOPED FOR. n children sit at a typical separation of about
// P/sqrt(n), so no child may have a radius larger than a third of that. Two neighbours always
// have black between them, at every level, for any number of children, which is what makes the
// vastness legible instead of a flood.
function sizes(children, P) {
const n = children.length;
const max = Math.max(...children.map(c => c.value)) || 1;
const spacing = (n === 1) ? P : ORBIT_FILL * P / Math.sqrt(n);
const cap = Math.min(RHO_MAX * P, GAP_SHARE * spacing);
// within a level the areas are exactly proportional to the values, because every sibling is
// scaled by the same cap. ACROSS levels nothing is to scale and it cannot be: a commit drawn
// to true scale inside the estate would be smaller than an atom on this screen.
children.forEach(c => { c.rho = cap * Math.sqrt(c.value / max); });
}
const LAWS = {
// POSITIONS AS DATA. A stepper put the dies where they are; no law of mine gets to move them.
// The engine only rescales the measured coordinates into the parent's disc and draws what it
// was given. This is the law that keeps a wafer a wafer.
explicit(children, cx, cy, P) {
const e = (M && M.extent_mm) || 1;
children.forEach(c => {
if (!c.src) c.src = { x:c.x, y:c.y, w:c.w, h:c.h };
c.shape = 'rect';
c.hw = (c.src.w / 2) / e * P;
c.hh = (c.src.h / 2) / e * P;
c.x = cx + (c.src.x / e) * P;
c.y = cy + (c.src.y / e) * P;
c.rad = Math.hypot(c.hw, c.hh); // bounding radius, for the field test
c.rho = Math.sqrt((4 * c.hw * c.hh) / Math.PI); // equal-area radius, for capacity
});
},
// no preferred axis: gravitational clustering, and a repository's commits
areal(children, cx, cy, P) {
const n = children.length;
children.forEach((c, i) => {
if (n === 1) { c.x = cx; c.y = cy; return; }
const a = P * ORBIT_FILL * Math.sqrt((i + 0.5) / n); // no minimum orbit: an inner hole
const th = i * GOLDEN; // would be invented structure
c.x = cx + a * Math.cos(th);
c.y = cy + a * Math.sin(th);
});
sizes(children, P);
children.forEach(c => { c.shape = 'disc'; c.rad = c.rho; });
},
// A WAFER HAS A PREFERRED AXIS AND THE SPIRAL IS WRONG FOR IT. A scanner steps a rectangular
// reticle across a round substrate at a fixed pitch, and the collision between the square step
// and the circle is the entire geometry of a wafer map. Steps whose full extent falls outside
// the circle are printed but not usable: they are marked partial and counted separately,
// because silently dropping them would misstate the yield.
grid(children, cx, cy, P) {
const n = children.length;
const cols = Math.max(1, Math.ceil(Math.sqrt(n * 4 / Math.PI)));
const pitch = 2 * P / cols;
const cells = [];
for (let gy = 0; gy < cols && cells.length < n * 4; gy++) {
for (let gx = 0; gx < cols; gx++) {
const x = -P + (gx + 0.5) * pitch, y = -P + (gy + 0.5) * pitch;
const far = Math.hypot(Math.abs(x) + pitch/2, Math.abs(y) + pitch/2);
if (Math.hypot(x, y) > P) continue; // no step at all out here
cells.push({ x, y, partial: far > P }); // rim steps: printed, not usable
}
}
children.forEach((c, i) => {
const cell = cells[i % Math.max(1, cells.length)] || { x:0, y:0, partial:false };
c.x = cx + cell.x; c.y = cy + cell.y; c.partial = cell.partial;
});
sizes(children, P);
children.forEach(c => { c.rho = Math.min(c.rho, pitch * 0.34); c.shape = 'disc'; c.rad = c.rho; });
}
};
// -------------------------------------------------------------------------------- the cartridge
let M = null, root = null, TOTAL = 0, hover = null, names = false, LEVELS = [];
// ONE ENGINE, MANY WORLDS. ?u=wafer.json loads a wafer, ?u=universe.json the estate.
const CART = new URLSearchParams(location.search).get('u') || 'universe.json';
fetch(CART).then(r => r.ok ? r.json() : Promise.reject(r.status)).then(m => {
M = m; LEVELS = m.levels || [];
TOTAL = m.total;
for (const lv of LEVELS) {
if (!LAWS[lv.law]) {
hud.textContent = 'the cartridge asks for the placement law "' + lv.law + '", which this '
+ 'engine does not have. Refusing rather than substituting another.';
throw new Error('unknown law');
}
}
return loadRows(LEVELS[0].source, 0);
}).then(rows => {
if (!rows || !rows.length) throw new Error('empty');
const sum = rows.reduce((a, r) => a + r.value, 0);
if (sum !== TOTAL) {
// THE CARTRIDGE MUST ADD UP. A hierarchy whose top level does not sum to its declared total
// is a hierarchy nobody can be held to, and drawing it would launder the error.
hud.textContent = 'the cartridge declares ' + fmt(TOTAL) + ' but its top level sums to '
+ fmt(sum) + '. Refusing to draw a total it cannot account for.';
throw new Error('mismatch');
}
LAWS[LEVELS[0].law](rows, 0, 0, 1);
cumulate(rows);
root = { label:M.name, value:TOTAL, children:rows, x:0, y:0, rho:1, depth:-1 };
// WHERE A THING CANNOT BE DRAWN, THE LAW SAYS WHY, on the page rather than in a comment.
if (M.law_note) {
const n = document.createElement('div');
n.id = 'lawnote';
n.innerHTML = M.law_note + (M.laws ? ' · <a href="' + M.laws + '">the laws</a>' : '');
document.body.insertBefore(n, document.getElementById('foot'));
}
big.textContent = words(TOTAL) + ' ' + M.unit;
sub.textContent = fmt(TOTAL) + ' exactly · ' + fmt(rows.length) + ' '
+ (LEVELS[0].plural || LEVELS[0].name) + ' · ' + (M.subtitle || '');
}).catch(e => {
if (!hud.textContent || hud.textContent === 'starting')
hud.textContent = 'the cartridge did not load. The instrument will not invent a universe.';
});
// A SECTOR IS FETCHED ONLY WHEN IT IS ENTERED. Nobody looks at two sectors at once, so the whole
// hierarchy is never downloaded and the page opens in milliseconds however large it becomes.
function loadRows(url, depth) {
const lv = LEVELS[depth];
return fetch(url).then(r => r.ok ? r.text() : Promise.reject(r.status)).then(txt =>
txt.split('\n').filter(l => l && l[0] !== '#').map((l, i) => {
const p = l.split('\t'), o = { depth, i, seed: (i * 2654435761) >>> 0 };
lv.columns.forEach((name, k) => {
o[name] = (name === 'label') ? p[k] : +p[k];
});
return o;
}).filter(r => r.value > 0));
}
const pending = new Map();
function requestChildren(node) { ensureChildren(node); }
function ensureChildren(node) {
const lv = LEVELS[node.depth];
if (node.children) return Promise.resolve(node.children);
if (node.noChildren || !lv || !lv.child) { node.noChildren = true; return Promise.resolve(null); }
const url = lv.child.replace('{i2}', String(node.i).padStart(2, '0'));
if (pending.has(url)) return pending.get(url);
const pr = loadRows(url, node.depth + 1).then(rows => {
if (!rows.length) { node.noChildren = true; return null; }
const sum = rows.reduce((a, r) => a + r.value, 0);
if (sum !== node.value) {
// a child level that does not sum to its parent would break the accounting, so it is
// refused for this node rather than allowed to quietly bend the total
node.badChildren = 'children sum to ' + fmt(sum) + ', parent holds ' + fmt(node.value);
node.noChildren = true; return null;
}
LAWS[LEVELS[node.depth + 1].law](rows, node.x, node.y, node.rho);
cumulate(rows);
node.children = rows;
restart();
return rows;
}).catch(() => { node.noChildren = true; return null; }).finally(() => pending.delete(url));
pending.set(url, pr);
return pr;
}
// ------------------------------------------------------------------- COLLAPSING SPACE TIME
// TRAVELLING IS NOT COLLAPSING. Flying in level by level is traversal, and traversal is the cost
// this whole structure exists to remove. The placement law is INVERTIBLE: an ordinal gives a
// position and a position gives the ordinal back, at every level. So any one of 37.93 billion
// things can be addressed directly. Landing on it costs one fetch, of the one sector it lives in,
// and no walking at all. That is what collapses the distance: not moving faster, but not moving.
function cumulate(rows) {
let acc = 0;
for (const r of rows) { r.cum = acc; acc += r.value; }
}
function findByOrdinal(rows, k) {
let lo = 0, hi = rows.length - 1;
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (rows[mid].cum <= k) lo = mid; else hi = mid - 1; }
return rows[lo];
}
// where a leaf sits inside its object: the same arithmetic the vertex shader does, run backwards
function leafPosition(node, m) {
const k32 = (node.seed + m) >>> 0;
if (node.shape === 'rect') { // the same R2 sequence the shader uses
const fx = (Math.imul(k32, 3242174889) >>> 0) / 4294967296;
const fy = (Math.imul(k32, 2447445413) >>> 0) / 4294967296;
return [node.x + (fx - 0.5) * 2 * node.hw, node.y + (fy - 0.5) * 2 * node.hh];
}
const r = node.rho * Math.sqrt((m + 0.5) / node.value);
const a = 6.283185307179586 * ((Math.imul(k32, GOLD32) >>> 0) / 4294967296);
return [node.x + Math.cos(a) * r, node.y + Math.sin(a) * r];
}
let target = null;
async function collapseTo(k) {
if (!root || !(k >= 0) || k >= TOTAL) return;
const path = [];
let rows = root.children, node = null, local = Math.floor(k), fetches = 0;
while (rows) {
node = findByOrdinal(rows, local); // binary search, not a walk
path.push(node);
local -= node.cum;
if (!node.children && LEVELS[node.depth] && LEVELS[node.depth].child) fetches++;
const kids = await ensureChildren(node); // ONE fetch, only for the sector entered
if (!kids) break;
rows = kids;
}
const [lx, ly] = leafPosition(node, local);
// point the instrument at the zoom where this leaf's own object can actually be resolved,
// so you arrive able to see the thing rather than at a boundary you must then cross
// a margin, because arriving at exactly the resolving limit leaves the object a hair short
// of resolving and the traveller staring at a boundary they just crossed
const needPx = Math.sqrt(node.value / (Math.PI * PER_PIXEL)) * 1.12;
let s = needPx / (node.rho * (cv.height / 2));
s = Math.max(0.5 / (node.rad || node.rho), Math.min(1e12, s));
tween = { t0:performance.now(), dur:900, s0:scale, s1:s, p0:pan.slice(), p1:[-lx*s, -ly*s] };
target = { k, x:lx, y:ly, m:local, node, path, fetches,
address: path.map(n => n.label).join(' / ') + ' # ' + fmt(local) };
}
// --------------------------------------------------------------------------------- the camera
let scale = 0.92, pan = [0, 0], tween = null;
function resize() {
cv.width = ov.width = Math.floor(innerWidth);
cv.height = ov.height = Math.floor(innerHeight);
gl.viewport(0, 0, cv.width, cv.height);
makeAccumulator();
restart();
}
addEventListener('resize', resize); resize();
// TRAVELLING IS THE COMPUTE STRATEGY. Moving in collapses the set to what is relevant; the
// accounting below is what stops that losing the whole.
function travelTo(b, fill) {
const s = (fill || 0.78) / (b.rad || b.rho);
tween = { t0:performance.now(), dur:750, s0:scale, s1:s, p0:pan.slice(),
p1:[-b.x * s, -b.y * s] };
}
function stepTween() {
if (!tween) return;
const u = Math.min(1, (performance.now() - tween.t0) / tween.dur);
const e = u < 0.5 ? 2*u*u : 1 - Math.pow(-2*u + 2, 2) / 2;
scale = Math.exp(Math.log(tween.s0) + (Math.log(tween.s1) - Math.log(tween.s0)) * e);
pan = [tween.p0[0] + (tween.p1[0]-tween.p0[0])*e, tween.p0[1] + (tween.p1[1]-tween.p0[1])*e];
restart();
if (u >= 1) tween = null;
}
// -------------------------------------------------------------- what the screen can hold
// THE CONFUSION LIMIT, WHICH IS THE REAL CRITERION. One thing per pixel is not the point at which
// things can be told apart: at one per resolution element a random field is about 63% covered and
// what you see is a confused mush, not a population. Radio astronomy has measured where this
// starts and calls it source confusion; it sets in at roughly one source per twenty to fifty beam
// areas, so surveys are cut off there rather than at one per beam. The same number is used here.
// Thirty pixels to a thing gives about three per cent coverage: a field with black between, where
// the count survives the drawing and exclusion actually holds.
const PER_PIXEL = 1 / 30;
const CHILD_PX = 44; // a source smaller than this keeps its children folded up
const RING_PX = 56; // beyond this an unresolved source is drawn as its boundary
let resolved = [], discs = [], rings = [], rects = [], held = 0, heldN = 0, drawn = 0, outside = 0;
const viewOf = d => (LEVELS[d] && LEVELS[d].view) || 'field';
function walk(node, depth) {
const R = cv.height / 2 * scale, asp = cv.width / cv.height;
const sx = (node.x * scale + pan[0]) / asp, sy = node.y * scale + pan[1];
const rpx = node.rho * R; // equal-area radius: what capacity is about
const radp = (node.rad || node.rho) * R; // bounding radius: what the field test is about
const rx = radp / (cv.width / 2), ry = radp / (cv.height / 2);
if (sx + rx < -1.02 || sx - rx > 1.02 || sy + ry < -1.02 || sy - ry > 1.02) {
outside += node.value; return; // outside the field, and counted as such
}
if (radp < 0.4) { held += node.value; heldN++; return; } // below the grain
// IN X-RAY NOTHING IS HELD BACK. The resolution rule exists because one bit per pixel cannot
// carry a crowd. Counting can, so every visible thing is drawn and the shade states how many
// landed in each pixel.
if (xray) {
resolved.push(node); drawn += node.value;
node.stride = Math.max(1, Math.ceil(node.value / PER_CALL));
maxStride = Math.max(maxStride, node.stride);
return;
}
const capacity = Math.PI * rpx * rpx * PER_PIXEL;
// THE MEASURED HIERARCHY WINS. Checking "does it fit" before "does it have children" is how a
// structure gets thrown away: once a repository's disc is large enough to hold its lines, it
// would draw all 35.56 billion of them flat, and the 5,054 commits that were measured would
// stop existing at exactly the zoom where they become visible. Worse, an address would then
// name a commit while the picture drew that line somewhere else. Descent is tried first.
//
// A PARENT STILL ONLY DISSOLVES WHEN ITS CHILDREN CAN BE SEEN. Descending too early replaces
// one visible source with five thousand sub pixel ones and the sky goes empty, which is a
// worse lie than the disc: the things are still there, and so is the object.
const lv = LEVELS[node.depth];
const canDescend = lv && lv.child && !node.noChildren;
if (canDescend && radp > CHILD_PX) {
if (node.children && depth < 8) { for (const c of node.children) walk(c, depth + 1); return; }
requestChildren(node);
held += node.value; heldN++;
node.perPixel = node.value / Math.max(1, Math.PI * rpx * rpx);
unresolvedInto(node, sx, sy, rpx, radp, depth);
return;
}
// below the size where children could be told apart, the child structure is sub pixel anyway,
// so drawing the leaves directly states nothing the eye could have contradicted
if (node.value <= capacity) {
resolved.push(node); drawn += node.value;
node.stride = Math.max(1, Math.ceil(node.value / PER_CALL));
maxStride = Math.max(maxStride, node.stride);
return;
}
if (canDescend && radp > CHILD_PX * 0.5) requestChildren(node);
held += node.value; heldN++;
// surface brightness: things per pixel over the source's own disc. This is the number that
// decides whether it can be resolved, so it is the number the instrument shows.
node.perPixel = node.value / Math.max(1, Math.PI * rpx * rpx);
unresolvedInto(node, sx, sy, rpx, radp, depth);
}
// HOW AN UNRESOLVED THING IS SHOWN DEPENDS ON WHAT IT IS. In a field it is a source: a disc, or
// its boundary if it fills the screen. In a SECTION it is an engineering object and must be drawn
// as one, an outline on a hard grid, dashed when the field is partial. A die drawn as a fuzzy dot
// would throw away the only structure that matters, which is exactly what must not happen when
// you arrive at a wafer.
function unresolvedInto(node, sx, sy, rpx, radp, depth) {
if (viewOf(node.depth) === 'section' && node.shape === 'rect') {
rects.push({ node, sx, sy });
} else if (radp > RING_PX) {
rings.push({ node, rpx: radp });
} else {
discs.push({ sx, sy, rpx: radp });
}
}
function classify() {
resolved = []; discs = []; rings = []; rects = []; held = 0; heldN = 0; drawn = 0; outside = 0; maxStride = 1;
if (root) for (const c of root.children) walk(c, 0);
}
// ------------------------------------------------------------------------------- the exposure
// one thing per confusion cell: sqrt(1/PER_PIXEL) pixels apart in each direction
const SCAN_PX = Math.sqrt(1 / PER_PIXEL);
let scanning = false, scanK = 0, scanT0 = 0, scanFrames = 0;
function scanFrame() {
const cols = Math.max(1, Math.floor(cv.width / SCAN_PX));
const rows = Math.max(1, Math.floor(cv.height / SCAN_PX));
const cells = cols * rows;
const n = Math.min(cells, TOTAL - scanK);
gl.clear(gl.COLOR_BUFFER_BIT);
if (n > 0) {
gl.useProgram(PS);
gl.uniform1f(sCols, cols);
gl.uniform2f(sStep, SCAN_PX * 2 / cv.width, SCAN_PX * 2 / cv.height);
gl.uniform2f(sOrig, -1 + SCAN_PX / cv.width, -1 + SCAN_PX / cv.height);
gl.drawArrays(gl.POINTS, 0, n);
scanK += n;
scanFrames++;
}
const secs = (performance.now() - scanT0) / 1000;
const rate = scanK / Math.max(0.001, secs);
const left = (TOTAL - scanK) / Math.max(1, rate);
const where = root && root.children ? findByOrdinal(root.children, Math.min(scanK, TOTAL - 1)) : null;
const dur = t => t > 3600 ? (t/3600).toFixed(1) + ' hours'
: t > 60 ? (t/60).toFixed(1) + ' minutes' : t.toFixed(0) + ' s';
hud.textContent = [
'SCAN · every ' + M.unit.replace(/s$/, '') + ' in its own resolution element',
(scanK >= TOTAL
? 'ALL ' + fmt(TOTAL) + ' SHOWN · COMPLETE in ' + dur(secs)
: 'shown ' + fmt(scanK) + ' of ' + fmt(TOTAL)
+ ' · ' + (scanK / TOTAL * 100).toFixed(3) + '%'),
fmt(cells) + ' per frame at ' + SCAN_PX.toFixed(1) + ' px spacing · nothing shares a pixel',
scanK >= TOTAL ? '' : words(rate) + ' per second · ' + dur(left) + ' remaining',
where ? 'now in ' + where.label : ''
].filter(Boolean).join(String.fromCharCode(10));
requestAnimationFrame(frame);
}
function frame() {
if (lost) return;
if (scanning && root) { scanFrame(); return; }
stepTween();
if (!root) { requestAnimationFrame(frame); return; }
if (fence) {
// A DRAW CALL IS A PROMISE, NOT A DRAWING. drawArrays returns the moment the command is
// queued; the GPU may be far behind. Timing the submission and calling it COMPLETE reports a
// picture that has not been drawn. The fence is the receipt.
if (gl.clientWaitSync(fence, 0, 0) === gl.TIMEOUT_EXPIRED) {