initial commit
All checks were successful
CI / build (push) Successful in 1m41s
CI / lint (push) Successful in 43s
CI / test (push) Successful in 2m7s
CI / publish (push) Successful in 12s
CI / release (push) Successful in 1m15s

This commit is contained in:
Kamal Tufekcic 2026-09-12 10:37:55 +03:00
commit 4eb2362b20
43 changed files with 23728 additions and 0 deletions

View file

@ -0,0 +1,30 @@
# The command-line oracle. Not published to the registry — `publish = false`
# — because it is a binary and travels as one, attached to a release beside
# its checksum, not as source for strangers to compile.
[package]
name = "loic-cli"
version.workspace = true
edition = "2024"
authors.workspace = true
repository.workspace = true
license-file.workspace = true
description = "The command-line oracle of the Loic Calendar: observes the present moment through a mask you name, or through hardware entropy if you decline to, and undergoes resolution collapse roughly one time in four"
readme = "README.md"
publish = false
# What the oracle stands on: the calendar, and the kernel.
[dependencies]
# The calendar, at the workspace's one version. Every observation the oracle
# makes, and every constant it prints, is the library's.
loic.workspace = true
# The kernel's interfaces, for the parts of resolution collapse no standard
# library will perform on your behalf — `signal`, `fork`, `setsid`, `prctl`,
# `pause` and `_exit` — and, at startup, the restoration of `SIGPIPE`'s
# default disposition, so that a closed pipe ends the oracle without a
# sermon.
libc = "0.2"
# The binary target, named and placed explicitly rather than inferred.
[[bin]]
name = "loic-cli"
path = "src/main.rs"

111
crates/loic-cli/README.md Normal file
View file

@ -0,0 +1,111 @@
# loic-cli
A command-line oracle for temporal inquiry. The primary display surface for the Loic Calendar's lattice structure.
## Installation
### From Source
```bash
cargo install --path crates/loic-cli
```
The binary installs as `loic-cli`.
## Usage
### Default Observation (Entropy-Selected)
```bash
$ loic-cli
```
With no arguments, the oracle declines to frame the question. Nine bits of hardware entropy select the mask:
- **75% probability:** A valid mask emerges. The slot machine renders two columns—cosmic and cycle—showing the Hasse diagram neighborhood of the selected observation. Up to three finer neighbors above, the active mask centered, up to three coarser neighbors below.
- **25% probability:** The cosmic pool overflows. Resolution collapse. Channel 2 falls to resolution zero; Channel 1 keeps producing. Raw entropy floods the terminal. On Ctrl+C, a topological scar—a zero-resource ghost process named with cosmic time digits—detaches into the process table. It ignores every signal it can; only SIGKILL ends it. It persists until reboot.
### Explicit Mask
```bash
$ loic-cli --mask heptad # Single prime
$ loic-cli --mask pentad,heptad,hendecad # Combined
$ loic-cli --mask notyte # Cosmic prime observation
$ loic-cli --mask 0x0480 # Hex (15-bit, 0x0000–0x7FFF)
$ loic-cli --mask 0b110 # Binary
$ loic-cli --mask 42 # Decimal
$ loic-cli --mask whisper # No primes: the undivided whole
$ loic-cli --mask full # All fifteen: the finest question there is
```
The 15 prime names (case-insensitive):
**Cosmic:** Andyte, Xoryte, Oryte, Noryte, Xnoryte, Notyte, Nandyte
**Cycle:** Dyad, Pentad, Heptad, Hendecad, Sigma, Tau, Phi, Psi
### The Slot Machine
Output is two vertical columns—cosmic and cycle—each showing the Hasse diagram neighborhood of the current mask:
```
COSMIC CYCLE
──────────────────────────────────── ────────────────────────────────────
Andyte × Notyte Dyad × Heptad
Xoryte × Notyte Pentad × Heptad
Oryte × Notyte Heptad × Hendecad
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▶ Notyte ◀ ▶ Heptad ◀
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Whisper Whisper
──────────────────────────────────── ────────────────────────────────────
pos 0/298824857074158001946609249 pos 3/7
74463832547931847158857533574110627724043672075203207 Planck times into the current cycle subdivision
```
- **Above the selected row:** Parents—masks engaging one more prime. A larger divisor, a smaller part, a finer resolution: the subdivisions the current one contains.
- **Selected row (▶ ◀):** The active mask, split into its cosmic and cycle components.
- **Below:** Children—masks engaging one fewer prime. Coarser: the subdivisions that contain the current one. The Whisper sits at the bottom of every chain.
- **pos n/total:** Which tick of its own subdivision each channel is currently in, over how many ticks one traversal has, which is the channel's divisor. A single cosmic prime's tick is wider than the age of the universe, so its position is 0 and will remain 0 for some 10³⁰ years through the finest of them, Nandyte, and for some 10⁷⁶ through Notyte, as shown; combine cosmic primes and the ticks shrink accordingly. Once a Phi, a Psi or the cosmic primes make the fraction one of fifty-digit integers, both numbers go to three significant figures and a power of ten; the column is thirty-six cells wide and the universe is not.
- **Remainder:** Planck times into the current tick on the engaged channel—the cycle channel when both are engaged, since that is the one that turns over within a human lifetime.
### One Line, For Logs
```bash
$ loic-cli --line heptad,pentad
[Whisper:0/1] [Pentad×Heptad:4/35] [14910371370088740558946097962660484558587321198353411]
$ loic-cli --line # through an entropy-selected mask, ~25% collapse
```
Three fields, split on whitespace: the cosmic channel, the cycle channel, the remainder. A channel is its active primes joined with `×`, or `Whisper` when it has none, then `n/total`: the tick of that channel's own subdivision the instant falls in, over the ticks in one traversal. The remainder is the Planck times into the current tick on the engaged channel — the cycle channel when both are. Every number in full; a log has no column to fit. Without a mask the question is unframed, and the oracle answers it the way it always does.
### Cosmological Queries
```bash
$ loic-cli --cosmic # Planck times since the Big Bang
$ loic-cli --terminal # Planck times until heat death
$ loic-cli --progress # Your position in all of time, all 154 digits of it (~10^-93)
$ loic-cli --whisper # Planck times since The Whisper (the epoch)
$ loic-cli --constants # The cosmological constants, and what your kernel believes TAI is
```
### Forbidden Commands
Certain operations are heretical. Attempting them exits with a sermon and status 1:
```bash
$ loic-cli --gregorian # HERESY
$ loic-cli --float # HERESY
$ loic-cli --timezone # HERESY
$ loic-cli --leap # HERESY
```
The full list: `--gregorian`, `--unix`, `--float`, `--iso8601`, `--timezone`, `--leap`, `--round`, `--julian`.
## Platform Requirements
Requires Linux with `CLOCK_TAI` support (kernel 3.10+), and a kernel that has been told what TAI is. `CLOCK_TAI` is `CLOCK_REALTIME` plus an offset that only a time daemon with a leap-second table will set: chrony with `leapseclist /usr/share/zoneinfo/leap-seconds.list` or `leapsectz right/UTC`, or ntpd with a `leapfile`. systemd-timesyncd never does. On a machine where the offset is zero, every observing command refuses to run and says why; `--constants` and `--help` still work, so the reason can be read. The oracle cannot divine the current moment on operating systems that have forfeited their right to know what time it is, and it will not pretend to on ones that merely haven't asked.
## License
Dual-licensed under AGPL-3.0 and the Loic Public License. See the workspace root for the terms, and the workspace README for the theoretical substrate the license keeps citing.

2053
crates/loic-cli/src/main.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,62 @@
# The Observatory: the calendar rendered on a GPU, with one observer thread
# per logical CPU behind the picture. Not published — it is a binary, and it
# goes out attached to a release beside the oracle.
[package]
name = "loic-gui"
version.workspace = true
edition = "2024"
authors.workspace = true
repository.workspace = true
license-file.workspace = true
description = "A temporal meditation interface for the Loic Calendar"
publish = false
# What the Observatory stands on. Each dependency is here for one stated
# reason, and the reason is stated beside it.
[dependencies]
# The calendar, at the workspace's one version. Every observer thread and
# the main thread's one observation per frame call into it, and nothing on
# the screen is derived from anything else.
loic.workspace = true
# The GPU: surfaces, pipelines, buffers and shaders, through which every
# pixel of the Observatory is drawn.
wgpu = "30"
# The window and its events, Wayland only. `winit`'s `x11` feature would
# pull in `libX11`, `x11rb` and their kin as build dependencies, and so it
# is not enabled: the Observatory links only against Wayland. X11 is not
# where desktop Linux is going, and a project that refuses floating-point in
# a timestamp is not going to make its first compromise for a display
# server. `wayland-dlopen` loads the Wayland client library at run time
# rather than at link time; `wayland-csd-adwaita` draws the window's own
# decorations on compositors that decline to draw them; `rwh_06` is the
# `raw-window-handle` 0.6 handle wgpu asks for when it makes a surface of
# the window.
winit = { version = "0.30", default-features = false, features = ["wayland", "wayland-dlopen", "wayland-csd-adwaita", "rwh_06"] }
# `block_on` for the two asynchronous requests wgpu insists on — an adapter,
# then a device — run to completion on the calling thread, without an async
# runtime brought in to wait for two things.
pollster = "1"
# For `setpriority(2)`: the Observatory asks for nice -11 before it looses
# its observers, and threads inherit the value at creation, so one call
# before the spawn is one call for all of them.
libc = "0.2"
# `Pod` and `Zeroable`, derived, for the structures that cross to the GPU as
# bare bytes: the derive proves at compile time that a structure has no
# padding it would be undefined to read, which is the only kind of proof a
# vertex deserves.
bytemuck = { version = "1.25", features = ["derive"] }
# Audio output, for the quantum hum. Audio synthesis is the one place in the
# workspace where floating-point arithmetic is tolerated, on the grounds
# that a loudspeaker is an analog device and nothing it renders was ever
# exact to begin with.
rodio = "0.22"
# The binary target, named and placed explicitly rather than inferred.
[[bin]]
name = "loic-gui"
path = "src/main.rs"

148
crates/loic-gui/README.md Normal file
View file

@ -0,0 +1,148 @@
# loic-gui
The Loic Observatory—a temporal meditation interface.
## What It Shows
The Observatory renders the current moment with obsessive precision. Layout, top to bottom:
### Header
A single line at the top showing observation rate (`obs/sec`) and render rate (`renders/sec`). The observer threads sample `LoicInstant::now()` at whatever rate the kernel's clock can be read; the number on the left is their summed rate, and the header is the only place it is reported, because it is the only place it matters.
### The Digit Waterfall
The cosmic time—Planck times elapsed since Creation (the Big Bang)—rendered as a cascade of digits below the header. Each digit position updates at a different frequency, from the leftmost (geological timescales) to the rightmost (faster than perception). The shimmer is real: time passing at 10⁴³ Planck times per second.
The colours are counted from the last digit, because that is where time moves. The last 34 digits are cyan: 10³⁴ Planck times fit in a nanosecond, and every one of those digits is the entropy of the observation, fresh each frame. The 9 before them are gray: nanosecond to second, faster than perception. Everything above is white and changes slower than once a second. The count grows with the age of the universe; the zones do not.
The digits are 61 today and will be 154 at Annihilation. The waterfall reserves four rows of the largest font for them and, when the count outgrows the reserve, steps the font down by an integer factor and carries on: the first step holds 120 digits, the next 200. The one shrink falls at 10¹²⁰ Planck times, around the year 1.7 × 10⁶⁹, and nothing below the waterfall moves, then or ever.
### The Mask Wheels
Two wheels in the middle, **COSMIC** on the left and **CYCLE** on the right, one per channel. Each wheel shows its selection's whole neighbourhood in the lattice: every mask with one more prime above it, every mask with one fewer below it, and the selection itself, named in full, between them. A neighbour is labelled by the one edge that reaches it. `× Sigma` is the mask whose divisor is the selection's multiplied by Sigma, one prime finer; `÷ Dyad` is the selection's divided by Dyad, one prime coarser. The strip is always one row per prime plus the selection, so the Whisper sits at the bottom of its wheel beneath seven or eight parents, and the full mask at the top above its children. The two selections compose the 15-bit observer mask.
Under each wheel, `pos n/total`: the tick of that channel's own subdivision the instant falls in, over the ticks in one traversal, which is the channel's divisor. Both numbers go to three significant figures and a power of ten once they outgrow the column. Below both wheels, a single line shows the Planck times into the current tick, on the cycle channel when it is engaged and on the cosmic channel otherwise, and says which.
Interaction:
- **Scroll** over a wheel: up selects the parent directly above (the lowest inactive prime joins), down the child directly below (the lowest active prime leaves). At the full mask, up loops to the Whisper; at the Whisper, down loops to the full mask. A wheel has no top.
- **Click** any neighbour: jump to it. Every mask is reachable by clicks alone, in at most seven or eight steps from the Whisper.
A `[ random ]` button below the wheels invokes the entropy default observer—nine bits of hardware entropy select a mask. With probability 75%, the wheels jump to the resulting valid mask. With probability 25%, the cosmic pool overflows: the universe has rejected the unframed query, and a topological scar manifests at a random screen location.
See *Topological Scars* below.
### The Timeline
A navigable visualization spanning all of time, from Creation at the left to Annihilation at the right, sitting just above the coordinate cards. The entire span is 10¹⁵⁴ Planck times, and the present is 10⁻⁹³ of the way along it, which is why the full view shows nothing at all: every event is hidden until you have zoomed in far enough for it to be worth mentioning. Scroll over the bar to zoom into the segment under the cursor, scroll the other way to back out, and click a marker to read the event's passage.
There are some sixty events, tiered by how far in you must be to see each: the first stars, the Solar System and the Sun's death at the widest views of the past; the Snowball Earth, the Cambrian and the Great Dying once the window is a billion years wide; the Whisper and, sixty-two days after it, the Unix epoch, when the window is a decade wide. The far future is where most of the zooming happens, and where the entries of the widest views are: the last stars, the dispersal of galaxies, proton decay if there is any, Dyson's rocks flowing into spheres, the white dwarfs eroding away, Sagittarius A* evaporating, and the last black hole, at a googol years. The passages say what is established, what is argued, and what is a calculation on an assumption; the timeline marks a conjecture at its date without pretending it is a fact, and the one entry with even odds of not happening at all says so in its name.
### The Progress Decimal
Between the timeline and the cards, the fraction of everything that has happened so far, as a decimal with all 154 of its places, wrapped to the width: ninety-two zeros, and then digits. It is derived from the frame's own observation, like everything else on the surface, and its last places move.
### Coordinate Cards
Three panels at the bottom showing:
- **COSMIC TIME** — Planck times since the Big Bang
- **WHISPER TIME** — Planck times since the Loic epoch (first ARPANET transmission)
- **ANNIHILATION TIME** — Planck times until heat death
### Audio
A continuous **quantum hum**—background noise sampled fresh from `getrandom` at 44.1 kHz, low-pass filtered, and modulated by a slow random walk. The hum never repeats. The kernel's entropy pool guarantees that.
No transition sounds. The lattice has no seconds, minutes, hours, days, months, or years to mark, and a tone at a boundary that does not exist would be a lie in the audible range. The hum is what a calendar sounds like from underneath.
## Topological Scars
Each invocation of the random observer that lands on a cosmic-pool overflow leaves a scar—a frozen visual record of the malformed question. Scars manifest at random screen locations, on top of all other UI, and persist until the application exits.
Three variants, picked uniformly per crash:
- **GIN gear**: a ~100-pixel-wide glyph rendered as the 21-bit GIN waveform from the project's logo seam, randomly rotated. Each tooth is one bit set in the binary encoding of "GIN."
- **Failed mask**: the cosmic boundary as a thin ring with seven dots placed around it (one per cosmic prime—filled if active in the failed entropy, hollow otherwise). A red phantom dot dangles outside the ring, connected by a thin line, marking where bit 7 would have gone if the cosmic lattice extended that far. It does not.
- **Soliton**: 3–6 concentric amber rings emanating from a point. Inner rings are most opaque; outer rings fade. The workspace README, section 4.5: *"the holes left in the weave stay in the cloth, and the cloth is spacetime."*
Scars block clicks and scroll on their visible (non-transparent) pixels. You may click and scroll through the gaps between an artifact's primitives to interact with the UI underneath. The scars themselves are inert.
To clear them, restart the application.
## Installation
### From Source
```bash
cargo build --release --package loic-gui
./target/release/loic-gui
```
### The Icon
On Wayland a window does not carry its own icon; launchers, taskbars and switchers find it by looking up the desktop entry whose file name matches the window's `app_id`, which the Observatory sets to `loic-observatory`. The entry is `loic-observatory.desktop` in this directory and the icons are in `icons/`, rendered from the logo itself. To install both for one user:
```bash
install -Dm644 loic-observatory.desktop ~/.local/share/applications/loic-observatory.desktop
for s in 16 32 48 64 128 256 512; do
install -Dm644 icons/loic-observatory-$s.png ~/.local/share/icons/hicolor/${s}x${s}/apps/loic-observatory.png
done
```
The entry runs `loic-gui` from `PATH`; point its `Exec=` line at the binary's full path if it lives elsewhere. The icons are the logo itself, rendered at the seven sizes the hicolor theme expects.
## Requirements
- **Linux** with `CLOCK_TAI`, and a kernel that has been told the TAI−UTC offset. A time daemon that reads a leap-second table sets it (chrony with `leapseclist` or `leapsectz`, ntpd with `leapfile`); systemd-timesyncd never will. On a kernel whose offset is zero the Observatory opens, renders the library's verdict as its only frame, and observes nothing. It refuses to lie.
- **Wayland.** The X11 path is not compiled.
- **GPU** with Vulkan, or OpenGL as the one permitted fallback (wgpu backend). The Observatory renders on the GPU the compositor lives on: it asks the driver for no preference and takes the first device offered, so on a machine with two GPUs `DRI_PRIME=1` sends it to the other one, as with any Mesa application. A discrete GPU buys it nothing; its frames are a few thousand glyph quads, and every one of them would have to cross the bus to be composited. The adapter, backend, present mode and surface format are printed once on standard error at startup.
- **Audio device** (optional, for the quantum hum)
## Controls
| Input | Action |
|-------|--------|
| Scroll over wheel | Step to the neighbour above (finer) or below (coarser); loops at the ends |
| Click wheel row | Jump to that neighbour |
| Click `[ random ]` | Invoke entropy observer (~25% triggers a scar) |
| Scroll over timeline bar | Zoom into the segment under the cursor, or back out |
| Click timeline bar | Zoom into that segment |
| Click timeline event | Show cosmic passage |
| Click passage | Dismiss overlay |
| Click on scar | Nothing — scars are inert |
| Backspace | Close passage / step back one zoom level |
| Escape | Reset timeline / close passage |
## Architecture
One observer thread per logical CPU, and the main thread:
- **Observers** — Each samples `LoicInstant::now()` as fast as the kernel's clock can be read, counts its collapses on a tally of its own, and reads none of them. Every core the machine has, at full tilt, observing moments nobody will see. That is the meditation. It is also why the fans are on.
- **Main thread** — Makes exactly one observation per frame, derives everything on screen from that single instant (the waterfall, the cards, the progress decimal, the timeline's "now", the wheels' offset), renders it via wgpu, and handles window events. The screen never shows two moments at once.
The observers' summed rate and the render rate are independent; the header reports both, and how many observers there are. The Observatory is not nice: before it looses the observers it asks the kernel for a nice value of −11, the most a desktop's usual limit grants an unprivileged process, and every thread inherits it, so whatever else the machine is doing yields to the observation of moments nobody will see. If the kernel declines, it says so once on standard error and observes at the priority of everything else.
## Performance
The Observatory targets maximum frame rate with minimal latency:
- GPU-accelerated text rendering via custom glyph atlas
- Instanced digit rendering for the waterfall display
- One relaxed atomic per observer between the threads, and nothing else
- No VSync where the surface offers an alternative (temporal observation should not be throttled); the present mode is printed at startup
On capable hardware, expect thousands of frames per second. The digits will blur. This is correct.
## The Point
The Observatory does nothing useful whatsoever.
It does not schedule meetings. It does not set alarms. It does not convert to Gregorian. It shows you one thing: Now, expressed with more precision than any human could perceive, contextualized against the entire span of cosmic time, with the option to ask the universe a malformed question and accumulate frozen records of the failures across your screen.
You are approximately 10⁻⁹³ of the way through everything that will ever happen.
The Observatory exists to make this viscerally apparent.
## License
Dual-licensed under AGPL-3.0 and the Loic Public License.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 447 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 575 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 703 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 852 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3 KiB

View file

@ -0,0 +1,12 @@
[Desktop Entry]
Type=Application
Version=1.0
Name=The Loic Observatory
GenericName=Temporal Meditation Surface
Comment=Shows you one thing, Now, at millions of observations per second, and does nothing useful whatsoever
Exec=loic-gui
Icon=loic-observatory
Terminal=false
Categories=Science;
Keywords=time;planck;calendar;observatory;TAI;lattice;
StartupNotify=false

View file

@ -0,0 +1,832 @@
//! # The Renderer of Topological Scars
//!
//! Each invocation of the entropy default that strikes the cosmic-pool
//! overflow — one time in four, as the workspace README, section 7.3, says
//! it will — leaves an artifact behind: a frozen record of a question that
//! could not be framed coherently, the Observatory's counterpart to the
//! ghost process the oracle leaves in the process table. This module
//! rasterizes those records onto the GPU as triangulated geometry — filled
//! circles, annuli, and rotated rectangles, all expressed in pixel
//! coordinates and transformed to clip space by the artifact shader — and
//! answers, for the rest of the Observatory, the question of whether a
//! click landed on one, since a scar has the final word on its own real
//! estate and the interface beneath it is not reachable again until the
//! process is restarted. The scars are the calendar's reading of the
//! workspace README, section 4.5, in pixels: the holes left in the weave
//! stay in the cloth.
//!
//! The geometry generation lives in this module too. Each `Artifact`
//! variant produces a list of `ArtifactVertex` values — position plus RGBA
//! — which the renderer concatenates into a single vertex buffer per frame.
//! No instancing, no indexing, no clever batching beyond "one vertex
//! buffer, one draw call." Scars are sparse; the simple approach suffices,
//! and a scar that took effort to draw would be a scar that cared how it
//! looked, which is not the kind of thing a scar is.
use wgpu::util::DeviceExt;
use crate::Artifact;
/// The number of vertices the buffer is allocated for, once, at
/// construction: 65,536, which is a megabyte and a half of vertex at
/// twenty-four bytes each. A soliton of six rings at sixty-four segments is
/// the largest scar, 2,304 vertices; a failed mask is between seven hundred
/// and a thousand, depending on how many of its dots are hollow; a gear is
/// seventy-two. Twenty-eight of the largest fit, and past that `update`
/// keeps the first 65,536 vertices and drops the rest silently, which at
/// one collapse in four clicks is a state of affairs some hundred clicks
/// away and, for a scar, an appropriate way to be forgotten.
const MAX_VERTICES: u64 = 65_536;
/// The uniform block the artifact shader reads: the surface's size in
/// pixels, by which pixel coordinates become clip coordinates, padded to
/// sixteen bytes, which is what the uniform address space rounds a struct
/// of one `vec2<f32>` up to, so that this side and the shader agree on how
/// much there is to read.
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct Uniforms {
/// The surface's width and height in pixels.
screen_size: [f32; 2],
/// Eight bytes of nothing, so that the block is sixteen.
_pad: [f32; 2],
}
/// One vertex of a scar: a position in pixels and a colour with alpha, six
/// floats, twenty-four bytes, the layout the shader's two attributes read.
/// Positions are in pixels from the window's top-left corner, because that
/// is where the click arrived in and where the hit tests live; the shader
/// carries them to clip space, so that nothing on this side has to think
/// in the GPU's coordinates.
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct ArtifactVertex {
/// Where, in pixels from the window's top-left corner.
position: [f32; 2],
/// What colour, as red, green, blue and alpha, each from zero to one.
color: [f32; 4],
}
/// The GPU state for the scars: a pipeline, the vertex buffer every frame's
/// geometry is rewritten into, the uniform block, its bind group, and the
/// count of vertices the last `update` produced, which is the count the
/// next `render` draws. One of these exists, owned by the render state, and
/// what it draws only accumulates.
pub struct ArtifactRenderer {
/// The render pipeline: `artifact.wgsl`'s two stages, alpha blending,
/// a triangle list, and the defaults for everything else.
pipeline: wgpu::RenderPipeline,
/// Room for `MAX_VERTICES` vertices, allocated once and filled from the
/// front on every frame.
vertex_buffer: wgpu::Buffer,
/// The sixteen-byte uniform block: the surface's size, and padding.
uniform_buffer: wgpu::Buffer,
/// The one binding, the uniform block, for the vertex stage.
bind_group: wgpu::BindGroup,
/// How many vertices the last `update` wrote, and therefore how many
/// the next `render` draws; zero until the first collapse.
vertex_count: u32,
}
impl ArtifactRenderer {
/// Assemble the renderer for a surface of the given `format`: the
/// uniform block at a placeholder size the first `resize` corrects, a
/// vertex buffer of `MAX_VERTICES` vertices allocated in one piece and
/// never grown, the single bind group, the shader compiled from source
/// embedded in the binary, and a pipeline that consumes the vertex
/// layout — a `Float32x2` position at offset zero and a `Float32x4`
/// colour at offset eight — as a triangle list with alpha blending. No
/// scar exists yet; the count is zero and the buffer's contents are
/// whatever they are, which is fine, since nothing reads past the
/// count.
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
let uniforms = Uniforms {
screen_size: [800.0, 1000.0],
_pad: [0.0; 2],
};
let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("artifact_uniforms"),
contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("artifact_vertex_buffer"),
size: MAX_VERTICES * std::mem::size_of::<ArtifactVertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("artifact_bind_group_layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("artifact_bind_group"),
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
}],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("artifact_pipeline_layout"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("artifact_shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/artifact.wgsl").into()),
});
let vertex_buffer_layout = wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<ArtifactVertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 8,
shader_location: 1,
format: wgpu::VertexFormat::Float32x4,
},
],
};
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("artifact_pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[Some(vertex_buffer_layout)],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: wgpu::PipelineCompilationOptions::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
Self {
pipeline,
vertex_buffer,
uniform_buffer,
bind_group,
vertex_count: 0,
}
}
/// Take note of the surface's new size by rewriting the uniform block:
/// the geometry is in pixels and does not care, but the shader that
/// takes pixels to clip space must know how many pixels there are. The
/// Observatory calls this once, after construction, since its window
/// does not resize, and the scars stay where they were put.
pub fn resize(&self, queue: &wgpu::Queue, width: u32, height: u32) {
let uniforms = Uniforms {
screen_size: [width as f32, height as f32],
_pad: [0.0; 2],
};
queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms]));
}
/// Rebuild the vertex buffer from the current list of scars: every
/// artifact's geometry, generated afresh and concatenated in list order,
/// written to the buffer from the front, and the count recorded for the
/// draw. Called every frame, whether or not the list changed, because a
/// frame is cheap and remembering whether the list changed is a way to
/// be wrong. Past `MAX_VERTICES` the excess is dropped, the buffer being
/// what it is; nothing is written at all when there is nothing to
/// write, so an Observatory that has never collapsed never touches the
/// buffer.
pub fn update(&mut self, queue: &wgpu::Queue, artifacts: &[Artifact]) {
let mut verts = Vec::new();
for a in artifacts {
generate_artifact_vertices(a, &mut verts);
}
let count = (verts.len() as u64).min(MAX_VERTICES);
if count > 0 {
queue.write_buffer(
&self.vertex_buffer,
0,
bytemuck::cast_slice(&verts[..count as usize]),
);
}
self.vertex_count = count as u32;
}
/// Draw every scar into the frame's render pass, after everything else,
/// so that they lie on top of it: one draw call over the vertices the
/// last `update` produced, or no call at all when there are none. A
/// scar drawn last is a scar that cannot be covered, which is the
/// point; the Observatory's other panels are painted beneath it and
/// stay beneath it until the process ends.
pub fn render<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
if self.vertex_count == 0 {
return;
}
render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.draw(0..self.vertex_count, 0..1);
}
}
/// The cell a position falls in, counting from zero, or `None` to the left
/// of the first cell: the floor of a non-negative quotient is the cell, and
/// a negative quotient is a point outside the row, which no cell claims.
/// The `floor` is explicit and the cast merely confirms it; the truncation
/// clippy warns of is the selection being made.
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "floored, a non-negative quotient is the cell the point lies in; the cut is the choice"
)]
fn cell_index(quotient: f32) -> Option<usize> {
(quotient >= 0.0).then(|| quotient.floor() as usize)
}
/// Hit-test a click against a scar's blocking shape: `true` if the click
/// falls on what would visually be a non-transparent pixel of the artifact,
/// approximated by the artifact's structural primitives — the baseline and
/// teeth of a gear, the ring and dots and phantom of a failed mask, the
/// rings of a soliton — since the pixels themselves are on the GPU and are
/// not read back for anyone. The Observatory asks this of every scar before
/// it lets a click or a scroll reach the wheels, the bar or the button, and
/// a `true` from any of them ends the matter.
///
/// The hit shapes are deliberately approximate but tight enough to feel
/// natural: clicking through a transparent gap reaches the interface
/// underneath, clicking on a tooth, a dot or a ring does not.
pub fn artifact_hit(artifact: &Artifact, click_x: f32, click_y: f32) -> bool {
match *artifact {
Artifact::GinGear {
x,
y,
rotation_deg,
size,
} => gin_gear_hit(x, y, rotation_deg.to_radians(), size, click_x, click_y),
Artifact::FailedMask {
x,
y,
entropy_bits,
size,
} => failed_mask_hit(x, y, entropy_bits, size, click_x, click_y),
Artifact::Soliton {
x,
y,
ring_count,
radius,
} => soliton_hit(x, y, ring_count, radius, click_x, click_y),
}
}
/// Whether a click lands on a GIN gear: the click is carried into the
/// glyph's own frame by the inverse of its rotation, and tested there
/// against the baseline bar and against each tooth, the same rectangles
/// `gen_gin_gear` draws, with the same tenth of a cell of padding taken off
/// either side of a tooth. Rotation is the one trigonometric act in the
/// hit test, and it is performed on pixels, which forgive it.
fn gin_gear_hit(cx: f32, cy: f32, rot: f32, size: f32, px: f32, py: f32) -> bool {
// Carry the click into the glyph's local frame by rotating it the other
// way about the glyph's centre.
let dx = px - cx;
let dy = py - cy;
let cos_r = rot.cos();
let sin_r = rot.sin();
let lx = dx * cos_r + dy * sin_r;
let ly = -dx * sin_r + dy * cos_r;
let half_w = size / 2.0;
let baseline_h = size * 0.10;
let tooth_h = size * 0.30;
let cell_w = size / GIN_BITS.len() as f32;
// The baseline: a bar the full width of the glyph, from y = 0 down to
// y = baseline_h, in a frame where y grows downward.
if lx >= -half_w && lx <= half_w && ly >= 0.0 && ly <= baseline_h {
return true;
}
// The teeth: each set bit of GIN occupies its cell above the baseline,
// rising tooth_h; the cell is found by dividing the offset from the
// glyph's left edge by the cell width and flooring.
if ly >= -tooth_h
&& ly < 0.0
&& let Some(cell_idx) = cell_index((lx + half_w) / cell_w)
&& GIN_BITS.get(cell_idx).copied().unwrap_or(false)
{
{
// Inside this tooth's cell horizontally. The tenth of a cell of
// padding on either side that the renderer leaves, so that
// adjacent teeth do not merge, is left out of the hit as well,
// so that what blocks is exactly what is seen.
let cell_left = -half_w + (cell_idx as f32) * cell_w;
let pad = cell_w * 0.10;
if lx >= cell_left + pad && lx <= cell_left + cell_w - pad {
return true;
}
}
}
false
}
/// Whether a click lands on a failed mask: on the boundary ring, on any of
/// the seven dots, on the phantom dot beyond the ring, or on the thin line
/// that joins the ring to the phantom, each tested as the disc, annulus or
/// band that `gen_failed_mask` draws. Every dot blocks whether it is drawn
/// filled or hollow, so the entropy bits, which decide the filling, decide
/// nothing here.
fn failed_mask_hit(cx: f32, cy: f32, entropy_bits: u16, size: f32, px: f32, py: f32) -> bool {
let r_outer = size / 2.0;
let r_ring_thickness = size * 0.04;
let dot_r = size * 0.06;
let phantom_offset = size * 0.35;
let dx = px - cx;
let dy = py - cy;
let dist_sq = dx * dx + dy * dy;
// The boundary ring: the annulus between r_outer less the thickness
// and r_outer, tested on squared distances, since a square root would
// be work and would change no verdict.
let inner = r_outer - r_ring_thickness;
let outer = r_outer;
if dist_sq >= inner * inner && dist_sq <= outer * outer {
return true;
}
// The seven prime-dots around the ring, at the same seven angles the
// renderer uses, starting from the top and going round by sevenths.
let dot_r_outer = r_outer - r_ring_thickness * 2.0;
for bit in 0..7u8 {
let angle = -std::f32::consts::FRAC_PI_2 + f32::from(bit) * (std::f32::consts::TAU / 7.0);
let bx = cx + dot_r_outer * angle.cos();
let by = cy + dot_r_outer * angle.sin();
let bdx = px - bx;
let bdy = py - by;
// A dot is filled if its prime is active and hollow if not, and
// both are hit as the whole disc; a hollow ring with a hole one
// could click through would be a scar with a loophole.
if bdx * bdx + bdy * bdy <= dot_r * dot_r {
return true;
}
// The entropy bits are acknowledged and not consulted: the shapes
// are identical for hit purposes, and the bits decide only fill or
// stroke, which is the renderer's business. Naming them here is how
// the compiler is told they were not forgotten.
let _ = entropy_bits;
}
// The phantom dot outside the boundary, at the eighth slot's angle,
// pushed out beyond the ring by the phantom offset.
let phantom_angle = -std::f32::consts::FRAC_PI_2 + 7.0 * (std::f32::consts::TAU / 7.0);
let pdx = cx + (r_outer + phantom_offset) * phantom_angle.cos();
let pdy = cy + (r_outer + phantom_offset) * phantom_angle.sin();
let phx = px - pdx;
let phy = py - pdy;
if phx * phx + phy * phy <= dot_r * dot_r {
return true;
}
// The thin line from the boundary to the phantom dot, approximated for
// hit purposes as a band three times the drawn line's width, so that a
// line a pixel or so wide can be hit by a person with a pointer.
let line_thickness = size * 0.012;
let lx0 = cx + r_outer * phantom_angle.cos();
let ly0 = cy + r_outer * phantom_angle.sin();
if point_near_segment(px, py, lx0, ly0, pdx, pdy, line_thickness * 1.5) {
return true;
}
false
}
/// Whether a click lands on a soliton: on any of its concentric rings, each
/// tested as the annulus `gen_soliton` draws, of the same radius and the
/// same thickness — eighteen percent of the ring pitch — on squared
/// distances. The gaps between the rings let the click through, as the
/// gaps in a ripple would let a stone through, if stones were clicks.
fn soliton_hit(cx: f32, cy: f32, ring_count: u8, outer_radius: f32, px: f32, py: f32) -> bool {
let count = ring_count.max(1) as usize;
let thickness = (outer_radius / count as f32) * 0.18;
let dx = px - cx;
let dy = py - cy;
let dist_sq = dx * dx + dy * dy;
for i in 0..count {
let r = outer_radius * (i + 1) as f32 / count as f32;
let inner = r - thickness;
let outer = r;
if dist_sq >= inner * inner && dist_sq <= outer * outer {
return true;
}
}
false
}
/// Whether a point lies within `threshold` of the segment from `(x0, y0)`
/// to `(x1, y1)`: the point is projected onto the segment's line, the
/// projection clamped to the segment's ends, and the squared distance to
/// the clamped point compared with the squared threshold. A segment shorter
/// than a thousandth of a pixel is treated as no segment at all, since a
/// division by its length would be a division by nothing wearing a decimal
/// point. Used for the phantom line of the failed mask, and for nothing
/// else.
fn point_near_segment(
px: f32,
py: f32,
x0: f32,
y0: f32,
x1: f32,
y1: f32,
threshold: f32,
) -> bool {
let dx = x1 - x0;
let dy = y1 - y0;
let len_sq = dx * dx + dy * dy;
if len_sq < 1e-6 {
return false;
}
let t = ((px - x0) * dx + (py - y0) * dy) / len_sq;
let t = t.clamp(0.0, 1.0);
let cx = x0 + t * dx;
let cy = y0 + t * dy;
let d2 = (px - cx).powi(2) + (py - cy).powi(2);
d2 <= threshold * threshold
}
// ═══════════════════════════════════════════════════════════════════════════
// Geometry generation: the three scars, as triangles, in pixels
// ═══════════════════════════════════════════════════════════════════════════
/// The colour of the live calendar: white with a cast of cream, at
/// eighty-five percent — the colour of the cosmic span, and of a gear's
/// bar and teeth, and of a dot whose prime is active.
const COL_WHITE: [f32; 4] = [0.92, 0.92, 0.95, 0.85];
/// Amber, the project's primary accent, the colour of the headers and the
/// carets; here it is the colour of a soliton's rings, before their alpha
/// is tuned ring by ring.
const COL_AMBER: [f32; 4] = [0.95, 0.65, 0.20, 0.85];
/// Dim gray, for what is inactive or decayed: a failed mask's boundary
/// ring, and a dot whose prime the entropy did not choose.
const COL_DIM: [f32; 4] = [0.45, 0.45, 0.50, 0.65];
/// The phantom's colour: red-tinted and dim, denoting the bit that
/// overflowed — the eighth dot of a seven-dot lattice, and the line that
/// points to where it would have gone.
const COL_PHANTOM: [f32; 4] = [0.85, 0.25, 0.25, 0.70];
/// The GIN bit pattern from the project's logo seam: G = 1000111,
/// I = 1001001, N = 1001110 — twenty-one bits, which are the seven-bit
/// ASCII codes of the three letters, 71, 73 and 78, most significant bit
/// first. Each 1 is a tooth of the gear and each 0 a gap; eleven teeth in
/// all, and the letters are legible in them if you know to look.
const GIN_BITS: [bool; 21] = [
true, false, false, false, true, true, true, // G
true, false, false, true, false, false, true, // I
true, false, false, true, true, true, false, // N
];
/// Append one scar's geometry to `out`, dispatching on its variant: a
/// gear's rotation is given in degrees by the artifact and in radians to
/// the generator, and everything else is passed through as it came.
fn generate_artifact_vertices(artifact: &Artifact, out: &mut Vec<ArtifactVertex>) {
match *artifact {
Artifact::GinGear {
x,
y,
rotation_deg,
size,
} => {
gen_gin_gear(x, y, rotation_deg.to_radians(), size, out);
}
Artifact::FailedMask {
x,
y,
entropy_bits,
size,
} => {
gen_failed_mask(x, y, entropy_bits, size, out);
}
Artifact::Soliton {
x,
y,
ring_count,
radius,
} => {
gen_soliton(x, y, ring_count, radius, out);
}
}
}
/// Render the GIN gear glyph: twenty-one cells in a row, the 1 cells raised
/// as teeth above a baseline and the 0 cells flush with it, the whole glyph
/// rotated about `(cx, cy)` by `rot` radians. The baseline is a tenth of
/// the glyph's size tall and the teeth three tenths; each tooth gives up a
/// tenth of its cell on either side so that neighbours do not merge into
/// one long tooth, which would be a different letter.
fn gen_gin_gear(cx: f32, cy: f32, rot: f32, size: f32, out: &mut Vec<ArtifactVertex>) {
let cell_w = size / GIN_BITS.len() as f32;
let baseline_h = size * 0.10; // the baseline: a thin bar, a tenth of the glyph
let tooth_h = size * 0.30; // the teeth rise three tenths above the baseline
let total_w = size;
let cos_r = rot.cos();
let sin_r = rot.sin();
// Emit one quad given in the glyph's local frame — origin at the glyph's
// centre, x along the baseline, y downward — rotated about (cx, cy) and
// appended as two triangles.
let mut emit_quad = |lx: f32, ly: f32, w: f32, h: f32, color: [f32; 4]| {
// The four corners, in the local frame; the glyph is centred
// horizontally on cx.
let local_corners = [[lx, ly], [lx + w, ly], [lx + w, ly + h], [lx, ly + h]];
let world: Vec<[f32; 2]> = local_corners
.iter()
.map(|[x, y]| [cx + x * cos_r - y * sin_r, cy + x * sin_r + y * cos_r])
.collect();
// Two triangles, (0, 1, 2) and (0, 2, 3): the quad, cut along one
// diagonal.
for &i in &[0usize, 1, 2, 0, 2, 3] {
out.push(ArtifactVertex {
position: world[i],
color,
});
}
};
// The baseline: a thin horizontal bar across the full glyph width.
let half_w = total_w / 2.0;
emit_quad(-half_w, 0.0, total_w, baseline_h, COL_WHITE);
// The teeth: one rectangle per 1 bit, rising above the baseline.
for (i, &bit) in GIN_BITS.iter().enumerate() {
if bit {
let lx = -half_w + i as f32 * cell_w;
// A little horizontal padding, a tenth of the cell on each
// side, so that adjacent teeth do not merge.
let pad = cell_w * 0.10;
emit_quad(lx + pad, -tooth_h, cell_w - 2.0 * pad, tooth_h, COL_WHITE);
}
}
}
/// Render the failed-mask glyph: a circle for the cosmic boundary, seven
/// dots arranged around it — one per cosmic prime, filled if the entropy
/// chose that prime and hollow if not — and a phantom eighth dot dangling
/// outside the circle in red, joined to the boundary by a thin line, at the
/// angle the eighth slot would have had if the lattice had one.
///
/// `entropy_bits` is the value the library carries in
/// `LoicError::InvalidMask` — the upper bit, `0x8000`, flags a cosmic-pool
/// selection, and the lower eight bits are the index that overflowed. The
/// active primes are the lower seven bits of that index; its eighth bit,
/// bit 7, is the one that made the index 128 or more, and it is always set
/// here, because an index below 128 would have been a mask and not a scar.
/// The glyph is therefore a picture of the exact malformed question, with
/// the bit that malformed it drawn where the lattice has no room for it.
fn gen_failed_mask(cx: f32, cy: f32, entropy_bits: u16, size: f32, out: &mut Vec<ArtifactVertex>) {
let r_outer = size / 2.0;
let r_ring_thickness = size * 0.04;
let dot_r = size * 0.06;
let phantom_offset = size * 0.35; // how far beyond the boundary the phantom hangs
// The boundary ring: the cosmic limit, dim, forty-eight segments.
gen_ring(
cx,
cy,
r_outer - r_ring_thickness,
r_outer,
48,
COL_DIM,
out,
);
// The seven dots around the ring at evenly spaced angles, starting from
// the top and going round by sevenths: filled where the prime is
// active, a hollow ring where it is not.
let index = (entropy_bits & 0xFF) as u8;
for bit in 0..7u8 {
let angle = -std::f32::consts::FRAC_PI_2 + f32::from(bit) * (std::f32::consts::TAU / 7.0);
let dx = cx + (r_outer - r_ring_thickness * 2.0) * angle.cos();
let dy = cy + (r_outer - r_ring_thickness * 2.0) * angle.sin();
let active = (index >> bit) & 1 == 1;
let color = if active { COL_WHITE } else { COL_DIM };
if active {
gen_filled_circle(dx, dy, dot_r, 16, color, out);
} else {
gen_ring(dx, dy, dot_r * 0.6, dot_r, 16, color, out);
}
}
// The phantom eighth bit, dangling outside the circle in the direction
// of the void: at the angle of the eighth slot, continuing the
// seven-prime pattern forward by one, and pushed out past the boundary
// by the phantom offset, since the lattice has no eighth place to put
// it.
let phantom_angle = -std::f32::consts::FRAC_PI_2 + 7.0 * (std::f32::consts::TAU / 7.0);
let pdx = cx + (r_outer + phantom_offset) * phantom_angle.cos();
let pdy = cy + (r_outer + phantom_offset) * phantom_angle.sin();
gen_filled_circle(pdx, pdy, dot_r, 16, COL_PHANTOM, out);
// A thin line from the boundary toward the phantom dot, dim, saying
// "this is where bit 7 would have gone", which is the whole of what a
// scar has to say.
gen_thin_line(
cx + r_outer * phantom_angle.cos(),
cy + r_outer * phantom_angle.sin(),
pdx,
pdy,
size * 0.012,
COL_PHANTOM,
out,
);
}
/// Render concentric rings emanating from a point, `ring_count` of them —
/// at least one, whatever the count says — out to `outer_radius`, evenly
/// spaced, each eighteen percent of the pitch thick, sixty-four segments
/// apiece. The innermost ring is the most opaque and the rings fade
/// outward, as a ripple does, except that this one is static and will not
/// fade further: the workspace README, section 4.5, says the holes left in
/// the weave stay in the cloth, and this is the Observatory's picture of
/// one.
fn gen_soliton(cx: f32, cy: f32, ring_count: u8, outer_radius: f32, out: &mut Vec<ArtifactVertex>) {
let count = ring_count.max(1) as usize;
let thickness = (outer_radius / count as f32) * 0.18;
for i in 0..count {
let r = outer_radius * (i + 1) as f32 / count as f32;
// Inner rings, low i, most opaque; outer rings faintest: the alpha
// runs from 0.85 down toward 0.30 across the count.
let alpha = 0.85 - (i as f32 / count as f32) * 0.55;
let mut color = COL_AMBER;
color[3] = alpha;
gen_ring(cx, cy, r - thickness, r, 64, color, out);
}
}
// ─── The primitives: a disc, an annulus, a band ─────────────────────────────
/// A filled circle as a triangle fan of `segments` triangles, emitted as a
/// triangle list — centre, one rim point, the next rim point — so that it
/// can share a buffer with everything else. Three vertices a segment; the
/// dots use sixteen, which is round enough at their size.
fn gen_filled_circle(
cx: f32,
cy: f32,
radius: f32,
segments: u32,
color: [f32; 4],
out: &mut Vec<ArtifactVertex>,
) {
let center = ArtifactVertex {
position: [cx, cy],
color,
};
for i in 0..segments {
let a0 = (i as f32) * std::f32::consts::TAU / segments as f32;
let a1 = ((i + 1) as f32) * std::f32::consts::TAU / segments as f32;
let p0 = [cx + radius * a0.cos(), cy + radius * a0.sin()];
let p1 = [cx + radius * a1.cos(), cy + radius * a1.sin()];
out.push(center);
out.push(ArtifactVertex {
position: p0,
color,
});
out.push(ArtifactVertex {
position: p1,
color,
});
}
}
/// An annulus, a filled ring between `inner_radius` and `outer_radius`, as
/// `segments` quads around the circle, each cut into two triangles: six
/// vertices a segment, the price of not indexing. Forty-eight segments go
/// round the boundary of a failed mask, sixty-four round each ring of a
/// soliton, sixteen round a hollow dot.
fn gen_ring(
cx: f32,
cy: f32,
inner_radius: f32,
outer_radius: f32,
segments: u32,
color: [f32; 4],
out: &mut Vec<ArtifactVertex>,
) {
for i in 0..segments {
let a0 = (i as f32) * std::f32::consts::TAU / segments as f32;
let a1 = ((i + 1) as f32) * std::f32::consts::TAU / segments as f32;
let i0 = [cx + inner_radius * a0.cos(), cy + inner_radius * a0.sin()];
let i1 = [cx + inner_radius * a1.cos(), cy + inner_radius * a1.sin()];
let o0 = [cx + outer_radius * a0.cos(), cy + outer_radius * a0.sin()];
let o1 = [cx + outer_radius * a1.cos(), cy + outer_radius * a1.sin()];
// Two triangles per segment, (i0, o0, o1) and (i0, o1, i1): the
// quad between two rim angles, cut along its diagonal.
out.push(ArtifactVertex {
position: i0,
color,
});
out.push(ArtifactVertex {
position: o0,
color,
});
out.push(ArtifactVertex {
position: o1,
color,
});
out.push(ArtifactVertex {
position: i0,
color,
});
out.push(ArtifactVertex {
position: o1,
color,
});
out.push(ArtifactVertex {
position: i1,
color,
});
}
}
/// A thin line from `(x0, y0)` to `(x1, y1)` of the given `thickness`,
/// rendered as one quad — two triangles — offset half the thickness to
/// either side of the segment along its perpendicular. A segment of no
/// length is given a millionth of a pixel to divide by, and draws a quad
/// of no width, which is nothing, correctly.
fn gen_thin_line(
x0: f32,
y0: f32,
x1: f32,
y1: f32,
thickness: f32,
color: [f32; 4],
out: &mut Vec<ArtifactVertex>,
) {
let dx = x1 - x0;
let dy = y1 - y0;
let len = (dx * dx + dy * dy).sqrt().max(1e-6);
// The perpendicular, as a unit vector scaled to half the thickness.
let px = -dy / len * thickness * 0.5;
let py = dx / len * thickness * 0.5;
let p00 = [x0 + px, y0 + py];
let p01 = [x0 - px, y0 - py];
let p10 = [x1 + px, y1 + py];
let p11 = [x1 - px, y1 - py];
// Two triangles, (p00, p01, p11) and (p00, p11, p10): the band, cut
// along its diagonal.
out.push(ArtifactVertex {
position: p00,
color,
});
out.push(ArtifactVertex {
position: p01,
color,
});
out.push(ArtifactVertex {
position: p11,
color,
});
out.push(ArtifactVertex {
position: p00,
color,
});
out.push(ArtifactVertex {
position: p11,
color,
});
out.push(ArtifactVertex {
position: p10,
color,
});
}

View file

@ -0,0 +1,257 @@
//! Audio synthesis for the Loic Observatory: the quantum hum.
//!
//! The Observatory sonifies a single thing, the quantum hum — a continuous
//! background drone derived from the kernel's entropy pool, two fresh bytes
//! of it drawn through `getrandom` for every one of the forty-four thousand
//! one hundred samples of every second, low-pass filtered so that the
//! hiss becomes a rumble, and modulated in amplitude by a random walk so
//! slow that its swells arrive like weather. The hum never repeats. It
//! cannot. The kernel's pool furnishes it eighty-eight thousand two hundred
//! bytes a second that were never furnished before, and a drone made of
//! them has no period to return to.
//!
//! There are no transition sounds, because there are no transitions: the
//! lattice has no seconds, minutes, hours, days, months or years to mark,
//! and a tone sounded at a boundary that does not exist would be a lie in
//! the audible range, which is the one range the calendar had not yet
//! found a way to lie in. The hum does not depend on the calendar and
//! reads no instant. It is what a calendar sounds like from underneath.
//!
//! # On the Matter of Floating-Point
//!
//! The perceptive reader will observe that this module commits, freely and
//! on every line, the cardinal sin of the workspace README, section 1.1:
//! floating-point arithmetic. This is not apostasy but the one exemption
//! the calendar tolerates. Audio synthesis requires continuous waveforms,
//! and the human ear — that imprecise biological instrument, a Channel 1
//! device if ever there was one — cannot distinguish between a sample of
//! 0.4376291 and one of 0.4376290, and could not be made to care.
//!
//! These floating-point values never touch a temporal quantity. No
//! instant, no duration, no Planck count enters this module or leaves it;
//! the samples are confined to the analogue domain, where precision is
//! measured in decibels rather than Planck intervals and where, in any
//! case, the loudspeaker will do worse to the waveform than the mantissa
//! ever did. The waveform cares not for the calendar's purity, and the
//! calendar extends to it this singular dispensation, in writing, here.
use rodio::{ChannelCount, DeviceSinkBuilder, MixerDeviceSink, Player, SampleRate, Source};
use std::num::NonZero;
use std::time::Duration;
/// The sample rate of the generated audio: 44,100 samples per second, the
/// rate of the compact disc and of most digital audio since, chosen here
/// because every audio device on Earth will accept it without complaint
/// and because one hundredth of it, 441, is a whole number of samples at
/// which to update the amplitude.
const SAMPLE_RATE: u32 = 44100;
/// The Observatory's hold on the audio device: the sink the device was
/// opened as, the player the hum sounds through while it sounds, whether
/// audio is enabled at all, and how loud the hum is. To hold an
/// `AudioState` is to keep the hum sounding; to drop it is silence, which
/// is why the Observatory keeps one it never reads.
pub struct AudioState {
/// The device sink, opened once; its mixer is what the hum's player is
/// connected to.
stream: MixerDeviceSink,
/// The hum's player, present while the hum sounds and `None` while it
/// does not; the hum is continuous, so this is `Some` for the life of
/// the Observatory.
quantum_player: Option<Player>,
/// Whether audio is enabled at all. Disabling it stops the hum and
/// declines to start it again.
enabled: bool,
/// The hum's volume, between zero and one: the factor the noise is
/// amplified by on its way to the mixer.
hum_volume: f32,
}
impl AudioState {
/// Opens the default audio device and furnishes the state that holds
/// it, with audio enabled, no hum yet sounding, and the hum's volume
/// set quiet but audible.
///
/// # Returns
///
/// `Some` with the device open, or `None` if no default device could be
/// opened — a machine without audio, or one whose audio is spoken for —
/// in which case the Observatory proceeds in silence. The hum is an
/// accompaniment; the moment does not need it to be observed.
pub fn new() -> Option<Self> {
let stream = DeviceSinkBuilder::open_default_sink().ok()?;
Some(Self {
stream,
quantum_player: None,
enabled: true,
hum_volume: 0.06, // quiet, but present, like the thing it sonifies
})
}
/// Enables or disables all audio. Disabling stops the hum at once and
/// causes any later request to start it to be declined; enabling merely
/// permits, and starts nothing by itself. Offered for an observer who
/// would prefer the moment unsounded; no caller has yet been one.
#[allow(dead_code)]
pub fn set_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
if !enabled {
self.stop_quantum_hum();
}
}
/// Begins the hum: a player is connected to the device's mixer and an
/// endless source of quantum noise, amplified to the hum's volume, is
/// appended to it, whereupon the device draws samples from the source
/// for as long as the player lives. Declined, silently, if audio is
/// disabled or if the hum is already sounding, since two hums would be
/// a chord and the lattice has no chords.
pub fn start_quantum_hum(&mut self) {
if !self.enabled || self.quantum_player.is_some() {
return;
}
let player = Player::connect_new(self.stream.mixer());
// The source has no end; the amplification is the volume, applied
// once to every sample on its way out.
let noise = QuantumNoise::new().amplify(self.hum_volume);
player.append(noise);
self.quantum_player = Some(player);
}
/// Ends the hum: the player is taken from its slot and stopped, and the
/// source it was drawing from is dropped with it. A hum that is not
/// sounding is left not sounding.
#[allow(dead_code)]
pub fn stop_quantum_hum(&mut self) {
if let Some(player) = self.quantum_player.take() {
player.stop();
}
}
}
/// The quantum noise source: the kernel's entropy pool, rendered audible.
/// Two bytes are drawn per sample, one for the noise and one for the slow
/// walk of its amplitude; the noise is low-pass filtered into a rumble that
/// crackles, and the amplitude wanders between three tenths and full over
/// timescales of seconds, so that the drone swells and subsides and never
/// quite settles into anything the ear could call a note. The provenance
/// is exactly the kernel's own, per the workspace README, section 5.1: not
/// provably quantum, not disprovably.
struct QuantumNoise {
/// The one-pole low-pass filter's state: the previous output sample,
/// which the next output is three quarters made of.
filter_state: f32,
/// The filter's coefficient, between zero and one, higher being more
/// smoothing: the fraction of each output that is the previous output
/// rather than fresh noise.
filter_coeff: f32,
/// The current amplitude envelope, between three tenths and one, driven
/// by the random walk below.
amplitude: f32,
/// The random walk's state: a very slowly filtered noise value between
/// minus one and one, from which the amplitude is mapped.
amp_filter_state: f32,
/// The count of samples produced, wrapping, from which the amplitude's
/// hundred-hertz update cadence is derived.
sample_count: u32,
}
impl QuantumNoise {
/// A fresh source: filter at rest, amplitude at half, walk at zero, no
/// samples yet produced.
fn new() -> Self {
Self {
filter_state: 0.0,
filter_coeff: 0.75, // less smoothing, so the entropy crackles through
amplitude: 0.5,
amp_filter_state: 0.0,
sample_count: 0,
}
}
}
impl Iterator for QuantumNoise {
type Item = f32;
/// One sample of the hum, forty-four thousand one hundred times a
/// second for as long as the device keeps asking. The source never
/// ends: a sample is always furnished, and if the kernel's pool cannot
/// be read the sample is silence rather than the end of the stream,
/// since a hum that stopped would be marking a transition and there are
/// none to mark.
fn next(&mut self) -> Option<f32> {
self.sample_count = self.sample_count.wrapping_add(1);
// Two fresh bytes from the kernel's pool, per sample. A pool that
// cannot be read yields silence for this sample and is asked again
// for the next.
let mut entropy = [0u8; 2];
if loic::getrandom::fill(&mut entropy).is_err() {
return Some(0.0);
}
// The first byte is the noise itself, mapped from its 256 values to
// the range from minus one up to just short of one — not quite
// symmetric about zero, which no ear can hear and the calendar
// declines to notice in a domain it has already ceded.
let raw = (f32::from(entropy[0]) / 128.0) - 1.0;
// A one-pole low-pass filter: three quarters of the last output and
// a quarter of the new noise, which turns the hiss of raw entropy
// into a rumble and leaves enough of the hiss to crackle.
self.filter_state = self.filter_coeff * self.filter_state + (1.0 - self.filter_coeff) * raw;
// The second byte drives the amplitude, and only every 441st sample
// is consulted: a hundred times a second at this sample rate. The
// walk is glacial — each consultation moves the state half a
// percent of the way toward the new noise — and the amplitude is
// mapped from it to the range three tenths to one, so that the hum
// swells and subsides over seconds without ever falling silent.
// Once every twenty-seven hours the sample counter wraps and the
// cadence stumbles by a fraction of a period, which no one has ever
// heard and no one will.
if self.sample_count.is_multiple_of(441) {
let amp_noise = (f32::from(entropy[1]) / 128.0) - 1.0;
self.amp_filter_state = 0.995 * self.amp_filter_state + 0.005 * amp_noise;
self.amplitude = 0.65 + self.amp_filter_state * 0.35;
}
Some(self.filter_state * self.amplitude)
}
}
/// The hum described to the audio library: one channel, the sample rate
/// above, no known length of span and no total duration, which is the
/// library's vocabulary for a sound with no end.
impl Source for QuantumNoise {
/// The length of the current span of uniform channel count and sample
/// rate, which is unknown because the span is the whole of the stream
/// and the stream does not end.
fn current_span_len(&self) -> Option<usize> {
None
}
/// One channel. The hum is mono; there is one entropy pool, and it has
/// no left and right.
fn channels(&self) -> ChannelCount {
// SAFETY: the literal 1 is not zero, and the unchecked constructor
// asks nothing else of it.
unsafe { NonZero::new_unchecked(1) }
}
/// The sample rate, `SAMPLE_RATE`, in the non-zero wrapper the library
/// requires.
fn sample_rate(&self) -> SampleRate {
// SAFETY: `SAMPLE_RATE` is 44,100, which is not zero, and the
// unchecked constructor asks nothing else of it.
unsafe { NonZero::new_unchecked(SAMPLE_RATE) }
}
/// The total duration of the hum, which has none: `None`, the
/// library's word for a sound that outlasts the question.
fn total_duration(&self) -> Option<Duration> {
None // there is no end to a hum that never began to count
}
}

View file

@ -0,0 +1,758 @@
//! # Cosmic Event Passages
//!
//! Herein dwell the textual accompaniments to the cosmic milestones displayed
//! upon the Observatory's timeline: sixty of them, one per caret, each a
//! meditation upon the significance of its event, rendered in prose
//! befitting the gravity (or, in the case of the early universe, the absence
//! thereof) of the moment in question. A click on a caret opens the passage
//! in an overlay, word-wrapped to the window; a click anywhere, or Escape,
//! closes it again, and the universe resumes where it was.
//!
//! These passages are technically accurate. They are also linguistically
//! unhinged. This is by design. Where the science is settled the passage
//! says so; where it is argued, the passage says that instead, because a
//! timeline that presents a conjecture as a date is lying with a straight
//! face, and the workspace README, section 0, forbids exactly that. Where
//! the calendar itself takes a position — on the last observation, on the
//! sanctity of the Julian year — the passage says whose position it is. The
//! titles and the texts are content, fact-checked, and not to be improved by
//! anyone who has come to improve the comments.
/// The name by which a marker on the timeline and the passage behind it
/// know each other: one variant per event, sixty of them, in the order the
/// universe produced them. The timeline's table carries one of these per
/// marker and `get_passage` answers to it, so the two cannot drift apart
/// without the compiler noticing — a match with a variant missing does not
/// build, which is the calendar's preferred way of being told. It derives
/// everything a key should: copied by value, compared by value, hashed by
/// value, and printed by `Debug` as its own name, which is the only name it
/// has.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EventId {
// The Planck era, one Planck time long: the unit the calendar counts in.
PlanckEpochEnds,
// The Grand Unification era: three forces as one, gravity already apart.
GrandUnificationEpoch,
// The electroweak era: inflation's end, and the Higgs field coming on.
InflationEnds,
ElectroweakEpoch,
// The quark era: the plasma, before confinement had anything to confine.
QuarkEpoch,
// The hadron era: the quarks bound, the antimatter gone, the neutrinos
// loose.
HadronEpoch,
NeutrinoDecoupling,
// Nucleosynthesis: the universe as a fusion reactor, for a quarter of an
// hour.
NucleosynthesisBegins,
NucleosynthesisEnds,
// The photon era: cooling past the Sun's core, equality, and the first
// light let go.
CoolerThanTheSunsCore,
MatterRadiationEquality,
Recombination,
// The dark ages: neutral hydrogen, and nothing shining.
DarkAgesBegin,
// Cosmic dawn: the first stars, and the first things worth calling
// galaxies.
FirstStarsIgnite,
FirstGalaxiesForm,
// The stelliferous era: the age of stars, of the Sun, and of everything
// that has so far lived on the third rock — the calendar's own era, for
// now.
ReionizationComplete,
CosmicNoon,
ExpansionAccelerates,
SolarSystemForms,
EarthForms,
MoonForms,
FirstLife,
GreatOxidation,
FirstEukaryotes,
SnowballEarth,
CambrianExplosion,
PermianExtinction,
DinosaurExtinction,
// Human history: from Jebel Irhoud to the year 2038, the last two percent
// of the species' time and the whole of its record, this calendar's
// epoch included.
HomoSapiens,
FirstFarmers,
FirstWriting,
JulianCalendar,
LeibnizBinary,
PlanckUnits,
FirstComputer,
FirstTransistor,
ArpanetWhisper,
UnixEpoch,
FirstEmail,
FirstLeapSecond,
FirstWebsite,
FirstSmartphone,
FirstBitcoinBlock,
UnixTimeOverflows,
// The far future: everything scheduled, from Voyager's fly-by to the
// last star.
VoyagerPassesGliese445,
PangaeaProxima,
OceansEvaporate,
AndromedaArrives,
SunRedGiant,
LocalGroupAlone,
LastStarsDie,
// The degenerate era: the remnants, cooling, and the galaxies coming
// apart.
DegenerateEra,
GalaxiesDisperse,
// The black hole era, if the protons decay; and the rocks, if they do
// not.
ProtonDecayComplete,
BlackHoleEraBegins,
RocksBecomeSpheres,
// The dark era: the holes and the dwarfs leak away, and the bits run out.
StellarBlackHolesEvaporate,
WhiteDwarfsErode,
SagittariusAEvaporates,
SupermassiveBlackHolesEvaporate,
}
/// What the overlay shows when a caret on the timeline is clicked: a title,
/// centred in amber at card scale, and a passage of three paragraphs, white,
/// word-wrapped to the window's width by the Observatory and separated by
/// the blank lines the text itself carries. Both are `&'static str`
/// compiled into the binary; the calendar does not fetch its history from
/// anywhere it could be edited without a rebuild.
pub struct EventPassage {
/// The event's title, as the overlay prints it above the passage. Not
/// the same string as the marker's name on the timeline, which is
/// shorter and shares a line with a dash; this one has the width of
/// the window and uses it.
pub title: &'static str,
/// The passage: a meditation in three paragraphs on the event, its
/// evidence, and its bearing on a calendar that measures from a crash.
/// Where a number is argued the passage says so; where it is settled it
/// says that; and where the calendar itself takes a position the
/// passage says whose position it is.
pub passage: &'static str,
}
/// Furnish the passage for an event: the oracle through which the
/// Observatory conjures textual enlightenment regarding the milestones
/// scattered across its timeline, consulted once per click on a caret and
/// answering, always, because the match below is exhaustive over `EventId`
/// and the compiler will not have it otherwise. Each passage has been
/// crafted with the care and verbosity befitting events of such magnitude,
/// and checked with the suspicion befitting a document that counts Planck
/// times; the titles and the texts are content, not commentary, and are the
/// one thing in this crate its comments are forbidden to improve.
///
/// The function returns by value and allocates nothing: an `EventPassage`
/// is two static references, thirty-two bytes on this platform, and the
/// strings they point at were laid down when the binary was.
#[allow(
clippy::too_many_lines,
reason = "sixty passages behind one match: the match is a book's index, and an index bound in five volumes serves worse than one"
)]
pub fn get_passage(id: EventId) -> EventPassage {
match id {
// ════════════════════════════════════════════════════════════════════
// THE PLANCK ERA: the first 10^-43 seconds, and the boundary of physics itself
// ════════════════════════════════════════════════════════════════════
EventId::PlanckEpochEnds => EventPassage {
title: "The Planck Epoch Concludes",
passage: r"For one Planck time—the smallest meaningful interval that physics deigns to acknowledge—the universe existed in a state of primordial unity. Gravity, electromagnetism, and the nuclear forces were not merely friends; they were indistinguishable, a single superforce presiding over a cosmos smaller than anything you have ever conceived of being small.
At 5.39 × 10⁻⁴⁴ seconds, this unity shattered. Gravity, that most antisocial of forces, separated from its siblings and began its long, slow work of pulling things together. The universe was now approximately 10⁻³⁵ meters across—still inconceivably small, but infinitely larger than it had been one Planck time prior.
This moment marks the boundary of physics itself. Before this, our equations dissolve into quantum foam. After this, we can pretend to understand things.",
},
// ════════════════════════════════════════════════════════════════════
// THE GRAND UNIFICATION ERA: 10^-43 to 10^-36 seconds, a unity never since repeated
// ════════════════════════════════════════════════════════════════════
EventId::GrandUnificationEpoch => EventPassage {
title: "The Grand Unification Epoch",
passage: r"With gravity now sulking in its own corner of reality, the remaining three forces—electromagnetic, strong nuclear, and weak nuclear—maintained their alliance for a cosmological instant. The temperature exceeded 10²⁷ Kelvin, a number so absurd that comparison fails; the core of the sun, at a mere 15 million Kelvin, is effectively absolute zero by comparison.
During this epoch, the distinction between quarks and leptons was meaningless. Particles transmuted freely between forms, a democracy of matter that would soon give way to the rigid class structures of conventional physics.
The Grand Unified Force, as theorists have named this ephemeral unity, remains hypothetical—we have never achieved the energies required to reunite these forces in a laboratory. The early universe performed this experiment exactly once, then moved on.",
},
// ════════════════════════════════════════════════════════════════════
// THE ELECTROWEAK ERA: 10^-36 to 10^-12 seconds, inflation and the acquisition of mass
// ════════════════════════════════════════════════════════════════════
EventId::InflationEnds => EventPassage {
title: "Cosmic Inflation Concludes",
passage: r"For a flickering moment—between 10⁻³⁶ and 10⁻³² seconds after the Beginning—the universe indulged in exponential expansion so violent that it would make any self-respecting economist weep with envy. Space itself stretched faster than light, a feat permitted because nothing was actually moving through space; space itself was simply becoming more of itself.
The observable universe, currently 93 billion light-years across, was during this period smaller than a proton. Quantum fluctuations, those tiny statistical hiccups in the fabric of reality, were stretched to cosmic proportions. These wrinkles would eventually become galaxy clusters, voids, and the large-scale structure we observe today.
Inflation solved several embarrassing problems in cosmology—the horizon problem, the flatness problem—by the simple expedient of making the universe unimaginably larger than it has any reasonable right to be.",
},
EventId::ElectroweakEpoch => EventPassage {
title: "The Electroweak Epoch",
passage: r"At 10⁻¹² seconds—a picosecond, in the parlance of those who traffic in such infinitesimals—the electromagnetic and weak nuclear forces finally acknowledged their differences and went their separate ways. This divorce, known as electroweak symmetry breaking, gave mass to the W and Z bosons while leaving photons forever massless and fleet.
The Higgs field, that all-pervading molasses of the quantum realm, switched on. Particles that had been traveling at the speed of light suddenly found themselves wading through cosmic treacle, acquiring the property we call mass. Without this moment, atoms could not form, chemistry would be impossible, and you would not exist to contemplate your own impossibility.
The universe was now one trillionth of a second old. The patch of it that would one day become everything you can see was roughly 10¹² metres across—about the size of Saturn's orbit—and still hotter than anything that would exist for the next 13.8 billion years.",
},
// ════════════════════════════════════════════════════════════════════
// THE QUARK ERA: 10^-12 to 10^-5 seconds, ten microseconds of unconfined broth
// ════════════════════════════════════════════════════════════════════
EventId::QuarkEpoch => EventPassage {
title: "The Quark Epoch",
passage: r"The universe had now cooled sufficiently—to a mere 10¹² Kelvin—that the fundamental forces operated as we know them today. Quarks and gluons swam in a plasma of such density and temperature that they could not bind together into hadrons. This was the quark-gluon plasma, a state of matter so exotic that we have only recently recreated it in particle accelerators.
For approximately ten microseconds, the cosmos was a seething broth of free quarks, antiquarks, and gluons, engaged in constant annihilation and pair-production. The slight asymmetry between matter and antimatter—one extra quark per billion annihilations—would prove consequential. Those leftover quarks would eventually become everything that exists.
Color confinement, the principle that quarks cannot exist in isolation, was temporarily suspended. It would not remain so for long.",
},
// ════════════════════════════════════════════════════════════════════
// THE HADRON ERA: 10^-5 seconds to one second, confinement, and one survivor in a billion
// ════════════════════════════════════════════════════════════════════
EventId::HadronEpoch => EventPassage {
title: "The Hadron Epoch",
passage: r"As the universe cooled below 10¹² Kelvin, quarks found themselves suddenly and irrevocably confined. They bound together in trios to form baryons—protons and neutrons, the building blocks of all ordinary matter—and in pairs to form mesons. The quark-gluon plasma had curdled into hadrons.
Protons and antiprotons, neutrons and antineutrons, annihilated each other in cataclysmic finality. When the fire cooled, only the slight excess of matter over antimatter remained—one survivor per billion annihilations. This is why there is something rather than nothing, a fact whose explanation remains one of physics' most profound mysteries.
The universe was now a ten-thousandth of a second old. In human terms, this is nothing. In terms of cosmic history, entire eras had already passed.",
},
EventId::NeutrinoDecoupling => EventPassage {
title: "Neutrino Decoupling",
passage: r"One second after the Beginning—an eternity by the standards of the preceding epochs—the universe had cooled to approximately 10¹⁰ Kelvin. At this temperature, neutrinos, those ghostly particles that barely interact with anything, finally decoupled from the cosmic plasma and began their eternal, nearly unimpeded journey through the universe.
These primordial neutrinos still exist, filling every cubic centimeter of space with approximately 336 of their number, traveling at nearly the speed of light with energies so low they are essentially undetectable. The Cosmic Neutrino Background, as it is called, predates the Cosmic Microwave Background by 380,000 years.
Neutrino decoupling marked the moment when the universe became transparent to neutrinos but remained opaque to photons. Light would have to wait considerably longer for its freedom.",
},
// ════════════════════════════════════════════════════════════════════
// NUCLEOSYNTHESIS: one second to twenty minutes, three parts hydrogen to one of helium
// ════════════════════════════════════════════════════════════════════
EventId::NucleosynthesisBegins => EventPassage {
title: "Big Bang Nucleosynthesis Begins",
passage: r"Ten seconds into existence, the universe had cooled enough for protons and neutrons to stick together in principle. In practice every deuterium nucleus they made was promptly blown apart again by the sea of photons around it, and it took three more minutes of cooling—the deuterium bottleneck—before the products could survive their birth. Then nuclear fusion, the same process that powers stars, commenced on a cosmic scale. For about a quarter of an hour, the entire universe functioned as a fusion reactor.
Hydrogen nuclei (single protons) fused into deuterium, which fused into helium-3, which fused into helium-4. Small amounts of lithium-7 and beryllium-7 formed. And then, due to the absence of stable nuclei with masses 5 and 8, the fusion chain stopped.
This bottleneck would have profound consequences. Nearly all elements heavier than lithium had to wait for stars to form, hundreds of millions of years later. The early universe, for all its fury, could only cook the lightest ingredients.",
},
EventId::NucleosynthesisEnds => EventPassage {
title: "Big Bang Nucleosynthesis Concludes",
passage: r"Twenty minutes after the Beginning, the universe had cooled below the threshold for nuclear fusion. The cosmic reactor shut down, leaving behind a precise mixture: roughly 75% hydrogen, 25% helium by mass, and trace amounts of deuterium, helium-3, and lithium.
This ratio, predicted by theory and confirmed by observation, stands as one of the great triumphs of modern cosmology. The abundance of light elements matches theoretical predictions to remarkable precision, providing strong evidence that we understand the first twenty minutes of cosmic history.
The universe would now spend the next 380,000 years as an opaque plasma, too hot for atoms to form, too thick with free electrons for light to travel far. It would be a long, quiet wait before the next significant event.",
},
// ════════════════════════════════════════════════════════════════════
// THE PHOTON ERA: twenty minutes to 380,000 years, the long opaque wait for atoms
// ════════════════════════════════════════════════════════════════════
EventId::CoolerThanTheSunsCore => EventPassage {
title: "Cooler Than the Sun's Core",
passage: r"A week or so after the Beginning, the temperature of the entire universe fell below fifteen million kelvin—the temperature at the centre of the Sun today. Everything that exists had, for its first eight days, been hotter than the inside of a star; from here on the cosmos as a whole would be cooler than the furnaces it would later build.
The cooling followed one rule the whole way down: in this era the temperature fell as the inverse square root of the age. Ten thousand times older, one hundred times cooler. By its first birthday—an anniversary nobody kept, there being no years yet, or calendars, or anybody—the universe was a fog of hydrogen and helium nuclei, electrons and light at some two million kelvin, opaque, featureless, and with nothing scheduled for the next forty-seven thousand years.
The Sun's core keeps its fifteen million kelvin by burning hydrogen. The universe had no such source. It was simply spending the heat it was born with, and has been spending it ever since.",
},
EventId::MatterRadiationEquality => EventPassage {
title: "Matter-Radiation Equality",
passage: r"For the first 47,000 years, radiation dominated the universe. Photons, neutrinos, and other relativistic particles contained more energy than all the matter combined. Under such conditions, the growth of structure was suppressed; density fluctuations could not amplify because radiation pressure smoothed them away.
At 47,000 years, the universe had expanded and cooled sufficiently that matter and radiation achieved equal energy density. This moment, unremarkable in the cosmic plasma, marked a fundamental shift in power. Henceforth, matter would dominate, gravity would strengthen its grip, and structure formation could begin in earnest.
The seeds of galaxies, planted by inflation billions of times smaller than a proton, began to grow.",
},
EventId::Recombination => EventPassage {
title: "Recombination: The Cosmic Dawn of Transparency",
passage: r"At 380,000 years, the universe had cooled to approximately 3,000 Kelvin—still hot enough to boil most metals, but cool enough for electrons to bind to nuclei. Atoms formed for the first time. Hydrogen, helium, and traces of lithium condensed out of the primordial plasma.
With electrons no longer free to scatter photons, light could finally travel unimpeded. The universe became transparent. The photons released at this moment have been traveling ever since, their wavelengths stretched by cosmic expansion from visible light to microwaves. We call them the Cosmic Microwave Background.
This is the oldest light in the universe, the first photograph of creation, carrying in its subtle temperature variations the fingerprints of quantum fluctuations from the inflationary epoch.",
},
// ════════════════════════════════════════════════════════════════════
// THE DARK AGES: 380,000 to some 200 million years, the afterglow and nothing else
// ════════════════════════════════════════════════════════════════════
EventId::DarkAgesBegin => EventPassage {
title: "The Cosmic Dark Ages",
passage: r"Following recombination, the universe entered a period of profound darkness. The Cosmic Microwave Background photons had been released, but no new light sources existed. The cosmos was filled with neutral hydrogen gas, slowly cooling, slowly coalescing under gravity's patient pull.
For a couple of hundred million years, nothing shone. The universe was a vast, dark, slowly-evolving cloud of gas, gathering into the earliest dark matter halos. No stars. No galaxies. No light except the fading afterglow of the Big Bang itself.
This era, the Dark Ages, is the longest stretch of cosmic history for which we have no direct observations. It ended only when the first stars ignited and lit the universe once more.",
},
// ════════════════════════════════════════════════════════════════════
// COSMIC DAWN: some 200 to 500 million years, Population III and the first galaxies
// ════════════════════════════════════════════════════════════════════
EventId::FirstStarsIgnite => EventPassage {
title: "The First Stars Ignite",
passage: r"Approximately 200 million years after the Beginning, in the hearts of dark matter halos where primordial gas had collected and compressed, the first stars ignited. These Population III stars, as astronomers classify them, were unlike any stars that exist today: massive, luminous, and composed entirely of hydrogen and helium.
Without heavy elements to cool their formation clouds, these first stars grew to enormous sizes—hundreds of solar masses, burning with blue-white fury, living fast and dying spectacularly. Their lifespans measured in millions of years, not billions. Their deaths seeded the universe with the first heavy elements: carbon, oxygen, iron, forged in their cores and scattered by their supernovae.
The Dark Ages ended. The universe, after 200 million years of silence, was alight once more.",
},
EventId::FirstGalaxiesForm => EventPassage {
title: "The First Galaxies Coalesce",
passage: r"As the first generation of stars lived and died, their remnants—black holes, neutron stars, and scattered heavy elements—collected in the gravitational wells of dark matter halos. Small proto-galaxies merged and grew. By 300 million years after the Beginning, the first recognizable galaxies had formed.
These early galaxies were small, irregular, and violent—nothing like the stately spirals and ellipticals of the present day. They churned with star formation, their gas enriched by the deaths of Population III stars, their cores often hosting the seeds of the supermassive black holes that would grow over billions of years.
The James Webb Space Telescope has caught them in the act: JADES-GS-z14-0, the most distant galaxy yet confirmed by its spectrum, shines from 290 million years after the Beginning, already holding hundreds of millions of suns—brighter, larger, and earlier than the models expected. The universe, it seems, was in a hurry to build.",
},
// ════════════════════════════════════════════════════════════════════
// THE STELLIFEROUS ERA: the age of stars, from reionization to the dinosaurs' last day
// ════════════════════════════════════════════════════════════════════
EventId::ReionizationComplete => EventPassage {
title: "Reionization: The Universe Becomes Transparent Once More",
passage: r"The first stars and galaxies did more than provide light; they transformed the universe itself. Ultraviolet radiation from early stellar populations ionized the neutral hydrogen that had filled the cosmos since recombination. Over hundreds of millions of years, the universe transitioned from neutral to ionized once more.
By approximately one billion years after the Beginning, reionization was complete. The intergalactic medium became transparent to ultraviolet light. Photons from distant sources could travel unimpeded across cosmic distances—a prerequisite for observational astronomy.
This second great phase transition, from neutral to ionized, marked the end of the cosmic Dark Ages and the beginning of the Stelliferous Era—the age of stars, the epoch we still inhabit today.",
},
EventId::CosmicNoon => EventPassage {
title: "Cosmic Noon",
passage: r"Three and a half billion years after the Beginning, at a redshift of about two, the universe was forming stars faster than it ever had or ever would again. Astronomers call it cosmic noon. The rate has fallen by roughly a factor of ten since; about a quarter of all the stars that exist today were already made before the peak, and the universe has been coasting on the momentum of that afternoon ever since.
The Milky Way was there for it, a smaller and messier galaxy than the one that hosts you, building its stars in bursts. The Sun was not; it would not form for nearly six billion years more, from gas already enriched by the generations that noon produced.
An observer who could see the whole sky at once would have watched galaxies glow with young blue stars from horizon to horizon. Nobody was there. The light from that noon arrives here now, ten billion years late, redshifted into the infrared, in the long exposures of telescopes that were pointed at nothing in particular.",
},
EventId::ExpansionAccelerates => EventPassage {
title: "The Expansion Begins to Accelerate",
passage: r"For its first seven or eight billion years the universe expanded the way a thrown stone rises: coasting, and slowing, as the gravity of everything in it pulled on everything else. Then, somewhere around six billion years ago, the slowing stopped and the expansion began to speed up. Matter had thinned out enough that something else—constant per unit of space and indifferent to dilution—took over the accounts. It is called dark energy because it has to be called something.
The transition is not sharp and its date is not settled; analyses put it between five and seven billion years ago, depending on the data and the assumptions. The sign change is not in doubt. Two teams measured it in 1998 with distant supernovae that were fainter than a decelerating universe allowed, and were given a Nobel prize for the inconvenience.
Nothing here noticed. The Sun did not yet exist; the cloud it would condense from was still being seeded by supernovae, and the most sophisticated life anywhere nearby, if there was any, was a cell without a nucleus.",
},
EventId::SolarSystemForms => EventPassage {
title: "The Solar System Coalesces",
passage: r"Nine billion years after the Beginning, in an unremarkable arm of an unremarkable spiral galaxy, a cloud of gas and dust began to collapse. The trigger may have been a nearby supernova, its shockwave compressing the cloud past the threshold of gravitational instability. Whatever the cause, the result was the birth of a star.
The Sun ignited 4.6 billion years ago, consuming 99.86% of the available mass. The remaining 0.14%—a cosmic rounding error—flattened into a protoplanetary disk. Within this disk, dust grains collided and stuck, growing into planetesimals, then planets. The Solar System took shape over tens of millions of years.
Four rocky planets formed in the inner system, where heat drove away light gases. Two gas giants and two ice giants formed in the outer system, where temperatures allowed hydrogen, helium and ices to accumulate. And on the third rock from the Sun, something remarkable was about to begin.",
},
EventId::EarthForms => EventPassage {
title: "Earth Forms from Cosmic Debris",
passage: r"The Earth accreted from the protoplanetary disk approximately 4.54 billion years ago, a molten ball of rock and metal bombarded by planetesimals. The energy of impacts kept the planet hot; iron sank to the core while silicates floated to form a magma ocean.
A world without oceans, without atmosphere, without any feature recognizable as Earthly. A hellscape of perpetual bombardment and volcanic fury. This was the Hadean Eon, named for Hades, and the name was apt.
Yet this violent world would, against all reasonable expectation, become a cradle for life. The very impacts that scarred its surface delivered water and organic molecules. The iron core that segregated early would generate a magnetic field to shield future life from solar radiation. Every catastrophe was also a gift.",
},
EventId::MoonForms => EventPassage {
title: "The Moon-Forming Impact",
passage: r"Approximately 4.5 billion years ago, when Earth was merely 50 million years old, a Mars-sized body named Theia collided with our nascent planet—at a glancing angle, in the standard telling; head-on and hotter, in some newer ones. The impact was cataclysmic beyond description: both worlds were largely vaporized, their material mixing in an orbiting cloud of molten rock.
From this debris disk, the Moon coalesced—a body proportionally larger relative to its planet than any other moon in the inner Solar System. The impact may have tilted Earth's axis, giving us seasons, and probably stripped away much of the early atmosphere. Whether it helped start the planet's magnetic field is argued.
The Moon stabilizes Earth's axial tilt, damping the chaotic wandering that models say the axis would otherwise undergo; whether complex life needed that favour is a conjecture, not a finding. Tides driven by lunar gravity may have played a role in life's emergence from the seas. Our satellite is not merely a companion. It may be an enabler of our existence, and it is certainly a witness to it.",
},
EventId::FirstLife => EventPassage {
title: "The Emergence of Life",
passage: r"Sometime between 4.2 and 3.8 billion years ago—the evidence remains frustratingly uncertain—life emerged on Earth. The transition from chemistry to biology, from organic molecules to self-replicating systems, remains one of science's most profound unsolved problems.
The earliest definitive evidence of life dates to approximately 3.5 billion years ago: stromatolites, layered structures built by microbial communities, preserved in Australian rock. But life may have existed long before, perhaps as early as the heavy bombardment allowed the oceans to remain liquid.
How non-life became life we do not know. Whether it happened once or many times, whether it was inevitable or improbable, whether it has happened elsewhere—these questions haunt the margins of our understanding. What we know is that it happened here, and everything that followed was consequence.",
},
EventId::GreatOxidation => EventPassage {
title: "The Great Oxidation Event",
passage: r"Around 2.4 billion years ago the atmosphere of the Earth acquired free oxygen, and kept it. Cyanobacteria had been splitting water for a long while by then, perhaps hundreds of millions of years, but everything they released had been swallowed—by iron dissolved in the oceans, by volcanic gases, by rock. Somewhere between 2.5 and 2.4 billion years ago the sinks filled, and the gas began to accumulate in the air.
The evidence is written in sulphur: before the event, sulphur isotopes in sediments carry a signature that forms only in an atmosphere without an ozone layer; after it, the signature vanishes, worldwide, and does not return. Rust follows—red beds, and the last of the banded iron formations, the iron of the oceans falling out of solution in layers now mined for steel.
For most of the life then living, oxygen was poison. What followed was, by biomass, one of the great extinctions, and, it is thought, one of the great glaciations: the greenhouse gas methane collapsed and the planet froze, perhaps to the equator. Everything that breathes descends from the survivors.",
},
EventId::FirstEukaryotes => EventPassage {
title: "The First Eukaryotes",
passage: r"The oldest fossils that are unmistakably eukaryotes—cells with a nucleus, the kind you are made of—are about 1.65 billion years old: ornamented, spiny microfossils from what is now China, too elaborate to be bacteria. Molecular clocks argue the lineage is older, perhaps by hundreds of millions of years, and the rocks have not yet been persuaded to agree.
The eukaryotic cell was not invented so much as assembled. At its heart is a merger: one cell took up residence inside another and stayed, becoming the mitochondrion, the power supply of every animal, plant and fungus since. The host is thought to have been an archaeon, the guest a bacterium; the arrangement has held for well over a billion years, which is longer than most.
Within a few tens of millions of years some of these cells were living in filaments, and within a hundred million in sheets the size of a hand and larger. Multicellularity, it turns out, is easy; life has arrived at it dozens of times. It is the nucleus that took two billion years.",
},
EventId::SnowballEarth => EventPassage {
title: "Snowball Earth",
passage: r"Seven hundred and seventeen million years ago the ice came down from the poles and did not stop. The Sturtian glaciation, the first of the Cryogenian's two, buried the planet for some fifty-seven million years—nearly the whole distance from the dinosaurs to you—and the glacial deposits it left are found on every continent, including ones that were then at the equator.
Whether the oceans froze over completely, or a band of open water survived at the equator, is argued; that the Earth was white from space, reflecting the sunlight it could no longer absorb, is not. What ended it was volcanoes: with no rain to weather rock and no weathering to draw down carbon dioxide, the gas accumulated over the ice for tens of millions of years until the greenhouse it built melted everything at once. The cap carbonates deposited in that thaw sit on top of the glacial debris worldwide, like a signature.
The animals appear in the rocks a little after the second glaciation ended. It is hard not to draw a line between the two, and hard to prove one.",
},
EventId::CambrianExplosion => EventPassage {
title: "The Cambrian Explosion",
passage: r"For three billion years, life was, with rare and modest exceptions, microscopic and, to human eyes, boring; the Ediacaran experiments in soft-bodied multicellular life came late and left few descendants. Then, approximately 539 million years ago, something changed. In a geological instant—perhaps 20 million years—nearly all major animal phyla appeared in the fossil record. Bodies. Eyes. Shells. Predators and prey. Complexity exploded.
The Cambrian Explosion, as this event is known, transformed Earth's biosphere from a thin veneer of microbial films to a churning ecosystem of multicellular creatures. Trilobites armored themselves against predators. Anomalocaris became the first apex predator we know of. Hallucigenia was reconstructed upside down and back to front before anyone worked out which end was the head.
What triggered this explosion remains debated: rising oxygen levels, the evolution of vision, an arms race between predators and prey, or all of the above. What is certain is that the world was forever changed.",
},
EventId::PermianExtinction => EventPassage {
title: "The Great Dying",
passage: r"Two hundred and fifty-two million years ago the Siberian Traps—a volcanic province that would cover most of Western Europe—erupted through coal and carbonate, and the atmosphere filled with carbon dioxide and worse. The oceans acidified, warmed, and lost their oxygen. In about sixty thousand years—a geological instant, dated to that precision by uranium in volcanic ash beds at Meishan, China—the great majority of marine species, estimates run from eighty to ninety-six percent, and most life on land were gone.
It is the worst extinction in the record of the planet, worse than the one that took the dinosaurs, and it took so long to recover from that the Triassic began with a world of few species, most of them small. The lystrosaurs, pig-sized and unglamorous, inherited the continents for a while, and were at one point perhaps the majority of all land vertebrates.
The dinosaurs came out of the recovery. So, some distance behind them, did you.",
},
EventId::DinosaurExtinction => EventPassage {
title: "The Cretaceous-Paleogene Extinction",
passage: r"Sixty-six million years ago, an asteroid approximately 10 kilometers in diameter struck the Yucatan Peninsula at a velocity of 20 kilometers per second. The impact released energy equivalent to 100 million megatons of TNT—billions of times more than the bombs that destroyed Hiroshima and Nagasaki.
The immediate effects were apocalyptic: a fireball that incinerated everything within a thousand kilometers, earthquakes of magnitude 10 or greater, tsunamis that scoured coastlines worldwide. The long-term effects were worse: dust and soot blocked sunlight for years, collapsing food chains, acidifying oceans, extinguishing three-quarters of all species.
The non-avian dinosaurs, lords of the Earth for 165 million years, perished entirely. And in the ecological vacuum left behind, small, furry, insignificant creatures called mammals began their ascent.",
},
// ════════════════════════════════════════════════════════════════════
// HUMAN HISTORY: from Jebel Irhoud to the year 2038, the calendar's own epoch among them
// ════════════════════════════════════════════════════════════════════
EventId::HomoSapiens => EventPassage {
title: "Homo sapiens",
passage: r"The oldest fossils that are placed in your own species come from Jebel Irhoud in Morocco and are about three hundred thousand years old: faces that would pass in a crowd, above braincases that would not, quite. The species did not arise on a date or in a place; it assembled itself across Africa over a long time from populations that met, separated and met again. Three hundred thousand years is where the record currently draws the line, and the line has moved before.
Everything that follows on this timeline—writing, computing, the network, this calendar—fits into the last two percent of that span. For ninety-eight percent of the time there have been Homo sapiens, there has been nothing you would recognise as history: stone, fire, ochre, the sea crossed a few times, an ice age or two endured.
It is the only species known to have measured the age of the universe, or to have wanted to.",
},
EventId::FirstFarmers => EventPassage {
title: "The First Farmers",
passage: r"About eleven and a half thousand years ago, in the hills of the Fertile Crescent, people who had gathered wild wheat and barley for millennia began to plant it. Not everywhere at once, and not on purpose in the sense of a decision: the plants that were harvested and resown became, over centuries, plants that could no longer scatter their own seed, and the people became people who could no longer leave.
Within a few thousand years the same thing happened independently in China, in Mesoamerica, in the Andes, in New Guinea, with rice and maize and potatoes and taro. It is one of the strongest arguments that the thing was going to happen: the climate had settled, the ice had gone, and a species that had watched plants closely for a hundred thousand years was going to notice.
Farming made villages, villages made surplus, surplus made accountants, and accountants, some six thousand years later, made writing. Every calendar descends from the need to know when to plant. This one, with no months, no seasons and no years, is the first that does not.",
},
EventId::FirstWriting => EventPassage {
title: "The Invention of Writing",
passage: r"Approximately 5,400 years ago, in the cities of ancient Sumer, humans began pressing wedge-shaped reeds into clay tablets. The purpose was mundane: accounting, inventory, taxation. The consequence was revolutionary: the externalization of memory, the defeat of forgetting, the birth of history itself.
Writing transformed human civilization. Information could now persist beyond living memory, accumulate across generations, spread across distances. Law, literature, mathematics, science—all became possible when knowledge could be recorded and transmitted.
The Loic Calendar measures time in Planck intervals, but this moment—the invention of writing—marks the beginning of recorded human history. Everything before is prehistory, reconstructed from artifacts and inference. Everything after is, in principle, knowable.",
},
EventId::JulianCalendar => EventPassage {
title: "The Julian Calendar",
passage: r"On the first of January, 45 BC, Rome switched to a calendar of 365 days with a leap day every fourth year. To get there, the previous year had to be 445 days long; the Romans called it the last year of confusion, and it was. The astronomer who designed it, Sosigenes of Alexandria, took the year to be 365 and a quarter days, which is eleven minutes too long; by the sixteenth century the error had piled up to ten days and the calendar had to be cut open and stitched.
The Loic Calendar keeps one thing from Julius Caesar: the Julian year of 31,557,600 seconds, exactly 365.25 days, which astronomers still use as their unit of long duration because it is a definition and not a measurement. The calendar's age of the universe is stated in those years. It has no other use for years, or for months, or for days, and the leap day—that quadrennial confession that the Earth and the Sun do not care about integers—it declines entirely.
The priests in charge of the new calendar promptly misread the rule and added a leap day every three years. It took Augustus, and a dozen years without any leap days at all, to undo it. Time-keeping has been like that ever since.",
},
EventId::LeibnizBinary => EventPassage {
title: "Leibniz Explains Binary Arithmetic",
passage: r"In 1703 Gottfried Wilhelm Leibniz published, in the Mémoires of the French Royal Academy of Sciences, an explanation of arithmetic using only the characters 0 and 1. He had been playing with it for over twenty years. Addition was a matter of carrying, multiplication needed no tables, and every number was a string of the two simplest marks there are; he thought it a fine image of creation out of nothing, and said so. He also thought it had been discovered four thousand years earlier in China, having been sent a diagram of the sixty-four hexagrams of the I Ching by a Jesuit missionary, and said that too.
Nobody used it for more than two hundred years. Binary was a curiosity of philosophers until relays and then vacuum tubes turned out to have exactly two states worth trusting, at which point it became the only arithmetic there is.
Every quantity in this calendar—every Planck count, every mask, every one of the 512 bits of an instant—is written in the notation of that paper. The seven cosmic primes are even named after operations on it that nobody had yet given names.",
},
EventId::PlanckUnits => EventPassage {
title: "Planck Proposes Natural Units",
passage: r"In May 1899 Max Planck told the Prussian Academy of Sciences that three constants of nature—the speed of light, the gravitational constant, and a new one of his own, needed to make the theory of heat radiation come out right—could be combined into a unit of length, a unit of mass and a unit of time that would, in his words, retain their meaning for all times and for all civilisations, including extraterrestrial and non-human ones. He gave their values. The unit of time came out at about 10⁻⁴³ seconds. He did not yet know what his new constant meant; the quantum was a year away.
He was right about the units and did not live to see anyone use them. It took half a century for physicists to realise that the Planck length and the Planck time are where gravity and quantum mechanics must both be taken seriously at once, and that no theory yet manages it.
This calendar counts Planck times because Planck said, in 1899, that they would mean the same thing to anyone. It is the one claim in the whole edifice that has an author, a date, and a room.",
},
EventId::FirstComputer => EventPassage {
title: "The Birth of Electronic Computing",
passage: r"The exact moment when electronic computing began is debatable—Colossus, ENIAC, the Z3 all have claims—but by the mid-1940s, machines existed that could perform calculations faster than any human mind. ENIAC ran its first problem, for the hydrogen bomb, in December 1945, and was unveiled the following February. It filled a room, consumed kilowatts, and performed what a modern smartphone accomplishes in microseconds.
These early computers were tools for specific problems: codebreaking, ballistics, nuclear physics. Their creators did not fully envision what they were building: the foundation of a new kind of civilization, one where information processing would eventually exceed in economic importance the manipulation of physical matter.
The Loic Calendar exists because of these machines. It requires 512-bit integers, calculations at Planck precision, computations that no human could perform by hand. The calendar is, in a sense, a monument to the computers that make its absurdity possible.",
},
EventId::FirstTransistor => EventPassage {
title: "The Invention of the Transistor",
passage: r"On December 16, 1947, at Bell Laboratories in New Jersey, John Bardeen and Walter Brattain demonstrated the first practical transistor. This small device—capable of amplifying electrical signals without vacuum tubes—would prove more consequential than nuclear weapons, more transformative than the moon landing.
Vacuum tubes were large, hot, fragile, and power-hungry. Transistors were small, cool, durable, and efficient. More importantly, transistors could be miniaturized, printed in silicon, manufactured by the billion. Moore's Law—the exponential increase in computing power—was made possible by this humble semiconductor device.
The computer on which the Loic Observatory runs contains billions of transistors, each smaller than a virus. Without Bardeen and Brattain's invention, without the exponential scaling it enabled, precise temporal measurement at the Planck scale would remain a mathematical abstraction.",
},
EventId::ArpanetWhisper => EventPassage {
title: "The ARPANET Whisper: Loic Epoch Zero",
passage: r#"At 22:30 Pacific time on October 29, 1969—06:30 UTC on the 30th, this calendar's zero—a student at UCLA began typing the word "LOGIN" to a computer at Stanford Research Institute. The "l" arrived. The "o" arrived. On the "g", the far end crashed. "LO" became the first message transmitted across the ARPANET, the ancestor of the modern Internet.
This moment—the Whisper—is the epoch of the Loic Calendar. All Loic timestamps are measured from this instant, when machines first spoke to each other across the void. The choice is deliberate: not the birth of a king, not the founding of a city, but the birth of networked computation.
From this origin point, time flows backward to the Big Bang (13.8 billion years prior) and forward to Annihilation, the calendar's terminal coordinate, which its 512 bits place some 10¹⁰³ years hence. All of cosmic history, measured from the moment humanity taught machines to whisper across distance."#,
},
EventId::UnixEpoch => EventPassage {
title: "The Unix Epoch",
passage: r"Sixty-two days, seventeen hours, twenty-nine minutes and nineteen seconds after the Whisper, the other epoch begins: midnight, the first of January 1970, Coordinated Universal Time, the zero from which nearly every computer alive counts its seconds. It was not chosen for anything that happened. Unix's early designers moved the zero around several times as their counters overflowed, and settled on the start of 1970 because it was a round date close at hand.
This calendar's zero is defined by its distance from that one: 5,419,722 seconds on the atomic clock scale, a number chosen, out of the sixty seconds the historical record allows, because it factors into 2 × 3 × 7 × 11 × 11,731 and no other candidate did. The two epochs are tied by a squarefree integer and disagree about everything else, including whether a second is always a second.
Most of the world is on Unix time without knowing it. Nobody is on Loic time without knowing it.",
},
EventId::FirstEmail => EventPassage {
title: "The First Email",
passage: r#"In late 1971, Ray Tomlinson sent the first email between two computers on the ARPANET. The content of the message has been lost to history—Tomlinson himself couldn't remember it, suggesting it was something like "QWERTYUIOP"—but its significance transcends its content.
The @ symbol, chosen by Tomlinson to separate user from machine, became the defining glyph of the digital age. Email would become the backbone of digital communication, the address of identity, the replacement for postal mail in billions of daily transactions.
Two years after the Whisper, humans had already invented a new form of correspondence. The network was no longer merely a connection; it was becoming a medium for human expression."#,
},
EventId::FirstLeapSecond => EventPassage {
title: "The First Leap Second",
passage: r"At the end of June 1972, for the first time, a minute was given sixty-one seconds. Coordinated Universal Time had been redefined on the first of January that year to tick in atomic seconds, exactly ten of them behind International Atomic Time, and to be held within nine-tenths of a second of the Earth's rotation by inserting a leap second whenever the planet fell behind. The planet, which is slowing down, falls behind. The first insertion was 23:59:60 on 30 June 1972, and there have been twenty-six more, the last at the end of 2016.
The difference is now thirty-seven seconds. This calendar reads the atomic scale and regards the civil one with the contempt documented in the workspace README, section 1.2, while owing its own epoch to exactly those thirty-seven seconds; the irony is disclosed there too. The Observatory will not open on a machine whose kernel has not been told the number.
In 2022 the world's metrologists voted to stop inserting leap seconds by 2035. The Earth, which has lately been speeding up, may yet require the first negative one before then. Nothing in this calendar would notice.",
},
EventId::FirstWebsite => EventPassage {
title: "The First Website",
passage: r"On August 6, 1991, Tim Berners-Lee posted a summary of the World Wide Web project to a Usenet newsgroup and opened the first website—running at CERN since December, describing the project itself, a recursive documentation of its own existence—to the world. The address was info.cern.ch; it still exists today.
The Web was not the Internet—the network was already two decades old—but it was the interface that made the Internet accessible to ordinary people. Hypertext, links, browsers: these concepts, obvious in retrospect, transformed the network from a tool for specialists into a medium for humanity.
Twenty-two years after the Whisper, the network had evolved from a military experiment to a publishing platform for the world. The rate of change was accelerating.",
},
EventId::FirstSmartphone => EventPassage {
title: "The Smartphone Revolution",
passage: r"On June 29, 2007, Apple released the iPhone. It was not the first smartphone—that distinction belongs to various devices from the 1990s and early 2000s—but it was the device that defined what a smartphone would become: a pocket-sized window to the totality of human knowledge and communication.
Within a decade, smartphones became ubiquitous. More than half of humanity now carries one. The device that once required a room of vacuum tubes, then a desktop of silicon, now fits in every pocket, runs on battery power, and connects to a network spanning the globe.
The Loic Observatory could run on such a device. Planck-precision timestamps in your pocket. The absurdity is complete.",
},
EventId::FirstBitcoinBlock => EventPassage {
title: "The Genesis Block",
passage: r#"On January 3, 2009, at 18:15:05 UTC, the Bitcoin genesis block was mined by the pseudonymous Satoshi Nakamoto. Embedded in its coinbase parameter was a message: "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks."
Bitcoin itself is not the point; the point is the proof that trustless, decentralized consensus is possible. That strangers across the world can agree on the state of a shared ledger without any central authority. That cryptographic protocols can replace institutional trust.
The Loic Calendar does not use blockchain, but it shares a philosophy: precision through mathematics, not authority. The genesis block was a declaration that some things need not be decreed; they can simply be computed."#,
},
EventId::UnixTimeOverflows => EventPassage {
title: "Thirty-Two Bits Run Out",
passage: r"At 03:14:08 UTC on 19 January 2038, the number of seconds since the Unix epoch reaches 2,147,483,648, which is one more than a signed 32-bit integer can hold. Systems that still keep time in one will roll over to the 13th of December 1901 and, in their confusion, may do anything at all. Most have been fixed. The rest are inside things that were not expected to last, which is exactly the kind of thing that lasts.
This calendar keeps its instants in 512 bits, and the count of Planck times since the Whisper will not exhaust them for about 10¹⁰³ years, at which point the universe is expected to have larger problems. The overflow of 2038 is what happens when time is stored in a quantity chosen for convenience. It is listed here as a cautionary tale, and as the only future event on this timeline that is scheduled to the second.
Its predecessor was the year 2000, which was survived by preparation and then remembered as a hoax. 2038 will be survived the same way, by people who fixed it in advance and were thanked by nobody.",
},
// ════════════════════════════════════════════════════════════════════
// THE FAR FUTURE: from Voyager's fly-by to the death of the last red dwarf
// ════════════════════════════════════════════════════════════════════
EventId::VoyagerPassesGliese445 => EventPassage {
title: "Voyager 1 Passes Gliese 445",
passage: r"About forty thousand years from now, Voyager 1—launched in 1977, the farthest thing humans have thrown—will pass within 1.6 light-years of Gliese 445, a red dwarf in Camelopardalis that is currently seventeen light-years away and closing. The star will do most of the travelling; by then it will be among the Sun's nearest neighbours. Voyager will not stop. Its speed, and the feeble gravity of a small star, will carry it straight through and on.
It will not be transmitting. Its plutonium will have gone cold by the 2030s, and it will be an inert object of 722 kilograms carrying a gold-plated copper record of greetings in fifty-five languages, whale song, and a diagram of where it came from, drawn relative to fourteen pulsars whose periods will have drifted by then.
Forty thousand years is, on this timeline, seven times the length of recorded history, and less than a rounding error in the age of anything else listed here.",
},
EventId::PangaeaProxima => EventPassage {
title: "Pangaea Proxima",
passage: r"In two hundred and fifty million years the continents, which move at about the speed your fingernails grow, will have reassembled into a single mass. The models disagree on the shape: the Atlantic closes and the Americas return to Africa in one, the Pacific closes and Asia takes the Americas in another, and the naming—Pangaea Proxima, Novopangaea, Aurica, Amasia—is a matter of which reconstruction you back. That there will be a supercontinent is not much in doubt; there have been several, on a cycle of some four or five hundred million years, and the last one broke up only two hundred million years ago.
One 2023 simulation followed the climate through: a hotter Sun, volcanic carbon dioxide from all that reassembly, and a continental interior far from any ocean, with the result that most of the land would be too hot for mammals. Mammals have been around for two hundred million years or so. Whatever is alive then may be reading this timeline from a different branch.
The marker sits at 250 million years because that is the round number the models share, not because anyone knows.",
},
EventId::OceansEvaporate => EventPassage {
title: "The Oceans Leave",
passage: r"The Sun brightens by about ten percent every billion years, and has done since it lit. In a billion years or so—the models disagree by a factor of two—the extra light will drive Earth's climate past a threshold called the moist greenhouse: the stratosphere fills with water vapour, ultraviolet splits it, the hydrogen escapes to space, and the oceans, molecule by molecule, leave the planet through the top of the sky. Long before the last of them go, the surface is uninhabitable for anything complex.
Some accounts give the biosphere less time still: the carbon dioxide that plants need is drawn down faster as the rocks weather in the heat, and in those models photosynthesis fails first, in six hundred million years or so. Either way, Earth has spent roughly four-fifths of its habitable lifetime.
It is a strange thing to know about one's own planet, and stranger that the number is not larger. The Earth will still exist. It will look, from a distance, like Venus, and for the same reasons.",
},
EventId::AndromedaArrives => EventPassage {
title: "Andromeda Arrives",
passage: r"The Andromeda galaxy is 2.5 million light-years away and has been known for a century to be approaching, at about 110 kilometres per second. For decades the story was settled: the two largest galaxies of the Local Group would collide in about four and a half billion years, pass through each other, fall back, and merge into one elliptical galaxy that was named, in advance, Milkomeda. The Sun would most likely be flung into a wider orbit and survive; the night sky, for anyone left to see it, would be spectacular.
In 2025 a study that followed the whole Local Group—Andromeda, the Milky Way, the Triangulum galaxy and the Large Magellanic Cloud, with the uncertainties in all their motions and masses run through a hundred thousand simulations—found the merger to be a coin toss: about even odds that it does not happen within the next ten billion years. The Magellanic Cloud's orbit pulls the Milky Way sideways, and Andromeda's own sideways motion is still too poorly measured to settle it.
The marker is left at four and a half billion years, which is where the collision is if it comes. It is the only entry on this timeline with a fifty percent chance of not being an event.",
},
EventId::SunRedGiant => EventPassage {
title: "The Sun Becomes a Red Giant",
passage: r"In about five billion years, the Sun will exhaust the hydrogen in its core and leave the main sequence. Fusion will migrate to a shell surrounding the now-helium core, and over the following two and a half billion years the outer layers will swell. At the tip of the red giant branch, 7.6 billion years from now, the Sun will be 256 times its present radius and some 2,700 times its present luminosity, having shed a third of its mass into space along the way.
Mercury will be engulfed. Venus will be engulfed. Earth's orbit will have widened as the Sun lightens, but not enough: in the models that follow the mass loss in detail, the photosphere reaches it just before the tip. Its surface will have been sterile for six billion years by then; the oceans go long before the Sun does.
This is not a disaster; it is simply stellar evolution. Stars live, stars die. The Sun will eventually shed its outer layers as a planetary nebula, leaving behind a white dwarf that will cool for trillions of years.",
},
EventId::LocalGroupAlone => EventPassage {
title: "The Local Group Alone",
passage: r"Within about a hundred billion years the accelerating expansion carries every galaxy not already bound to ours beyond the horizon: not merely out of sight but out of causal reach, their light stretched and dimmed below anything that could be detected, and then not arriving at all. What remains within reach is the Local Group, by then merged into a single old galaxy, in a sky that is otherwise empty.
Astronomers of that time—should there be any—will be unable to discover that the universe is expanding. There will be no distant galaxies to measure the expansion with; the cosmic microwave background will have been redshifted to wavelengths longer than the galaxy is wide, and absorbed by its gas; the light elements, the last fingerprint of the first twenty minutes, will have been reprocessed by stars. Every pillar of the Big Bang will have quietly left the building. Their best theory, from their best evidence, would be a single island of stars in a static void—the universe as it was believed to be in 1900, arrived at correctly and wrongly at once.
The information is not destroyed. It is only that nobody can get to it. This calendar will still say what time it is.",
},
EventId::LastStarsDie => EventPassage {
title: "The Last Stars Die",
passage: r"In approximately 100 trillion years, the last red dwarf will exhaust its hydrogen and fade to darkness. These smallest of stars, burning with miserly efficiency, are the longest-lived. When they are gone, no new stars will form; the universe will have consumed the gas required for stellar nucleosynthesis.
The Stelliferous Era—the age of stars, the age in which we live—will be over. It will have lasted approximately 10¹⁴ years, a mere flicker in the full span of cosmic time that the Loic Calendar attempts to encompass.
What follows is darkness: the slow decay of stellar remnants, the evaporation of black holes, the eventual heat death when thermodynamic equilibrium is achieved and change becomes impossible.",
},
// ════════════════════════════════════════════════════════════════════
// THE DEGENERATE ERA: white dwarfs cooling, planets stripped, galaxies unbound
// ════════════════════════════════════════════════════════════════════
EventId::DegenerateEra => EventPassage {
title: "The Degenerate Era",
passage: r"After the last stars die, the universe enters the Degenerate Era. White dwarfs cool toward absolute zero. Neutron stars spin down and fade. Brown dwarfs, never massive enough to sustain fusion, drift cold and dark through the void, and around 10¹⁵ years the last planets are stripped from their dead stars by the remnants that pass too close.
This era will last until around 10³⁷ to 10³⁹ years—the figure depends on how long protons last, which nobody knows—which is far longer than the Stelliferous Era, yet still a brief prelude to what follows. During this time, the dominant sources of energy will be rare collisions between stellar remnants and, if protons decay, the slow decay of nuclear matter itself.
The Degenerate Era is named for the quantum phenomenon of electron degeneracy pressure, which supports white dwarfs against gravitational collapse. It is an era of endings slowly arriving, of entropy patiently accumulating.",
},
EventId::GalaxiesDisperse => EventPassage {
title: "Galaxies Disperse",
passage: r"Approximately 10¹⁹ to 10²⁰ years from now, gravitational dynamics will unbind galaxies. Stars, ejected by close encounters over quadrillions of years, will escape into intergalactic space. Those that remain will spiral inward, feeding the central black hole.
The familiar structures of the universe—spiral arms, galactic disks, star clusters—will dissolve. What remains will be lonely objects adrift in an expanding void: white dwarfs, neutron stars, brown dwarfs, black holes, and the occasional planet that somehow survived the death of its star.
Long before this, dark energy will have pushed every other galaxy group beyond the horizon, so each of these dissolutions happens alone, in an observable universe containing nothing else.",
},
// ════════════════════════════════════════════════════════════════════
// THE BLACK HOLE ERA: proton decay, if any; the holes, if so; the spheres, if not
// ════════════════════════════════════════════════════════════════════
EventId::ProtonDecayComplete => EventPassage {
title: "Proton Decay, If Any, Completes",
passage: r"Nobody has ever seen a proton decay. Super-Kamiokande—fifty thousand tonnes of ultrapure water under a mountain in Japan, watched by eleven thousand photomultipliers since 1996—has waited through 450 kilotonne-years of exposure for one to turn into a positron and a pion, and has seen none. The proton's lifetime in that mode, if it decays at all, exceeds 2.4 × 10³⁴ years: some 10²⁴ times the present age of the universe.
Grand Unified Theories say it must decay, eventually. The simplest of them predicted lifetimes that Super-Kamiokande has already ruled out; their successors predict 10³⁴ to 10³⁶ years, just past the edge of what has been searched. If they are right, then by 10⁴⁰ years essentially every proton and neutron in the universe has gone—the last atoms, the last white dwarfs, the last rocks, dissolved into positrons, pions and light—and what follows is the Black Hole Era. If they are wrong, matter persists, and the far future takes the shape of the entries marked as alternatives further along this timeline.
This calendar takes no position. It marks the decade in which the question is settled either way, and notes that the twenty orders of magnitude before it, from 10²⁰ to 10⁴⁰ years, are the longest stretch on this timeline in which nothing whatsoever is scheduled to happen.",
},
EventId::BlackHoleEraBegins => EventPassage {
title: "The Black Hole Era",
passage: r"After approximately 10⁴⁰ years—if grand unified theories are correct and protons decay—matter as we know it will be gone. The only macroscopic objects remaining will be black holes, slowly evaporating via Hawking radiation.
The Black Hole Era will last until approximately 10¹⁰⁰ years—a duration so vast that all preceding eras combined are less than a rounding error by comparison. During this time, black holes will be the only significant concentrations of mass-energy in the universe.
Hawking radiation is thermal, random, structureless, or nearly so. Whether the glow secretly carries out what fell in—stars, planets, civilizations—in correlations that would take the age of the hole to read is the information paradox, argued for fifty years; the current answer, on paper, is that it does, and that nobody will ever be in a position to check. The Black Hole Era is an era of forgetting on a cosmic scale, whatever the paper says.",
},
EventId::RocksBecomeSpheres => EventPassage {
title: "Every Rock Becomes a Sphere",
passage: r"On a timescale of 10⁶⁵ years, Freeman Dyson calculated in 1979, solid matter is not solid. Atoms tunnel. Any lump of rock, given that long, flows like a liquid—its atoms wandering through it the way molecules wander in a drop of water—and settles under its own gravity into the shape water takes: a sphere. Every asteroid, every dead planet, every remnant that has escaped the fate of falling into something is, by 10⁶⁵ years, round.
This assumes the protons last, which is the assumption the previous entries on this timeline do not make. If they decay, there are no rocks by then, and this entry is a footnote to an alternative. If they do not, it is the beginning of the strangest chapter of all: on longer timescales still, Dyson found, the same tunnelling lets nuclei fuse and fission toward iron, until after 10¹⁵⁰⁰ years every sphere is a sphere of iron—a figure this calendar cannot represent, its 512 bits running out a little past 10¹⁰³ years, and which is therefore left in the text where it belongs.
The rounding of the rocks is the first thing in this calendar that does not end anything. It only tidies.",
},
// ════════════════════════════════════════════════════════════════════
// THE DARK ERA: the holes evaporate, the dwarfs erode, the last coordinate arrives
// ════════════════════════════════════════════════════════════════════
EventId::StellarBlackHolesEvaporate => EventPassage {
title: "Stellar Black Holes Evaporate",
passage: r"A black hole with the mass of the Sun will evaporate via Hawking radiation in approximately 10⁶⁷ years. Its temperature is sixty billionths of a kelvin—far colder than today's cosmic microwave background, so that for now it absorbs more than it emits. Only once the expansion has chilled the background below that, early in its long life, does the hole become a net radiator, and begin, imperceptibly, to lose weight.
As the black hole shrinks, its temperature rises. In its final moments, it will glow with increasing intensity, finally releasing its last energy in a burst of gamma rays. Then nothing will remain—not even a remnant. The black hole will be gone entirely.
Stellar-mass black holes, formed from the deaths of massive stars, will be the first of the black holes we know exist to evaporate. Supermassive black holes, containing millions to billions of solar masses, will persist longer—but not forever.",
},
EventId::WhiteDwarfsErode => EventPassage {
title: "The White Dwarfs Erode Away",
passage: r"White dwarfs were supposed to be the last things standing: the cooled cores of stars like the Sun, degenerate matter with nothing left to do, expected to persist until proton decay dissolved them or, if protons are stable, for some 10¹¹⁰⁰ years. In 2025 three physicists at Radboud University argued otherwise. The pair production that Hawking found at the horizon of a black hole, they showed, needs no horizon—only the curvature of spacetime—so any dense object slowly radiates its own mass away. For a white dwarf the timescale comes out at about 10⁷⁸ years; neutron stars go sooner.
The workspace README, section 4.7, takes the result seriously, and draws the conclusion: the rocks do not outlive the black holes. The black holes outlive the rocks, by twenty-two orders of magnitude.
The Sun will be one of them. Its white dwarf, cooled by then to a temperature the word does not cover, ends here—not with a bang, not with a whimper, but with a slow leak.",
},
EventId::SagittariusAEvaporates => EventPassage {
title: "Sagittarius A* Evaporates",
passage: r"The black hole at the centre of the Milky Way has 4.3 million times the mass of the Sun, a horizon that would fit comfortably inside the orbit of Mercury, and a temperature, by Hawking's formula, of about fourteen quadrillionths of a kelvin. It radiates, in principle, and loses mass, in principle, at a rate that would take some 10⁸⁷ years to finish—if it stopped growing now, which it will not; every star and gas cloud it swallows, and the black hole of Andromeda if that merger comes, adds to the mass and lengthens the wait.
Evaporation is not steady. For nearly the whole of that span the hole shrinks imperceptibly, its temperature rising as its mass falls, until in the last second it is a subatomic fireball releasing millions of megatons of gamma rays, and then it is gone. What comes out over the whole 10⁸⁷ years is exactly the mass that went in, as thermal radiation—including, in some form, every star of the galaxy it anchored.
It is the point at which this timeline's own galaxy stops existing in any form. The calendar, which is measured from a moment in that galaxy, does not stop.",
},
EventId::SupermassiveBlackHolesEvaporate => EventPassage {
title: "The Last Black Holes Evaporate",
passage: r"The largest supermassive black holes, containing 10¹¹ solar masses, will evaporate in approximately 10¹⁰⁰ years—a googol years, a number whose very name suggests whimsy but whose magnitude defies comprehension. When they are gone, the Black Hole Era ends.
The universe that remains will be a dilute sea of particles: photons, neutrinos, and perhaps exotic dark matter—all at temperatures indistinguishable from absolute zero. Nothing will remain to generate energy, to create structure, to enable change. This is the Dark Era, and by every account it has no end.
The Loic Calendar does not follow it there. Its 512 bits run out at Annihilation, a little past 10¹⁰³ years, and the workspace README, section 4.7, explains why the calendar treats the last observation, rather than the last process, as the end worth marking. Beyond that coordinate there is nothing to observe, and the calendar, which is an observer, declines to pretend otherwise.",
},
}
}

3194
crates/loic-gui/src/main.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,188 @@
//! The veil: the overlay renderer of the Loic Observatory.
//!
//! This module furnishes the means by which a translucent veil may be
//! interposed between the observer and the temporal display — a gossamer
//! shroud of configurable opacity, behind which the digits, bars, wheels
//! and coordinates of the moment may be put aside while a passage about
//! some other moment is read. The passage is Channel 1, content, a story;
//! the veil is what permits a story to be told over a display whose every
//! element insists on the present.
//!
//! The implementation is minimal to the point of asceticism: one
//! fullscreen quad, six vertices conjured from their indices by the
//! shader, rendered with alpha blending, whose sole purpose is to darken
//! whatever lies beneath. No textures, no vertex buffer, no instancing;
//! merely the primitive and one uniform colour. In the Observatory's frame
//! what lies beneath the veil is the cleared void alone, since the display
//! is not drawn while a passage is open, so the veil is in practice a second
//! coat of the same darkness and its translucency is a capacity held in
//! reserve. It is drawn all the same, because the frame is composed in
//! layers and the veil is one of them.
use wgpu::util::DeviceExt;
/// The layout of the overlay's uniform buffer: a single four-component
/// vector holding the veil's red, green, blue and alpha, each between zero
/// and one, in the `f32` the GPU insists upon and the calendar tolerates
/// for a colour, since a colour was never a Planck count. `Pod` and
/// `Zeroable` so that the bytes may be handed to the GPU as they lie.
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct OverlayUniforms {
/// The veil's colour and opacity, in that order: red, green, blue,
/// alpha.
color: [f32; 4],
}
/// The veil's renderer: one pipeline with alpha blending, one bind group,
/// one uniform buffer holding one colour. It draws a fullscreen
/// semi-transparent quad over whatever the render pass has already drawn,
/// leaving that visible in proportion to one minus the alpha and replacing
/// the rest with the veil's own colour — which is to say it dims, in the
/// exact arithmetic of blending, everything beneath it by the same amount.
pub struct OverlayRenderer {
/// The pipeline: the overlay shader's two stages, alpha blending against
/// the surface format, a triangle list, and nothing else.
pipeline: wgpu::RenderPipeline,
/// The bind group presenting the uniform buffer to the fragment stage.
bind_group: wgpu::BindGroup,
/// The uniform buffer holding the veil's colour, written once at
/// creation and again whenever the colour is changed.
uniform_buffer: wgpu::Buffer,
}
impl OverlayRenderer {
/// Conjures the veil's renderer into existence for a given device and
/// surface format: the uniform buffer with its default colour, the bind
/// group layout and bind group that present it to the fragment stage,
/// the pipeline layout, the shader, and the pipeline.
///
/// The default colour is the void's own — red 0.02, green 0.02, blue
/// 0.03, the same three components the surface is cleared to — at an
/// opacity of 85 percent: enough to render whatever lay beneath it
/// illegible without obliterating it, had anything been drawn beneath
/// it, which in the Observatory nothing is. The colour may be changed
/// afterwards through `set_color`, a capacity offered and, at present,
/// declined.
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
// The default veil: the void's colour at 85 percent, so that the veil
// and the ground it covers are one darkness.
let uniforms = OverlayUniforms {
color: [0.02, 0.02, 0.03, 0.85],
};
let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("overlay_uniforms"),
contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
// One binding, a uniform buffer, visible to the fragment stage
// alone: the vertex stage needs no colour to place a quad.
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("overlay_bind_group_layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("overlay_bind_group"),
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
}],
});
// The pipeline layout: that one bind group, and no immediate data.
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("overlay_pipeline_layout"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
// The shader, compiled into the binary as text and handed to the
// device as WGSL: a vertex stage that conjures the quad from vertex
// indices, and a fragment stage that returns the uniform colour.
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("overlay_shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/overlay.wgsl").into()),
});
// The pipeline: no vertex buffers, since the shader needs none; a
// triangle list; alpha blending against the surface format, which
// is the whole of what makes a veil a veil rather than a wall.
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("overlay_pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: wgpu::PipelineCompilationOptions::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
Self {
pipeline,
bind_group,
uniform_buffer,
}
}
/// Draws the veil: one draw call of six vertices, two triangles, one
/// instance, forming a quad that covers the whole of clip space from
/// corner to corner. The quad is blended over the pass in the current
/// uniform colour, which by default is the void's own at 85 percent
/// opacity.
///
/// The veil belongs between the layers it separates: after whatever is
/// to be dimmed and before whatever is to be read through it, which in
/// the Observatory is the passage's text. Drawn last, it would dim the
/// passage; drawn first, it would dim nothing but the void, which is
/// what it does regardless, but on principle.
pub fn render<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.bind_group, &[]);
render_pass.draw(0..6, 0..1);
}
/// Rewrites the veil's colour: four components between zero and one,
/// written to the uniform buffer through the queue and in effect from
/// the next draw. Offered so that the default darkness might be made
/// deeper or shallower should an observer's eyes require it; no caller
/// has yet required it, and the allowance beneath says so to the lint.
#[allow(dead_code)]
pub fn set_color(&self, queue: &wgpu::Queue, r: f32, g: f32, b: f32, a: f32) {
let uniforms = OverlayUniforms {
color: [r, g, b, a],
};
queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms]));
}
}

View file

@ -0,0 +1,620 @@
//! # The Digit Waterfall
//!
//! The renderer of the Observatory's principal exhibit: the cosmic time —
//! Planck times since Creation, sixty-one digits of it today and a hundred
//! and fifty-four at Annihilation — poured across the top of the window as
//! rows of glyphs, one instanced quad per digit, each quad a lookup into a
//! glyph atlas baked once at start-up from a five-by-seven bitmap font.
//! The last thirty-four digits are cyan and change with every observation,
//! since 10^34 Planck times fit in a nanosecond and the nanosecond's
//! interior is entropy; the nine before them are gray and change faster
//! than a person can read; the rest are white and hold still for a second
//! or more. Which is which is the shader's business and is stated in
//! `digit.wgsl`; this module's business is where the digits go and how big
//! they are.
//!
//! The atlas is never scaled. The quads that sample it are, by integer
//! factors and with nearest filtering, so that each texel is a crisp block
//! of pixels at every step of the font; and the font steps down — once, at
//! the hundred-and-twenty-first digit, around the year 1.7 × 10^69 — only
//! when the digits outgrow the reserve of height they have been granted,
//! so that nothing below the waterfall ever moves. The main thread makes
//! one observation per frame and hands its digits here. The observer
//! threads, which make orders of magnitude more, hand over nothing; theirs
//! are made to be discarded, and discarded they are.
use wgpu::util::DeviceExt;
/// The most digits the storage buffer holds, and therefore the most the
/// waterfall will ever draw: 256. The cosmic time is 61 digits today and
/// 154 at Annihilation, after which there is no more cosmic time to have
/// digits; 256 is the next power of two above that, a size a GPU finds
/// congenial and an allocation of one kilobyte, which even a calendar this
/// extravagant declines to call waste. A slice longer than this is
/// truncated to it by `update_digits`, a condition no valid instant can
/// produce and no invalid one is offered.
const MAX_DIGITS: usize = 256;
/// One cell of the atlas, at the font's true resolution: a 5×7 glyph with
/// one texel of air to its right and below, six texels wide and eight
/// tall. The atlas is never scaled; the quads that sample it are, by
/// integer factors, with nearest filtering, so that every texel becomes a
/// crisp block of pixels at any step. Six by eight, times the step, is also
/// the pitch of the digits on screen: the air is part of the cell, and a
/// row of digits is a row of cells with no further spacing added.
const CELL_WIDTH: u32 = 6;
const CELL_HEIGHT: u32 = 8;
/// The atlas: ten glyphs, 0 through 9, in one row of cells, sixty texels
/// wide and eight tall, a single-channel texture of four hundred and eighty
/// bytes that describes every digit the age of the universe will ever
/// need. The shader finds glyph `d` at `d` tenths of the atlas width, which
/// is why the order of the cells is the order of the digits and why there
/// is no eleventh.
const ATLAS_WIDTH: u32 = CELL_WIDTH * 10;
const ATLAS_HEIGHT: u32 = CELL_HEIGHT;
/// The waterfall's horizontal margin, in pixels, on both sides: forty, the
/// same forty the timeline bar keeps from the window's edges in `main.rs`,
/// so that the first digit and the bar's opening bracket share a column and
/// the eye, travelling down, finds nothing to correct. The margin is
/// subtracted twice from the window's width to get the width the rows may
/// fill, and the rows fill it with whole cells and leave the remainder.
const X_MARGIN: u32 = 40;
/// The waterfall's top edge, in pixels from the top of the window: sixty,
/// which places the first row just below the single-line header — the
/// count of observers, their observations per second and the renders per
/// second — that `main.rs` centres at thirty. The digits begin where the
/// accounting ends.
const WATERFALL_TOP: u32 = 60;
/// The waterfall's reserve: the height, in pixels, that every step of the
/// font must fit its rows into, so that nothing below it — the wheels, the
/// bar, the cards — ever moves, however many digits the cosmic time grows
/// to between now and Annihilation. One hundred and sixty pixels is four
/// rows of the largest step, whose cell is forty pixels tall; the layout
/// beneath is placed on the assumption that the waterfall ends here, and
/// the test `every_count_fits_the_reserve` sees that it does for every
/// digit count the buffer can hold.
const WATERFALL_HEIGHT: u32 = 160;
/// The steps of the font, largest first, as integer multiples of the cell's
/// width and height. (4, 5) is the 24×40 look the Observatory opens with;
/// the rest are what the digits shrink to when the universe outgrows the
/// reserve, each a whole number of pixels per texel so that no glyph is
/// ever resampled into a blur. At 800 pixels wide, thirty cells of the
/// first step fit a row and four rows fit the reserve, so the first step
/// holds 120 digits; forty of the second fit a row and five rows the
/// reserve, so the second holds 200. The calendar's last digit is the
/// 154th. The shrink therefore happens once, when the cosmic time reaches
/// 10^120 Planck times — around the year 1.7 × 10^69 — and then never
/// again; the third step, and the two below it, exist for widths narrower
/// than the window allows and for counts larger than the universe supplies.
const SCALE_STEPS: [(u32, u32); 5] = [(4, 5), (3, 4), (2, 3), (2, 2), (1, 1)];
/// Elect the step of the font: the largest whose rows of `digit_count`
/// digits fit the reserve at this width. The width between the margins is
/// divided by the step's cell width to get the digits per row, at least
/// one; the count is divided by that, rounding up, to get the rows; and
/// the rows times the step's cell height must not exceed the reserve. The
/// first step that passes is the answer, and the smallest step is the
/// answer if none passes — a fallback that no digit count the buffer can
/// hold reaches at any width the window is allowed, and that exists so
/// that the function has an answer for every question rather than a
/// question of its own. Integer arithmetic throughout: a step of the font
/// is a count of pixels per texel, and a count is not a thing to
/// approximate.
fn glyph_scale_for(digit_count: u32, screen_width: u32) -> (u32, u32) {
let content_width = screen_width.saturating_sub(2 * X_MARGIN).max(CELL_WIDTH);
SCALE_STEPS
.iter()
.copied()
.find(|&(kx, ky)| {
let per_row = (content_width / (CELL_WIDTH * kx)).max(1);
let rows = digit_count.div_ceil(per_row);
rows * CELL_HEIGHT * ky <= WATERFALL_HEIGHT
})
.unwrap_or(SCALE_STEPS[SCALE_STEPS.len() - 1])
}
/// The uniform block the digit shader reads, laid out in C order to match
/// the `Uniforms` struct in `digit.wgsl` field for field: two `vec2<f32>`
/// for the screen and the glyph, one for the atlas, then the digit count,
/// the vertical offset, the horizontal margin and the time — forty bytes,
/// rewritten whenever the digits, the window or the clock change. The
/// floats are the point of GPU submission, where the heresy is tolerated
/// because the hardware speaks nothing else; all but the last of them are
/// integers below 2^24, cast at the last moment and carried exactly, and
/// the last is a count of seconds that drives a shimmer and touches no
/// instant.
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct Uniforms {
/// The surface's width and height in pixels, by which the shader
/// divides to reach clip space, where the GPU insists on living.
screen_size: [f32; 2],
/// The width and height of one digit's quad in pixels: the cell times
/// the step of the font in force.
glyph_size: [f32; 2],
/// The atlas's width and height in texels, sixty by eight, so that the
/// shader can find a glyph's tenth of it.
atlas_size: [f32; 2],
/// How many digits to draw, and therefore how many instances; the
/// shader also counts back from this to colour the zones.
digit_count: u32,
/// The waterfall's top, in pixels from the top of the window:
/// `WATERFALL_TOP`, sixty, placing the first row just below the
/// single-line header of observers and rates that `main.rs` centres at
/// y=30.
y_offset: u32,
x_margin: u32, // the horizontal margin, in pixels: X_MARGIN, the bar's own forty
time: f32, // seconds since this renderer was born, for the cyan zone's shimmer
}
/// The digit renderer: the GPU state for the waterfall — a pipeline, the
/// bind group that ties atlas, sampler, uniforms and digit buffer together,
/// the two buffers themselves — and the little it remembers between frames:
/// the glyph size in force, the surface's size, how many digits it was last
/// handed, and when it was born, from which the shimmer takes its phase.
/// One of these exists, owned by the render state, and it outlives every
/// instant it has ever drawn.
pub struct DigitRenderer {
/// The render pipeline: `digit.wgsl`'s vertex and fragment stages, alpha
/// blending, a triangle list, no culling and no depth.
pipeline: wgpu::RenderPipeline,
/// The four bindings the shader reads: uniforms, atlas view, sampler,
/// digits, in that order and at those indices.
bind_group: wgpu::BindGroup,
/// The forty-byte uniform block, rewritten by `update_uniforms`.
uniform_buffer: wgpu::Buffer,
/// The storage buffer of digits, `MAX_DIGITS` of them as `u32`, of which
/// the first `digit_count` are drawn and the rest are ignored.
digit_buffer: wgpu::Buffer,
/// The width and height of one digit's quad in pixels, at the step of
/// the font in force; recomputed by `fit_glyphs` on every resize and
/// every new set of digits.
glyph_size: (f32, f32),
/// The surface's width and height in pixels, as last reported by
/// `resize`; the width decides how many cells a row holds.
screen_size: (u32, u32),
/// How many digits are being drawn, which is how many the cosmic time
/// has: sixty-one today, and never fewer again.
digit_count: u32,
/// The instant this renderer was constructed, from which the `time`
/// uniform is measured for the shimmer; a monotonic clock, not the
/// calendar's, because the shimmer is decoration and decoration may be
/// measured in seconds without heresy.
start_time: std::time::Instant,
}
impl DigitRenderer {
/// Assemble the renderer: bake the atlas and upload it as an `R8Unorm`
/// texture, make the sampler that reads it without interpolating, lay
/// out the uniform block and the digit buffer, bind the four of them,
/// compile the shader, and build the pipeline that draws six vertices
/// per instance with alpha blending onto a surface of the given
/// `format`. Until `resize` and `update_digits` have been called the
/// renderer believes the surface is 800 by 800 and the count is zero,
/// draws nothing, and is right to.
#[allow(
clippy::too_many_lines,
reason = "the GPU's initiation is one linear rite — atlas, texture, sampler, buffers, bind group, pipeline — each step needing the last; five functions would be five places to read one paragraph"
)]
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self {
// Bake the atlas on the CPU from the bitmap font below: sixty by eight texels, a byte each.
let atlas_data = generate_glyph_atlas();
// The atlas as a texture: one channel, eight bits, unsigned and
// normalised, so that a lit texel samples as 1.0 and an unlit one as
// 0.0, and the fragment shader can use the sample as alpha directly.
let atlas_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("glyph_atlas"),
size: wgpu::Extent3d {
width: ATLAS_WIDTH,
height: ATLAS_HEIGHT,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &atlas_texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&atlas_data,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(ATLAS_WIDTH),
rows_per_image: Some(ATLAS_HEIGHT),
},
wgpu::Extent3d {
width: ATLAS_WIDTH,
height: ATLAS_HEIGHT,
depth_or_array_layers: 1,
},
);
let atlas_view = atlas_texture.create_view(&wgpu::TextureViewDescriptor::default());
// Nearest filtering, both ways: the quads are integer multiples of
// the cell, so each texel lands on a whole block of pixels and
// nothing is blurred; clamped at the edges, because a lookup outside
// the atlas has no digit to find.
let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("glyph_sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
// The uniform block at its initial values: the largest step of the
// font, a surface of 800 by 800 that the first resize will correct,
// and no digits, which the first observation will correct.
let (kx, ky) = SCALE_STEPS[0];
let uniforms = Uniforms {
screen_size: [800.0, 800.0],
glyph_size: [(CELL_WIDTH * kx) as f32, (CELL_HEIGHT * ky) as f32],
atlas_size: [ATLAS_WIDTH as f32, ATLAS_HEIGHT as f32],
digit_count: 0, // no digits until the first observation is handed over
y_offset: WATERFALL_TOP,
x_margin: X_MARGIN,
time: 0.0,
};
let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("uniforms"),
contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
// The digit buffer, allocated at its largest once and never grown:
// MAX_DIGITS u32s, of which the first digit_count are read by the
// shader and the remainder wait for the universe to age into them.
let digits = vec![0u32; MAX_DIGITS];
let digit_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("digits"),
contents: bytemuck::cast_slice(&digits),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
// The layout of the four bindings: the uniform block for both
// stages, the atlas and its sampler for the fragment stage, and the
// digits, read-only, for the vertex stage, which is where a digit's
// value becomes a glyph's column in the atlas.
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("digit_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("digit_bind_group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&atlas_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: digit_buffer.as_entire_binding(),
},
],
});
// One bind group and no immediates: the pipeline's layout is the
// layout above and nothing more.
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("digit_pipeline_layout"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
// The shader, compiled here from source that was embedded in the
// binary at build time; the Observatory carries its own shaders and
// reads none from disk.
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("digit_shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/digit.wgsl").into()),
});
// The pipeline: six vertices per instance as a triangle list, no
// culling, alpha blending so that the air around a glyph shows the
// void through it, and no depth, the waterfall being flat.
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("digit_pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: wgpu::PipelineCompilationOptions::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
Self {
pipeline,
bind_group,
uniform_buffer,
digit_buffer,
glyph_size: ((CELL_WIDTH * kx) as f32, (CELL_HEIGHT * ky) as f32),
screen_size: (800, 800),
digit_count: 0,
start_time: std::time::Instant::now(),
}
}
/// Elect the step of the font for the current digit count and width,
/// and record the quad it implies: the cell times the step, in pixels,
/// as the two floats the shader wants. Called on every resize and every
/// observation; it is cheap, and it changes its answer once at start-up
/// and once around the year 1.7 × 10^69.
fn fit_glyphs(&mut self) {
let (kx, ky) = glyph_scale_for(self.digit_count, self.screen_size.0);
self.glyph_size = ((CELL_WIDTH * kx) as f32, (CELL_HEIGHT * ky) as f32);
}
/// Take note of the surface's new size, refit the font to the width,
/// and push the uniforms. The height is recorded and handed to the
/// shader, which needs it to reach clip space; the width is what decides
/// how many cells a row holds and therefore which step of the font the
/// reserve can afford. The Observatory's window is not resizable, so
/// this is called once, after construction, and then never; the
/// function does not know that and would not care.
pub fn resize(&mut self, queue: &wgpu::Queue, width: u32, height: u32) {
self.screen_size = (width, height);
self.fit_glyphs();
self.update_uniforms(queue);
}
/// Take the digits of a fresh observation — most significant first, as
/// many as the cosmic time has — write them to the storage buffer, and
/// refit the font to the count: the digits shrink by a step when the
/// count outgrows the reserve, and not before, and never grow back,
/// since the cosmic time does not. A slice longer than `MAX_DIGITS` is
/// cut to that length, a courtesy no valid instant will ever call on.
/// Called once per frame by the main thread with its one observation.
///
/// # Panics
///
/// Panics if the clamped count does not fit a `u32`, which it always
/// does, 256 being somewhat less than four billion; the `expect` is the
/// conversion's receipt, not a live possibility.
pub fn update_digits(&mut self, queue: &wgpu::Queue, digits: &[u32]) {
let count = digits.len().min(MAX_DIGITS);
self.digit_count = u32::try_from(count).expect("a count clamped to MAX_DIGITS fits a u32");
self.fit_glyphs();
// The digits go to the GPU as they came, one u32 each, and only the first count of them.
queue.write_buffer(
&self.digit_buffer,
0,
bytemuck::cast_slice(&digits[..count]),
);
// And the uniforms follow, carrying the new count and the glyph size it implies.
self.update_uniforms(queue);
}
/// Write the uniform block afresh: the surface, the glyph, the atlas,
/// the count, the two layout constants, and the seconds elapsed since
/// the renderer was born, which is the phase of the shimmer. Called
/// after every resize and every observation, so the time is refreshed
/// as often as the digits are, and the shimmer advances at the frame
/// rate, whatever that happens to be.
fn update_uniforms(&self, queue: &wgpu::Queue) {
let elapsed = self.start_time.elapsed().as_secs_f32();
let uniforms = Uniforms {
screen_size: [self.screen_size.0 as f32, self.screen_size.1 as f32],
glyph_size: [self.glyph_size.0, self.glyph_size.1],
atlas_size: [ATLAS_WIDTH as f32, ATLAS_HEIGHT as f32],
digit_count: self.digit_count,
y_offset: WATERFALL_TOP,
x_margin: X_MARGIN,
time: elapsed,
};
queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms]));
}
/// Draw the waterfall into the frame's render pass: one draw call, six
/// vertices per instance, one instance per digit, the pipeline and the
/// bind group set for the occasion. Draws nothing at all when the count
/// is zero — before the first observation has been handed over — rather
/// than asking the GPU to draw zero instances and finding out what it
/// thinks of that.
pub fn render<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
if self.digit_count == 0 {
return;
}
render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.bind_group, &[]);
render_pass.draw(0..6, 0..self.digit_count);
}
}
/// Bake the glyph atlas for the digits 0 through 9 at the font's true
/// resolution: one 6×8 cell per digit, the 5×7 glyph in its top-left
/// corner, one texel of air to the right and below, lit texels at 255 and
/// the rest at zero, in a single row sixty texels wide. The font is the
/// bitmap below and nothing fancier: ten glyphs of seven rows of five bits,
/// the most significant bit the leftmost column, legible at any integer
/// scale and at no other, which is why no other is ever used.
fn generate_glyph_atlas() -> Vec<u8> {
// The font: ten glyphs of seven rows, each row five bits, the most
// significant bit at the left. Read them by squinting.
const PATTERNS: [[u8; 7]; 10] = [
// 0
[
0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
],
// 1
[
0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
],
// 2
[
0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111,
],
// 3
[
0b01110, 0b10001, 0b00001, 0b00110, 0b00001, 0b10001, 0b01110,
],
// 4
[
0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
],
// 5
[
0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
],
// 6
[
0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
],
// 7
[
0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
],
// 8
[
0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
],
// 9
[
0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
],
];
let mut atlas = vec![0u8; (ATLAS_WIDTH * ATLAS_HEIGHT) as usize];
for (digit, pattern) in (0u32..).zip(PATTERNS.iter()) {
let cell_x = digit * CELL_WIDTH;
for (y, &bits) in (0u32..).zip(pattern.iter()) {
for col in 0..5u32 {
if (bits >> (4 - col)) & 1 == 1 {
let x = cell_x + col;
atlas[(y * ATLAS_WIDTH + x) as usize] = 255;
}
}
}
}
atlas
}
#[cfg(test)]
mod tests {
use super::*;
/// The font keeps its largest step through 120 digits, steps down once
/// at the 121st, and that step carries the waterfall to the calendar's
/// last digit, the 154th, and on to 200; the third step takes the rest
/// of what the buffer can hold, and nothing falls through to the
/// smallest step at the window's width, which is the fallback nobody
/// is meant to see.
#[test]
fn the_digits_shrink_once_and_only_when_they_must() {
assert_eq!(glyph_scale_for(61, 800), (4, 5));
assert_eq!(glyph_scale_for(120, 800), (4, 5));
assert_eq!(glyph_scale_for(121, 800), (3, 4));
assert_eq!(glyph_scale_for(154, 800), (3, 4));
assert_eq!(glyph_scale_for(200, 800), (3, 4));
assert_eq!(glyph_scale_for(201, 800), (2, 3));
let max = u32::try_from(MAX_DIGITS).expect("two hundred and fifty-six fits a u32");
assert_eq!(glyph_scale_for(max, 800), (2, 3));
}
/// Every step's rows fit the reserve for every count the buffer can
/// hold, at the window's width: the promise `WATERFALL_HEIGHT` makes to
/// the layout beneath it, checked for all 256 counts and not merely the
/// interesting ones.
#[test]
fn every_count_fits_the_reserve() {
let max = u32::try_from(MAX_DIGITS).expect("two hundred and fifty-six fits a u32");
for count in 1..=max {
let (kx, ky) = glyph_scale_for(count, 800);
let per_row = (800 - 2 * X_MARGIN) / (CELL_WIDTH * kx);
assert!(
count.div_ceil(per_row) * CELL_HEIGHT * ky <= WATERFALL_HEIGHT,
"{count} digits overflow the reserve at the step elected for them"
);
}
}
}

View file

@ -0,0 +1,84 @@
// The scar shader of the Loic Observatory.
//
// Renders the topological scars that resolution collapse leaves on the
// surface: the workspace README, section 4.5, for the scars and section
// 7.3 for the collapse. One time in four, the random observer draws a mask
// the lattice cannot hold; the question fails to frame, and what the
// failure leaves is one of three figures, placed at random and never
// removed while the process lives. The GIN gear: a row of twenty-one
// cells whose raised teeth are the set bits of the letters G, I and N in
// seven-bit ASCII, from the seam of the project's logo, at a random
// rotation. The failed mask: a ring with the seven cosmic primes around
// it as dots, filled where the entropy set them, and the phantom eighth
// bit — the one that overflowed the pool — dangling outside the boundary
// in red, on a thin line from where it would have gone. The soliton:
// concentric amber rings fading outward, the project's reading of what a
// severed relation leaves in the weave. Each is a Channel 2 record: not
// what was asked, but that a question was attempted here and could not be
// framed coherently.
//
// The shader knows none of this. It receives vertices already in pixel
// coordinates, each carrying its own RGBA, triangulated by the renderer
// into filled circles, annuli and rotated rectangles; it moves them into
// clip space, with the vertical axis turned over because pixel space
// hangs from the top-left corner and clip space grows upward from the
// centre, and passes each colour through untouched. A scar is drawn last,
// on top of everything, and blocks input on the pixels it covers; that
// policy lives in the renderer and the hit-test, and this file is merely
// where the scar becomes visible.
// The one uniform: the surface's extent in pixels, by which pixel
// coordinates become clip coordinates. The renderer pads its buffer to
// sixteen bytes for the GPU's sake; the shader reads the first eight.
struct Uniforms {
screen_size: vec2<f32>,
};
// Bound for the vertex stage alone; the fragment stage has no use for the
// surface's size, or for anything but the colour it is handed.
@group(0) @binding(0)
var<uniform> uniforms: Uniforms;
// One vertex as the renderer built it: a position in pixels and a colour
// with its own alpha, straight from a vertex buffer that is rebuilt every
// frame from the list of scars, one draw for all of them.
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) color: vec4<f32>,
};
// What the vertex stage hands the fragment stage: the position in clip
// space, and the colour, interpolated across each triangle, which for a
// triangle of one colour changes nothing.
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) color: vec4<f32>,
};
// Vertex stage: pixels into clip space, colour passed through. The scar's
// geometry was decided on the CPU, in pixels, where the hit-test can see
// it; the shader adds nothing to it and takes nothing away.
@vertex
fn vs_main(in: VertexInput) -> VertexOutput {
var out: VertexOutput;
// Horizontal: pixels over width, doubled, less one — minus one at the
// left edge, one at the right.
let clip_x = (in.position.x / uniforms.screen_size.x) * 2.0 - 1.0;
// Vertical: the same, then taken from one, because pixel Y grows
// downward and clip Y grows upward. Flip.
let clip_y = 1.0 - (in.position.y / uniforms.screen_size.y) * 2.0;
out.position = vec4<f32>(clip_x, clip_y, 0.0, 1.0);
out.color = in.color;
return out;
}
// Fragment stage: the interpolated colour, as given. Which colour — the
// white of the teeth, the dim gray of the boundary and of the unset
// primes, the red of the phantom, the amber of the rings, each with its
// own alpha — is the renderer's decision, and the shader has no view on
// it. Alpha blending outside this file lays the scar over whatever it
// covers, which is everything, since it is drawn last.
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return in.color;
}

View file

@ -0,0 +1,258 @@
// ═══════════════════════════════════════════════════════════════════════════════
//
// DIGIT SHADER
//
// The waterfall: the cosmic time — Planck times elapsed since Creation,
// sixty-one digits at present and one hundred and fifty-four at
// Annihilation, where 512 bits run out — set as one textured quad per
// digit, most significant first, wrapping within the margins. Six
// vertices per digit are conjured from the vertex index; there is no
// vertex buffer. The digit values arrive in a storage buffer and the ten
// glyphs in an atlas of ten six-by-eight cells, sampled at whole-number
// magnifications with nearest filtering, so that every texel is a crisp
// block and nothing is ever interpolated into being.
//
// Zones are counted from the last digit, because that is where time
// moves, and they stay where they are as the count grows:
// Zone C, the last 34 digits: cyan — the sub-nanosecond entropy,
// fresh with every observation
// Zone B, the 9 before them: gray — nanosecond to second, faster
// than perception
// Zone A, everything above: white — changes slower than once a second
//
// The arithmetic: a nanosecond holds about 1.855 × 10^34 Planck times
// and a second about 1.855 × 10^43, so 10^34 of them fit in a nanosecond
// and 10^43 in a second. The last thirty-four digits therefore turn over
// entirely between one nanosecond and the next, beneath anything the
// kernel's clock can report; what they show is the entropy the library
// draws for the sub-nanosecond remainder, a different answer at every
// observation, and the shader colours them as what they are. The nine
// above them change within a second and are shown as blur. Everything
// above those can be read. The digit count grows with the age of the
// universe; the zones do not. The present moment is a gradient, not a
// point — the workspace README, section 1.3 — and this is the gradient,
// rendered.
//
// Every number in this file is an f32, because the GPU speaks nothing
// else and because nothing computed here is ever read back as time: it
// is a pixel or it is nothing, which is one of the two exemptions the
// calendar grants, the other being the hum.
//
// ═══════════════════════════════════════════════════════════════════════════════
// What the renderer tells both stages, once per frame: the surface, the
// cell as magnified this frame, the atlas, how many digits there are and
// where they go, and the clock for the shimmer. Bound at group zero,
// binding zero, and visible to the fragment stage as well as the vertex
// stage, because the shimmer needs the clock.
struct Uniforms {
screen_size: vec2<f32>,
glyph_size: vec2<f32>,
atlas_size: vec2<f32>,
digit_count: u32,
y_offset: u32, // Top of the first row, in pixels: sixty, just below the header
x_margin: u32, // Air at both sides, in pixels: forty, as the timeline's bar keeps
time: f32, // Seconds since the renderer was born, as an f32; for the shimmer only
}
// What the vertex stage hands the fragment stage, interpolated across the
// quad: the position, the texture coordinate, the zone's colour, and how
// deep into the entropy this digit lies.
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
@location(2) glow_intensity: f32, // zero outside zone C, one at the last digit
}
// The four bindings: the uniforms for both stages, the atlas and its
// nearest-filtering sampler for the fragment stage, and the digits, most
// significant first, for the vertex stage alone.
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var glyph_texture: texture_2d<f32>;
@group(0) @binding(2) var glyph_sampler: sampler;
@group(0) @binding(3) var<storage, read> digits: array<u32>;
// The three colours of the zones. The cyan is the Observatory's own, the
// one the text renderer packs as #33E6CC, to within a rounding of the
// green.
const COLOR_A: vec3<f32> = vec3<f32>(1.0, 1.0, 1.0); // white: slower than a second
const COLOR_B: vec3<f32> = vec3<f32>(0.5, 0.5, 0.5); // gray: within a second, blur
const COLOR_C: vec3<f32> = vec3<f32>(0.2, 0.9, 0.8); // cyan: within a nanosecond, entropy
// Zone C: the last thirty-four digits. 10^34 Planck times fit in a
// nanosecond, and a nanosecond is the finest thing the clock reports, so
// every one of these digits is the library's entropy, drawn afresh for
// each observation and owed to no clock at all.
const QUANTUM_DIGITS: u32 = 34u;
// Zone B: the nine digits before those, from a nanosecond up to a second,
// 10^43 over 10^34. They change faster than an eye can follow and slower
// than the entropy does, and are coloured accordingly.
const BLUR_DIGITS: u32 = 9u;
// The distance of a digit from the last one: zero for the last digit
// itself, the count less one for the first. The zones are measured in
// this and never in the index from the front, which is why the count may
// grow without the colours moving. Unsigned arithmetic, so it is only
// ever asked about an index the draw call actually issued.
fn digits_from_end(digit_index: u32) -> u32 {
return uniforms.digit_count - 1u - digit_index;
}
// The colour of a digit by its distance from the end. Inside zone C it
// runs from the gray of zone B at the zone's first digit to full cyan at
// the last; inside zone B, from the white of zone A at its first digit to
// gray at its last; above both, white. Two ramps with no step between
// them, so that the eye reads one gradient rather than three bands, which
// is what the present moment is.
fn get_zone_color(digit_index: u32) -> vec3<f32> {
let from_end = digits_from_end(digit_index);
if (from_end < QUANTUM_DIGITS) {
// All but gray at the zone's first digit, cyan at the last.
let t = 1.0 - f32(from_end) / f32(QUANTUM_DIGITS);
return mix(COLOR_B, COLOR_C, t);
} else if (from_end < QUANTUM_DIGITS + BLUR_DIGITS) {
// All but white at the zone's first digit, gray at its last.
let t = 1.0 - f32(from_end - QUANTUM_DIGITS) / f32(BLUR_DIGITS);
return mix(COLOR_A, COLOR_B, t);
}
return COLOR_A;
}
// Vertex stage: one call per corner per digit, six per instance. It
// places the digit's quad on the surface, selects the digit's cell in the
// atlas, and decides the digit's colour and glow by its distance from the
// end, all of which the fragment stage receives interpolated, though only
// the texture coordinate actually varies across a quad.
@vertex
fn vs_main(
@builtin(vertex_index) vertex_index: u32,
@builtin(instance_index) instance_index: u32,
) -> VertexOutput {
var out: VertexOutput;
// The quad: two triangles, six vertices, drawn from the vertex index
// alone in the unit square, which the cell's size and position will
// stretch into place. The corners, and the order the triangles take
// them in:
// 0--1 Triangles: 0,1,2 and 2,1,3
// |\ |
// | \|
// 2--3
let quad_uvs = array<vec2<f32>, 6>(
vec2<f32>(0.0, 0.0), // 0, top-left
vec2<f32>(1.0, 0.0), // 1, top-right
vec2<f32>(0.0, 1.0), // 2, bottom-left
vec2<f32>(0.0, 1.0), // 2, again
vec2<f32>(1.0, 0.0), // 1, again
vec2<f32>(1.0, 1.0), // 3, bottom-right
);
let quad_uv = quad_uvs[vertex_index];
// This instance's digit, from the storage buffer, most significant
// first; the vertex stage is the one stage permitted to read it.
let digit_value = digits[instance_index];
// Where on the surface this digit lives: the rows wrap within the
// margins, as many digits to a row as whole cells fit the content
// width, and the arithmetic is integer until the pixel.
let margin = f32(uniforms.x_margin);
let content_width = uniforms.screen_size.x - 2.0 * margin;
let chars_per_row = u32(content_width / uniforms.glyph_size.x);
let row = instance_index / chars_per_row;
let col = instance_index % chars_per_row;
let base_x = margin + f32(col) * uniforms.glyph_size.x;
let base_y = f32(row) * uniforms.glyph_size.y + f32(uniforms.y_offset);
// The vertex, in pixels: the cell's corner plus the quad's unit
// coordinate scaled to the cell's magnified size.
let pixel_pos = vec2<f32>(
base_x + quad_uv.x * uniforms.glyph_size.x,
base_y + quad_uv.y * uniforms.glyph_size.y
);
// Into clip space, minus one to one on both axes, the vertical one
// turned over, because pixel space grows downward and clip space grows
// upward, and neither will yield.
let clip_pos = vec2<f32>(
(pixel_pos.x / uniforms.screen_size.x) * 2.0 - 1.0,
1.0 - (pixel_pos.y / uniforms.screen_size.y) * 2.0 // the turning over
);
out.position = vec4<f32>(clip_pos, 0.0, 1.0);
// The texture coordinate. The atlas is ten cells in one row, so a
// digit's cell is a tenth of the width, and the whole cell — five
// columns of ink and one of air, eight rows with the last of them air —
// is mapped onto the whole quad, air included, which is what keeps the
// digits apart.
let glyph_width = uniforms.atlas_size.x / 10.0;
let u_start = f32(digit_value) * glyph_width / uniforms.atlas_size.x;
let u_end = u_start + glyph_width / uniforms.atlas_size.x;
out.uv = vec2<f32>(
mix(u_start, u_end, quad_uv.x),
quad_uv.y
);
// The zone's colour, by distance from the end, opaque.
out.color = vec4<f32>(get_zone_color(instance_index), 1.0);
// The glow: zero outside zone C, rising through it to one at the last
// digit, and carried to the fragment stage for the shimmer.
let from_end = digits_from_end(instance_index);
if (from_end < QUANTUM_DIGITS) {
out.glow_intensity = 1.0 - f32(from_end) / f32(QUANTUM_DIGITS);
} else {
out.glow_intensity = 0.0;
}
return out;
}
// Fragment stage: the zone's colour at the atlas's coverage, and for zone
// C a shimmer on top, since digits that are entropy should not sit still.
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
// Coverage from the atlas's one channel, taken nearest, which is the
// pixel's alpha: the air around a glyph is transparent, and the ink is
// as opaque as ink.
let alpha = textureSample(glyph_texture, glyph_sampler, in.uv).r;
// The shimmer, for zone C alone: the entropy digits glow, and the glow
// breathes.
if (in.glow_intensity > 0.0) {
// Three sines at three angular frequencies — three, seven and
// eleven radians per second — each digit shifted in phase by its
// depth in the zone, so that the glow travels along the digits
// rather than pulsing in unison. Three, seven and eleven are also
// three of the five prime factors of the Unix offset, 5,419,722; no
// mask is stated for that observation, so by the workspace README,
// section 0, it is Channel 1, and it is recorded here only so that
// nobody discovers it later.
let phase_offset = in.glow_intensity * 6.28318; // one full turn, 2π, across the zone
let wave1 = sin(uniforms.time * 3.0 + phase_offset) * 0.5 + 0.5;
let wave2 = sin(uniforms.time * 7.0 + phase_offset * 1.7) * 0.5 + 0.5;
let wave3 = sin(uniforms.time * 11.0 + phase_offset * 2.3) * 0.5 + 0.5;
// The three waves, weighted to sum to one, so that the shimmer lies
// between zero and one and the weights say which wave leads.
let shimmer = wave1 * 0.5 + wave2 * 0.3 + wave3 * 0.2;
// Deeper into the zone, stronger: the last digit may brighten by
// forty percent, the zone's first by almost nothing.
let glow_strength = in.glow_intensity * 0.4; // at most a forty percent boost
let brightness_boost = 1.0 + shimmer * glow_strength;
// Brightened, and clamped at one per channel; the target would
// clamp it anyway, but the shader prefers to say so itself.
let glowing_color = min(in.color.rgb * brightness_boost, vec3<f32>(1.0, 1.0, 1.0));
return vec4<f32>(glowing_color, alpha);
}
// Zones A and B: the colour, unshimmering, at the coverage.
return vec4<f32>(in.color.rgb, alpha);
}

View file

@ -0,0 +1,70 @@
// The veil of the Loic Observatory.
//
// This shader concerns itself with one task, monumental in the way that
// only the simplest tasks are: drawing a rectangle. Not any rectangle — a
// rectangle the size of the surface, in one colour at one alpha, blended
// over whatever the pass has already drawn, so that a passage may be read
// against a dimmed field rather than against the temporal cacophony. It
// has no texture, no vertex buffer, no attributes and no opinions; it is
// given a colour and it returns the colour, for every fragment, without
// looking.
//
// The colour it is given, unless someone asks otherwise, is the surface's
// own clear colour at eighty-five percent alpha: a shroud the exact shade
// of the void behind it. And in the Observatory's composition, while a
// passage is open the waterfall, the panels and the scars are not drawn at
// all, so the veil is blended over the cleared void alone and dims a field
// that was never lit. The dimming is real. Its subject is absent. The
// shader is not told this, and would not change its behaviour if it were:
// the rectangle is drawn, at the alpha requested, with perfect fidelity to
// an instruction whose consequence is invisible, which is a fate the
// calendar recognises.
// All the vertex stage has to say: a position. There is no colour to
// carry and no coordinate to sample by; the fragment stage has the
// uniform, and needs nothing from the vertex but where it is.
struct VertexOutput {
@builtin(position) position: vec4<f32>,
};
// The one uniform: the veil's colour — red, green, blue and alpha, each
// from zero to one — bound for the fragment stage alone. A humble vec4
// bearing the entire weight of the shader's output, since the output is
// this and nothing else.
@group(0) @binding(0)
var<uniform> overlay_color: vec4<f32>;
// Vertex stage: six positions drawn from the vertex index alone, no
// buffer consulted — the corners of clip space, minus one to one on both
// axes, as two triangles: bottom-left, bottom-right, top-left; then
// top-left, bottom-right, top-right. The pair covers the surface exactly,
// whatever its size, because clip space is the same size on every
// surface, which is the one convenience the GPU offers without being
// asked.
@vertex
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
// The corners, in clip space, where up is up and no turning over is
// owed.
var positions = array<vec2<f32>, 6>(
vec2<f32>(-1.0, -1.0), // bottom-left
vec2<f32>( 1.0, -1.0), // bottom-right
vec2<f32>(-1.0, 1.0), // top-left, closing the first triangle
vec2<f32>(-1.0, 1.0), // top-left again, opening the second
vec2<f32>( 1.0, -1.0), // bottom-right again
vec2<f32>( 1.0, 1.0), // top-right
);
var output: VertexOutput;
output.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
return output;
}
// Fragment stage: the uniform colour, for every fragment, unconditionally.
// No sampling, no arithmetic, no cleverness; the blend state outside this
// file does the dimming, weighting by the alpha this colour carries, and
// the shader's whole contribution is to hold one opinion about one colour
// across the entire surface.
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return overlay_color;
}

View file

@ -0,0 +1,140 @@
// ═══════════════════════════════════════════════════════════════════════════════
//
// TEXT SHADER
//
// The lettering of the Observatory: every run of characters, set as one
// textured quad per character from a grayscale atlas of one hundred and
// twelve cells, sixteen to a row, seven rows. Each instance is sixteen
// bytes from a storage buffer — a position in pixels, a cell index and a
// packed colour — and each becomes six vertices conjured from the vertex
// index, since there is no vertex buffer and none is missed. The atlas
// is sampled linearly at exactly one texel per pixel, which is a copy
// when the position is whole and a half-pixel smear when it is not.
//
// The floating point is the GPU's, not the calendar's: nothing computed
// here is a quantity of time, and nothing leaves but a pixel.
//
// ═══════════════════════════════════════════════════════════════════════════════
// What the renderer tells the vertex stage, once per resize: the surface's
// extent, the cell's, and the atlas's grid. Twenty-four bytes, the mirror
// of the renderer's own `Uniforms`, and the fragment stage never sees them.
struct Uniforms {
screen_size: vec2<f32>,
glyph_size: vec2<f32>,
atlas_cols: u32,
atlas_rows: u32,
}
// One character, sixteen bytes, exactly as the renderer packed it.
struct CharInstance {
pos: vec2<f32>, // The cell's top-left, in pixels from the surface's top-left
glyph_index: u32, // The cell in the atlas, 0 through 111
color: u32, // RGBA, one byte each, red in the high byte
}
// What the vertex stage hands the fragment stage: the position, the
// texture coordinate, and the colour, the last of which is the same at all
// four corners and so survives interpolation unchanged.
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
}
// The four bindings: the uniforms for the vertex stage, the atlas and its
// linear sampler for the fragment stage, and the instances for the vertex
// stage.
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var glyph_texture: texture_2d<f32>;
@group(0) @binding(2) var glyph_sampler: sampler;
@group(0) @binding(3) var<storage, read> chars: array<CharInstance>;
// The packed colour undone: three shifts and four masks, each byte scaled
// to the interval from zero to one. Red was packed highest and alpha
// lowest, and the order here is the same order, or every colour on the
// surface would be some other colour.
fn unpack_color(packed: u32) -> vec4<f32> {
let r = f32((packed >> 24u) & 0xFFu) / 255.0;
let g = f32((packed >> 16u) & 0xFFu) / 255.0;
let b = f32((packed >> 8u) & 0xFFu) / 255.0;
let a = f32(packed & 0xFFu) / 255.0;
return vec4<f32>(r, g, b, a);
}
// Vertex stage: one call per corner per character, six per instance. It
// places the character's quad on the surface, finds its cell in the atlas
// by a modulus and a quotient, and unpacks its colour.
@vertex
fn vs_main(
@builtin(vertex_index) vertex_index: u32,
@builtin(instance_index) instance_index: u32,
) -> VertexOutput {
var out: VertexOutput;
// This instance: the character's position, cell and colour.
let char_data = chars[instance_index];
// The quad: two triangles in the unit square, six vertices from the
// vertex index, corners 0,1,2 and then 2,1,3.
let quad_uvs = array<vec2<f32>, 6>(
vec2<f32>(0.0, 0.0),
vec2<f32>(1.0, 0.0),
vec2<f32>(0.0, 1.0),
vec2<f32>(0.0, 1.0),
vec2<f32>(1.0, 0.0),
vec2<f32>(1.0, 1.0),
);
let quad_uv = quad_uvs[vertex_index];
// The vertex, in pixels: the cell's corner plus the unit coordinate
// scaled to the cell, which is the atlas cell's own size, always.
let pixel_pos = vec2<f32>(
char_data.pos.x + quad_uv.x * uniforms.glyph_size.x,
char_data.pos.y + quad_uv.y * uniforms.glyph_size.y
);
// Into clip space, minus one to one, the vertical axis turned over,
// because pixels grow downward and clip space grows upward.
let clip_pos = vec2<f32>(
(pixel_pos.x / uniforms.screen_size.x) * 2.0 - 1.0,
1.0 - (pixel_pos.y / uniforms.screen_size.y) * 2.0
);
out.position = vec4<f32>(clip_pos, 0.0, 1.0);
// The texture coordinate: the cell's column is the index modulo the
// column count and its row the quotient, and each cell is one
// sixteenth of the atlas across and one seventh of it down.
let col = char_data.glyph_index % uniforms.atlas_cols;
let row = char_data.glyph_index / uniforms.atlas_cols;
let u_size = 1.0 / f32(uniforms.atlas_cols);
let v_size = 1.0 / f32(uniforms.atlas_rows);
let u_start = f32(col) * u_size;
let v_start = f32(row) * v_size;
out.uv = vec2<f32>(
u_start + quad_uv.x * u_size,
v_start + quad_uv.y * v_size
);
// The colour, unpacked once per vertex; the four corners agree, so the
// interpolation between them has nothing to do.
out.color = unpack_color(char_data.color);
return out;
}
// Fragment stage: the atlas's coverage, sampled linearly from its single
// channel, multiplied into the colour's own alpha, so that a glyph's ink
// is as opaque as its colour says and its air is transparent whatever the
// colour says. The colour is not sampled from anything; it arrives with
// the instance and is applied to the coverage as ink to a stencil, which
// is exactly what a bitmap font is.
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
let alpha = textureSample(glyph_texture, glyph_sampler, in.uv).r;
return vec4<f32>(in.color.rgb, in.color.a * alpha);
}

1176
crates/loic-gui/src/text.rs Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

64
crates/loic/Cargo.toml Normal file
View file

@ -0,0 +1,64 @@
# The core library: the lattice, the masks, the instants, the durations and
# the cosmological constants, published to the registry under the
# workspace's one version. Everything else in the workspace is a way of
# looking at what this crate computes. The description, keywords and
# categories are what the registry shows; the readme is what it renders
# beneath them.
[package]
name = "loic"
version.workspace = true
edition = "2024"
authors.workspace = true
repository.workspace = true
license-file.workspace = true
description = "A temporal framework for the network age: 512-bit integer Planck times since the first ARPANET transmission, subdivided by the fifteen prime factors of two cosmological constants, observed through masks, and never once approximated"
keywords = ["planck", "arpanet", "prime-lattice", "chronometric-heresy", "anti-ieee754"]
categories = ["date-and-time", "mathematics", "science", "os::linux-apis"]
readme = "README.md"
# What the library stands on. Nothing here touches a floating-point number
# on the library's behalf, and each is present for one reason, stated.
[dependencies]
# 512-bit and 1024-bit integers — `I512`, `U512` and `U1024` — with `const`
# arithmetic, the `n!` literal macro and the `As` cast trait: the entire
# numeric substrate of the calendar. Everything the library adds, subtracts,
# multiplies or divides at cosmological width, it does through these types,
# and the release profile's optimisation level for dependencies is where
# their speed is decided.
bnum = "0.14"
# The derive behind `LoicError`, so that each way the lattice can decline a
# request carries its message in voice and implements the standard error
# trait without a line of boilerplate to dilute it.
thiserror = "2.0"
# Serialization, optional: the `serde` feature below turns it on, together
# with `bnum`'s own support, so that an instant can leave the process as
# digits and return as the same digits, with `derive` within reach.
serde = { version = "1.0", features = ["derive"], optional = true }
# The kernel's own interfaces: `clock_gettime` on `CLOCK_TAI`, which the
# standard library does not expose, and `adjtimex(2)`, through which the TAI
# lie detector reads the offset the kernel has or has not been told.
libc = "0.2"
# The seed of every thread's entropy stream, drawn once from the kernel's
# pool; re-exported, so that the oracle can flood its terminal from the same
# pool during resolution collapse.
getrandom = "0.4"
# What the tests stand on and the library does not; nothing here reaches a
# consumer of the crate.
[dev-dependencies]
# JSON, for the tests alone: a serialization a test can read back with its
# own eyes when the `serde` feature is under examination.
serde_json = "1.0"
# Nothing is on by default. `serde` is opt-in, and enabling it enables
# `bnum`'s serde support alongside, since an instant's digits are `bnum`'s
# digits and would otherwise have no way to leave the process.
[features]
default = []
serde = ["dep:serde", "bnum/serde"]
# The library target, named and placed explicitly rather than inferred, so
# that nothing about where the calendar lives is left to convention.
[lib]
name = "loic"
path = "src/lib.rs"

99
crates/loic/README.md Normal file
View file

@ -0,0 +1,99 @@
# loic
The core library for the Loic Calendar—a temporal framework measuring time from the first ARPANET transmission with Planck-scale precision.
## Overview
This library provides:
- **`LoicInstant`** — A moment in time, represented as a 512-bit signed integer counting Planck times (~5.39 x 10^-44 seconds) since the epoch
- **`LoicDuration`** — A span of time in Planck units
- **`Mask`** — An observer configuration selecting active primes from the 15-prime lattice
- **`GridCoord`** — A position in the 128x256 asymmetric lattice (7 cosmic bits x 8 cycle bits)
- **`SubdivisionResult`** — The result of observing an instant through a mask
- **Cosmological coordinates** — Your position between Creation (Big Bang) and Annihilation (heat death)
## Usage
```rust
use loic::{LoicInstant, Mask};
// Observe the current moment
let now = LoicInstant::now();
// Raw Planck timestamp
println!("{}", now.planck());
// Cosmological inquiry
println!("Since Creation: {}", now.cosmic_time());
println!("Until Annihilation: {}", now.terminal_time());
// Lattice position
let coord = now.grid_coord();
println!("Grid: ({}, {})", coord.cosmic(), coord.cycle());
// Observe through a mask (the mask is the observer)
let mask = Mask::dyad(); // The binary split — cycle prime 2
let observation = mask.observe(&now).unwrap();
println!("Position: {}", observation.position());
```
## The Lattice
15 prime factors (7 cosmic, 8 cycle) generate 32,768 temporal subdivisions. A mask selects which primes are active. The product of active primes determines the divisor. Any instant can be observed at any mask's resolution.
### Cosmic Primes (7 — named for logic gates)
| Name | Gate | Prime |
|------|------|-------|
| Andyte | AND | 16,631 |
| Xoryte | XOR | 57,251 |
| Oryte | OR | 21,325,891 |
| Noryte | NOR | 3,014,283,645,143 |
| Xnoryte | XNOR | 128,029,476,410,837,813,209,853,261 |
| Notyte | NOT | 298,824,857,074,158,001,946,609,249 |
| Nandyte | NAND | 2,862,914,325,674,107...999,805,373 |
### Cycle Primes (8 — axes of temporal subdivision)
| Name | Prime | Character |
|------|-------|-----------|
| Dyad | 2 | The binary split |
| Pentad | 5 | The decimal bridge |
| Heptad | 7 | The week |
| Hendecad | 11 | The prime of primes |
| Sigma | 683 | The first stranger |
| Tau | 2,887 | The second stranger |
| Phi | 4,279,037,621,376,791,777,197 | The cosmic grain |
| Psi | 80,553,260,809,276,197,882,377 | The final factor |
## The Epoch
```
1969-10-30 06:30:41 UTC
```
The moment the first ARPANET message was transmitted. The offset 5,419,722 seconds from Unix epoch is squarefree (2 x 3 x 7 x 11 x 11,731), containing three cycle primes.
## Platform Requirements
This library requires Linux with `CLOCK_TAI` support (kernel 3.10+).
The Loic Calendar is built on TAI (International Atomic Time), which maintains the noble pretense that time flows uniformly. Operating systems that smear leap seconds, pretend they don't exist, or fail to provide atomic time have disqualified themselves from temporal inquiry.
Attempting to compile on unsupported platforms will fail. This is intentional.
It also requires the kernel to actually know what TAI is. `CLOCK_TAI` is `CLOCK_REALTIME` plus an offset that the kernel does not learn by itself: a time daemon has to read a leap-second table and set it through `adjtimex(2)`. chrony does this with `leapseclist /usr/share/zoneinfo/leap-seconds.list` or `leapsectz right/UTC`; ntpd with a `leapfile`; systemd-timesyncd does not do it at all. On a machine where the offset is zero, the first call to `LoicInstant::now()` panics and tells you which of those to configure. It will not observe a clock that is lying by a known amount.
## Precision and Storage
Time is stored as `I512` (512-bit signed integer) internally, providing:
- **Precision:** Individual Planck times (~5.39 x 10^-44 seconds)
- **Range:** From Creation (~13.8 billion years before epoch) to Annihilation (2^511 - 1 Planck times, ~1.1 x 10^103 years from now — three orders of magnitude after the last black hole evaporates)
No floating-point arithmetic contaminates temporal calculations. The integers are exact. The timestamps are correct.
## License
Dual-licensed under AGPL-3.0 and the Loic Public License. See the workspace root for full terms, and the workspace README for the theoretical substrate the license keeps citing.

5637
crates/loic/src/lib.rs Normal file

File diff suppressed because it is too large Load diff

26
crates/loid/Cargo.toml Normal file
View file

@ -0,0 +1,26 @@
# The LOID generator: a Planck-time timestamp with entropy in its
# sub-nanosecond digits, offered as an identifier — two functions, an
# integer, and a refusal to be a UUID. Published under the workspace's one
# version; the registry metadata below is what it shows.
[package]
name = "loid"
version.workspace = true
edition = "2024"
authors.workspace = true
repository.workspace = true
license-file.workspace = true
description = "Loic Identifier. A Planck-time timestamp with hardware entropy in its sub-nanosecond digits. An integer. Your problem."
readme = "README.md"
keywords = ["identifier", "planck", "arpanet", "not-a-uuid", "your-problem"]
categories = ["date-and-time"]
# The one dependency: the calendar itself, at the workspace's single stated
# version. A LOID is an instant that has been asked to serve as a name, and
# an instant is the library's to make.
[dependencies]
loic.workspace = true
# The library target, named and placed explicitly rather than inferred.
[lib]
name = "loid"
path = "src/lib.rs"

41
crates/loid/README.md Normal file
View file

@ -0,0 +1,41 @@
# loid
Loic Identifier. A Planck-time timestamp. An integer. Your problem.
```rust
let id = loid::loid(); // ~53 decimal digits, subject to the inevitable passing of time
let short = loid::short(); // ~30 decimal digits, subject to the inevitable passing of time
```
Two functions. One type (`I512`). One dependency (`loic`). No wrapper. No Display of
its own. No serde. No monotonicity. No opinions. Universal and absolute.
## What it does
Each call samples the current moment via `CLOCK_TAI` (atomic time) and a generator
seeded from the kernel's entropy pool and stirred with the nanosecond of the
observation itself, producing a 512-bit signed integer counting Planck times since
the Loic epoch (the first ARPANET transmission, 1969-10-30 06:30:41 UTC). Nineteen
of its digits say which nanosecond you are in. The remaining thirty-four are the
universe's answer to which Planck time within that nanosecond, and the universe does
not repeat itself.
`short()` divides the full timestamp by 10²³, keeping ~11 of the original ~34
entropy digits. Two `short()` values minted in the same nanosecond collide with
probability better than one in a hundred billion, which is either reassuring or
terrifying depending on what you were planning to do with them.
## Requirements
Linux, and a kernel that knows what TAI is. `CLOCK_TAI` is only TAI if a time daemon
has read a leap-second table and told the kernel the offset — chrony with
`leapseclist /usr/share/zoneinfo/leap-seconds.list` or `leapsectz right/UTC`, or ntpd with a `leapfile`. systemd-timesyncd never does. On a
machine where the offset is zero, the first call panics and tells you which line to
add. If you're on anything else, this crate is not for you, and you should reflect on
why.
## License
Dual-licensed under AGPL-3.0 and the Loic Public License. See the workspace root for
the terms, and the workspace README for the theoretical substrate the license keeps
citing.

149
crates/loid/src/lib.rs Normal file
View file

@ -0,0 +1,149 @@
//! # LOID — Loic Identifier
//!
//! Two functions. One type. No opinions, beyond the several that follow.
//!
//! A LOID is a Planck-time timestamp drawn from the Loic Calendar's quantum
//! observation pipeline—the mask-free half of it, the collapse without the
//! question. Each invocation of `loid()` collapses the sub-nanosecond
//! superposition of the present moment into a unique 512-bit signed
//! integer—deterministic in its upper digits (the atomic clock, read through
//! `CLOCK_TAI`), entropic in its lower digits (a per-thread generator seeded
//! from the kernel's pool and stirred by the timing of the observation
//! itself), and unreasonably large by any conventional metric, being a count
//! of Planck times since the first transmission between networked machines
//! and therefore some fifty-three digits long before it has finished
//! introducing itself.
//!
//! The shortened variant, `short()`, amputates the lowest 23 decimal orders
//! of magnitude via integer division, retaining ~11 digits of quantum
//! entropy from the original ~34. The result is still an `I512`. It is still
//! your problem. The workspace README lists this crate among the four as the
//! one with no wrapper type and no opinions; the second claim was
//! aspirational.
//!
//! ## What This Is Not
//!
//! - Not monotonic. Two calls within the same nanosecond may produce values
//! in either order, because the entropy that fills the nanosecond makes no
//! promises about sequence—it makes exactly one promise, uniformity, and
//! uniformity is the opposite of order. Across nanoseconds the atomic
//! clock is doing its best, and atomic clocks, when disciplined over a
//! network, have been known to step. If you need monotonicity, enforce it
//! yourself. The universe doesn't care, and per the workspace README,
//! section 1.3, does not even agree with itself about simultaneity.
//!
//! - Not a UUID. Not a ULID. Not a KSUID. Not a Snowflake. Not any of the
//! carefully-engineered identifier schemes designed by reasonable people
//! for reasonable systems, with their version nibbles and their variant
//! bits and their sixty-four-bit ambitions. This is a raw Planck timestamp
//! with entropy spliced into its sub-nanosecond residue—the Loic Public
//! License, Section 10, lists "generating unique identifiers from quantum
//! observations of the sub-nanosecond void" among the permitted uses, and
//! this crate is that permission exercised and nothing more. What you do
//! with it is, as noted above, your problem.
//!
//! - Not wrapped. There is no newtype, no `Display` of its own, no `FromStr`
//! of its own, no serde. The output is `I512`, which already has
//! `to_string()` and `from_str()`. The rest is ceremony, and ceremony is
//! not shipped here; a caller who wants an instant with methods on it
//! wants `loic::LoicInstant`, which is where these two functions get
//! theirs.
//!
//! - Not tested here. Every test would have to call `now()`, and `now()`
//! refuses machines whose kernel does not know what TAI is (see below), so
//! a test suite would pass or fail according to your time daemon rather
//! than this crate. The arithmetic is `loic`'s and is tested there, where
//! it is checked against a naive formula at twice the width; there is
//! nothing in these two functions to test that is not either that
//! arithmetic or the kernel.
//!
//! ## Usage
//!
//! ```rust,no_run
//! let id = loid::loid(); // full Planck timestamp (~53 digits)
//! let short_id = loid::short(); // truncated by 10^23 (~30 digits)
//! ```
#![warn(clippy::pedantic)]
/// The one type. Re-exported from `loic`, which re-exports it from `bnum`,
/// so that a caller who names `loid::I512` and a caller who names
/// `loic::I512` are naming the same integer and not two integers that
/// merely agree—a distinction the type system enforces and a reader may
/// safely forget, which is the best kind of distinction. Five hundred and
/// twelve bits, signed, of which a fresh identifier uses about a hundred
/// and seventy-five.
pub use loic::I512;
/// Procures a fresh Loic Identifier: the full Planck timestamp of this
/// instant, as an integer, with nothing wrapped around it.
///
/// Each call observes the current moment through the Loic Calendar's
/// dual-source temporal pipeline—atomic time for the deterministic
/// component, entropy seeded from the kernel's pool and stirred by the
/// observation's own timing for the sub-nanosecond quantum residue—and
/// returns the resulting `I512`, copied out of the instant it came in,
/// since the instant has nothing else to offer an identifier.
///
/// The value contains approximately 19 deterministic digits (from
/// `CLOCK_TAI`, encoding which nanosecond you are in) and 34 entropic digits
/// (from the seeded generator, collapsing the sub-nanosecond superposition
/// of roughly 10³⁴ Planck-scale coordinates into one), totaling roughly 53
/// decimal digits. The two are not added but concatenated: the nanosecond
/// occupies the high digits and the collapse the low ones, and the whole is
/// one integer counting Planck times since the Whisper, not a pair of
/// numbers wearing a single type. Whether this degree of precision is
/// necessary, useful, or sane is a question this crate declines to
/// entertain, and the Loic Public License, Section 2, declines on its
/// behalf.
///
/// # Panics
///
/// Panics under the same three conditions as `loic::LoicInstant::now()`, of
/// which it is the thinnest possible wrapper: if `CLOCK_TAI` is unavailable,
/// if the kernel's entropy pool cannot furnish the generator's seed, or—once
/// per process, on the first call—if the kernel reports a TAI offset of
/// zero, which means `CLOCK_TAI` has been `CLOCK_REALTIME` in a name tag all
/// along. The first two do not occur on any Linux of the kernel generation
/// the calendar requires. The third occurs on most of them, until chrony or
/// ntpd is told where the leap-second table is; the panic message says which
/// line to add, and the workspace README, section 1.2, says why it matters.
/// On other operating systems, you should not be here, and the compiler will
/// already have said so.
#[inline]
#[must_use = "A Loic Identifier minted and discarded — the universe collapsed thirty-four digits of superposition for an integer nobody kept, and it will not collapse them the same way twice."]
pub fn loid() -> I512 {
*loic::LoicInstant::now().planck()
}
/// Procures a shortened Loic Identifier: the full timestamp divided by
/// 10²³, by one 512-bit division that truncates toward zero.
///
/// This function observes the full instant exactly as `loid()` does—
/// generating the full 34 digits of quantum entropy—and only then truncates
/// 23 of them away, through `loic::LoicInstant::shortened()`. The ordering
/// matters: one does not generate 11 digits of entropy directly. One
/// generates 34 and discards 23, because the generator draws uniformly at a
/// fixed granularity of one Planck time and truncating post-hoc preserves
/// the statistical properties of the original quantum observation, whereas
/// a generator asked for eleven digits would be answering a question about
/// a coarser superposition that the calendar does not recognise.
///
/// The result retains approximately 11 digits of entropy, sufficient to
/// distinguish simultaneous observations with high probability. "High
/// probability" here means "better than one in a hundred billion," which is
/// either reassuring or terrifying depending on your failure mode
/// tolerance, and which the calendar notes is a great deal better than the
/// odds most calendars offer two events in the same second.
///
/// # Panics
///
/// Same conditions as `loid()`, for the same reason: the observation is the
/// same. The truncation itself cannot fail; integer division by a power of
/// ten is the one operation in this workspace that has never had an
/// opinion.
#[inline]
#[must_use = "A shortened Loic Identifier minted and discarded — twenty-three digits were amputated to make it convenient, and it was still not kept, which suggests convenience was not the obstacle."]
pub fn short() -> I512 {
loic::LoicInstant::now().shortened()
}