A familiar document model. More choice in how you run it.
+ >}
+
+
+ {prompt ? :
+
Document databases keep profiles, product catalogs, and AI records close to the application's data model.
+ Nested fields and evolving attributes do not require a table for every shape. But the document model does not
+ dictate one engine, API, license, or cloud.
+
Open-source DocumentDB combines BSON documents and selected compatible driver operations with PostgreSQL's
+ mature database foundation and an MIT license. Start locally, test real queries and compatibility, then choose
+ self-hosting or managed operations. Choose documents for the application and hosting for the organization.
+ {currentFeedback?.error
+ ? expanded ? "Could not copy. Select the prompt text and copy it manually." : "Could not copy. Show the prompt and copy it manually."
+ : currentFeedback ? "Copied. Paste into your coding agent, not a shell."
+ : prompt?.expected ?? "Document model · PostgreSQL foundation · MIT licensed"}
+
+
+
+
+
+ );
+}
diff --git a/app/components/campaign/CampaignFilm.module.css b/app/components/campaign/CampaignFilm.module.css
new file mode 100644
index 0000000..17206de
--- /dev/null
+++ b/app/components/campaign/CampaignFilm.module.css
@@ -0,0 +1,536 @@
+/*
+ * Layout states for the campaign film, switched by data-mode on .root:
+ *
+ * poster a static preview; no WebGL or renderer download until Play.
+ * film WebGL is available: the film plays behind the hero, with one
+ * line of narration and a pause button under it.
+ * static no WebGL (or a very short viewport): the hero, followed by the
+ * film's eight steps as a plain list.
+ *
+ * The traditional hero scrolls into its written fallback. The prompt layout
+ * fits the remaining viewport between the site's navigation and footer.
+ */
+
+.root {
+ /* Height of the announcement bar and the site header above the stage; the
+ component measures the real value once it runs. */
+ --film-top: 101px;
+ --stage-h: calc(100vh - var(--film-top));
+ position: relative;
+ isolation: isolate;
+ background: #05070a;
+}
+
+:global(body):has(.root[data-layout="prompt"]) {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+ height: 100dvh;
+}
+
+:global(body):has(.root[data-layout="prompt"]) > * {
+ flex-shrink: 0;
+}
+
+:global(body):has(.root[data-layout="prompt"]) > :global(main) {
+ flex: 1;
+ min-height: 0;
+}
+
+.root[data-layout="prompt"] {
+ height: 100%;
+}
+
+.root[data-layout="prompt"] .stage {
+ height: 100%;
+ min-height: 0;
+}
+
+.root[data-layout="prompt"] .frame {
+ height: 100%;
+}
+
+.root[data-layout="prompt"] .topbar {
+ flex-shrink: 0;
+ height: 0.5rem;
+}
+
+.root[data-layout="prompt"] .copy {
+ max-width: min(38rem, 48vw);
+ padding: 0.5rem 0 1rem;
+}
+
+.compactSteps {
+ position: absolute;
+ z-index: 4;
+ top: 1rem;
+ right: 1.5rem;
+ bottom: 5rem;
+ display: grid;
+ gap: 0.5rem;
+ width: calc(50% - 2.5rem);
+ overflow: auto;
+ list-style: none;
+}
+
+.compactSteps .stepItem {
+ padding: 1rem;
+}
+
+@supports (height: 100dvh) {
+ .root {
+ --stage-h: calc(100dvh - var(--film-top));
+ }
+}
+
+.stage {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ min-height: var(--stage-h);
+ overflow: hidden;
+}
+
+/* Shown until the first WebGL frame, and kept as the static-mode background.
+ It mirrors the scene's own backdrop so the canvas can fade in over it. */
+.backdrop {
+ position: absolute;
+ inset: 0;
+ z-index: 0;
+ background:
+ radial-gradient(ellipse 60% 55% at 70% 48%, rgba(14, 116, 168, 0.3), transparent 70%),
+ radial-gradient(ellipse 45% 40% at 86% 88%, rgba(16, 185, 129, 0.1), transparent 70%),
+ linear-gradient(180deg, #070b12 0%, #030405 100%);
+}
+
+.poster {
+ position: absolute;
+ z-index: 1;
+ left: var(--film-focus-left, 50%);
+ top: var(--film-focus-top, 1rem);
+ width: var(--film-focus-width, calc(50% - 1.5rem));
+ height: var(--film-focus-height, calc(100% - 6rem));
+ pointer-events: none;
+ transition: opacity 1.2s ease;
+}
+
+.poster img {
+ object-fit: contain;
+ mask-image:
+ linear-gradient(to right, transparent, #000 8%, #000 92%, transparent),
+ linear-gradient(to bottom, transparent, #000 3%, #000 94%, transparent);
+ mask-composite: intersect;
+}
+
+.poster[data-hidden="true"] {
+ opacity: 0;
+}
+
+.root[data-mode="static"] .poster {
+ display: none;
+}
+
+.scene {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 1.2s ease;
+}
+
+.scene[data-ready="true"] {
+ opacity: 1;
+}
+
+.scene canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+}
+
+.root:not([data-mode="film"]) .scene {
+ display: none;
+}
+
+/* Keeps the copy and the narration readable over whatever the film shows. */
+.scrim {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ pointer-events: none;
+ background:
+ linear-gradient(0deg, rgba(5, 7, 10, 0.9) 0%, rgba(5, 7, 10, 0.55) 9%, rgba(5, 7, 10, 0) 20%),
+ linear-gradient(
+ 90deg,
+ rgba(5, 7, 10, 0.94) 0%,
+ rgba(5, 7, 10, 0.82) 26%,
+ rgba(5, 7, 10, 0.42) 44%,
+ rgba(5, 7, 10, 0) 60%
+ );
+}
+
+.frame {
+ position: relative;
+ z-index: 3;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ width: 100%;
+ max-width: 80rem;
+ min-height: 0;
+ margin: 0 auto;
+ padding: 0 1.5rem;
+}
+
+/* Clear space under the site header. Its lower edge is the upper edge of the
+ area the film is framed in, so its height is part of the film's framing. */
+.topbar {
+ height: 2.75rem;
+}
+
+.copy {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ justify-content: center;
+ /* Narrower on small laptops, so the film keeps about half the width. */
+ max-width: min(35rem, 44vw);
+ min-height: 0;
+ padding: 1.25rem 0 1rem;
+}
+
+.heading {
+ font-size: clamp(2.05rem, min(4.5vw, 7.4vh), 3.75rem);
+ font-weight: 600;
+ line-height: 1.07;
+ letter-spacing: -0.025em;
+ color: #fff;
+ text-wrap: balance;
+}
+
+.buttons {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 1rem;
+ margin-top: 2rem;
+}
+
+/* Narration: a pause button, one line that changes with each shot, and a
+ hairline showing how far the film has run. */
+.player {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ align-items: center;
+ gap: 0.75rem 0.9rem;
+ padding: 0.5rem 0 1.5rem;
+}
+
+.root[data-mode="static"] .player {
+ display: none;
+}
+
+.toggle {
+ display: grid;
+ width: 2.25rem;
+ height: 2.25rem;
+ place-items: center;
+ border: 1px solid rgba(125, 211, 252, 0.35);
+ border-radius: 999px;
+ background: rgba(8, 20, 30, 0.7);
+ color: #e0f2fe;
+ cursor: pointer;
+ transition:
+ border-color 0.2s ease,
+ background-color 0.2s ease;
+}
+
+.toggle:hover {
+ border-color: #7dd3fc;
+ background: rgba(14, 40, 58, 0.85);
+}
+
+.toggle:disabled {
+ opacity: 0.5;
+ cursor: wait;
+}
+
+.toggle:focus-visible {
+ outline: 2px solid #7dd3fc;
+ outline-offset: 3px;
+}
+
+.toggleIcon {
+ width: 0.7rem;
+ height: 0.7rem;
+ fill: currentColor;
+}
+
+/* Every line shares one grid cell, so the bar keeps its height as they change. */
+.captions {
+ display: grid;
+ min-width: 0;
+}
+
+.caption {
+ grid-area: 1 / 1;
+ align-self: center;
+ margin: 0;
+ font-size: 0.9375rem;
+ line-height: 1.45;
+ color: #cbd5e1;
+ text-shadow: 0 0 14px #05070a;
+ opacity: 0;
+ transform: translateY(6px);
+ transition:
+ opacity 0.35s ease,
+ transform 0.45s cubic-bezier(0.2, 0.7, 0.2, 1);
+}
+
+.caption[data-active="true"] {
+ opacity: 1;
+ transform: none;
+ transition-delay: 0.1s;
+}
+
+.step {
+ margin-right: 0.75rem;
+ font-family: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
+ font-size: 0.75rem;
+ letter-spacing: 0.06em;
+ color: #7dd3fc;
+ white-space: nowrap;
+}
+
+.captionTitle {
+ margin-right: 0.3rem;
+ font-weight: 600;
+ color: #fff;
+}
+
+.progress {
+ position: relative;
+ grid-column: 1 / -1;
+ height: 3px;
+ overflow: hidden;
+ border-radius: 3px;
+ background: rgba(148, 163, 184, 0.22);
+}
+
+.progressFill {
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(90deg, #6ee7b7, #7dd3fc);
+ transform: scaleX(var(--film-progress, 0));
+ transform-origin: left center;
+}
+
+/* Gaps between the eight shots. */
+.tick {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 3px;
+ margin-left: -1.5px;
+ background: #05070a;
+}
+
+/* The film in words: static mode, reduced motion and no JavaScript. */
+.steps {
+ display: grid;
+ gap: 1.25rem;
+ max-width: 80rem;
+ margin: 0 auto;
+ padding: 3rem 1.5rem 1rem;
+ list-style: none;
+}
+
+.stepItem {
+ border: 1px solid #262626;
+ border-radius: 1rem;
+ background: rgba(23, 23, 23, 0.6);
+ padding: 1.5rem;
+}
+
+.facts {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ margin-top: 1.25rem;
+}
+
+.fact {
+ border: 1px solid rgba(125, 211, 252, 0.28);
+ border-radius: 999px;
+ background: rgba(8, 20, 30, 0.72);
+ padding: 0.3rem 0.75rem;
+ font-family: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
+ font-size: 0.75rem;
+ line-height: 1.35;
+ color: #bae6fd;
+}
+
+@media (min-width: 768px) {
+ .steps {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
+
+/* Narrow screens: the film plays on top, its narration sits right under it,
+ and the copy follows at the bottom. */
+@media (max-width: 1023px) {
+ .poster {
+ left: var(--film-focus-left, 1.25rem);
+ width: var(--film-focus-width, calc(100% - 2.5rem));
+ height: var(--film-focus-height, 30%);
+ }
+
+ .root[data-layout="prompt"] .poster {
+ height: var(--film-focus-height, calc(38% - 6rem));
+ }
+
+ .scrim {
+ background: linear-gradient(
+ 0deg,
+ rgba(5, 7, 10, 0.97) 0%,
+ rgba(5, 7, 10, 0.92) 40%,
+ rgba(5, 7, 10, 0.55) 56%,
+ rgba(5, 7, 10, 0) 70%
+ );
+ }
+
+ .frame {
+ padding: 0 1.25rem;
+ }
+
+ .topbar {
+ height: 2.15rem;
+ }
+
+ .player {
+ order: 2;
+ margin-top: auto;
+ padding: 0.5rem 0 0.25rem;
+ }
+
+ .copy {
+ order: 3;
+ flex: 0 0 auto;
+ max-width: 40rem;
+ padding: 0.9rem 0 1.25rem;
+ }
+
+ .buttons {
+ margin-top: 1.1rem;
+ }
+
+ .caption {
+ font-size: 0.8125rem;
+ line-height: 1.4;
+ }
+
+ .root[data-layout="prompt"] .copy {
+ flex: 0 0 62%;
+ max-width: none;
+ padding: 0.5rem 0 0.75rem;
+ }
+
+ .root[data-layout="prompt"] .player {
+ flex-shrink: 0;
+ }
+
+ .compactSteps {
+ inset: 0.5rem 1.25rem auto;
+ width: auto;
+ height: 28%;
+ }
+}
+
+@media (max-height: 559px) and (min-width: 640px) {
+ .root[data-layout="prompt"] .copy {
+ order: initial;
+ flex: 1;
+ max-width: 52%;
+ padding: 0.25rem 0 0.5rem;
+ }
+
+ .root[data-layout="prompt"] .player {
+ order: initial;
+ padding-bottom: 0.5rem;
+ }
+
+ .root[data-layout="prompt"] .scrim {
+ background: linear-gradient(90deg, #05070a 0%, rgba(5, 7, 10, 0.85) 45%, transparent 65%);
+ }
+
+ .root[data-layout="prompt"][data-mode="static"] .player {
+ display: none;
+ }
+
+ .compactSteps {
+ inset: 0.5rem 1.25rem 0.5rem auto;
+ width: 43%;
+ height: auto;
+ }
+}
+
+@media (max-width: 639px), (max-height: 450px) {
+ :global(body):has(.root[data-layout="prompt"]) > :global(footer) > :global(div) {
+ padding: 0.5rem 1rem;
+ }
+
+ :global(body):has(.root[data-layout="prompt"]) > :global(footer) :global(p) {
+ font-size: 0.6875rem;
+ line-height: 1.4;
+ }
+}
+
+/* Phones: every line of copy costs the film room, so the buttons share a row. */
+@media (max-width: 639px) {
+ .root[data-layout="prompt"] .poster {
+ height: var(--film-focus-height, calc(30% - 7rem));
+ }
+
+ .root[data-layout="prompt"] .copy {
+ flex-basis: 70%;
+ }
+
+ .compactSteps {
+ height: calc(30% - 4.5rem);
+ }
+
+ .root[data-mode="static"] .compactSteps {
+ height: 28%;
+ }
+
+ .topbar {
+ height: 1.93125rem;
+ }
+
+ .buttons {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.5rem;
+ }
+
+ .toggle {
+ width: 2rem;
+ height: 2rem;
+ }
+
+ .step {
+ margin-right: 0.5rem;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .poster,
+ .scene,
+ .caption {
+ transition-duration: 0.01s !important;
+ }
+
+ .caption {
+ transform: none;
+ }
+}
diff --git a/app/components/campaign/CampaignFilm.tsx b/app/components/campaign/CampaignFilm.tsx
new file mode 100644
index 0000000..5253ce8
--- /dev/null
+++ b/app/components/campaign/CampaignFilm.tsx
@@ -0,0 +1,353 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
+import Image from "next/image";
+import styles from "./CampaignFilm.module.css";
+import { narration } from "./filmContent";
+import type { FilmController } from "./scene";
+import { DURATION, SHOTS, STILL_AT, shotIndexAt } from "./scene/film";
+import { withBasePath } from "../../services/sitePath";
+
+type Mode = "poster" | "film" | "static";
+
+interface CampaignLink {
+ label: string;
+ href: string;
+}
+
+/**
+ * Pages may supply copy and links, or a prompt panel in their place.
+ * The film and narration stay the same in either layout.
+ */
+export interface CampaignFilmProps {
+ tagline: string;
+ heading: string;
+ description: string;
+ primary: CampaignLink;
+ secondary: CampaignLink;
+ children?: ReactNode;
+}
+
+/** Below this viewport height the stage cannot hold both the copy and the film. */
+const MIN_FILM_HEIGHT = 560;
+
+function debugWindow() {
+ return window as unknown as { __campaignFilm?: FilmController };
+}
+
+function supportsWebGL2() {
+ try {
+ const canvas = document.createElement("canvas");
+ const gl = canvas.getContext("webgl2");
+ if (!gl) return false;
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** The film in words: what each shot shows, for when it cannot or should not play. */
+function FilmSteps({ className }: { className: string }) {
+ return (
+
+ {narration.map((caption, index) => (
+
+
+ {String(index + 1).padStart(2, "0")}
+
+
{caption.title}
+
{caption.text}
+
+ {caption.facts.map((fact) => (
+
+ {fact}
+
+ ))}
+
+
+ ))}
+
+ );
+}
+
+export default function CampaignFilm({ tagline, heading, description, primary, secondary, children }: CampaignFilmProps) {
+ const promptLayout = Boolean(children);
+ const [mode, setMode] = useState("poster");
+ const [ready, setReady] = useState(false);
+ const [shot, setShot] = useState(shotIndexAt(STILL_AT));
+ const [playing, setPlaying] = useState(false);
+ const [still, setStill] = useState(true);
+ const [hydrated, setHydrated] = useState(false);
+ const loading = mode === "film" && !ready;
+
+ const rootRef = useRef(null);
+ const stageRef = useRef(null);
+ const topbarRef = useRef(null);
+ const copyRef = useRef(null);
+ const playerRef = useRef(null);
+ const sceneRef = useRef(null);
+ const controller = useRef(null);
+ const shotRef = useRef(shotIndexAt(STILL_AT));
+
+ /* Short viewports keep the written story; WebGL is checked only on Play. */
+ useEffect(() => {
+ setHydrated(true);
+ const decide = () => {
+ if (window.innerHeight < MIN_FILM_HEIGHT) {
+ setMode("static");
+ setPlaying(false);
+ setStill(true);
+ }
+ };
+ decide();
+ // A stage that no longer fits (a phone turned sideways) falls back for
+ // good; switching back and forth would move the reader around.
+ window.addEventListener("resize", decide);
+ return () => window.removeEventListener("resize", decide);
+ }, []);
+
+ /**
+ * Tells the scene which part of the stage is free of copy, so the camera can
+ * frame its subject there: beside the copy on wide screens, above it on
+ * narrow ones.
+ */
+ const reportFocus = useCallback(() => {
+ const stage = stageRef.current;
+ const topbar = topbarRef.current;
+ const copy = copyRef.current;
+ const player = playerRef.current;
+ const root = rootRef.current;
+ if (!stage || !topbar || !copy || !player || !root) return;
+ const box = stage.getBoundingClientRect();
+ const top = topbar.getBoundingClientRect().bottom - box.top + 12;
+ const bottom = player.getBoundingClientRect().top - box.top - 8;
+ const left = copy.getBoundingClientRect().right - box.left - 10;
+ const focus = box.width >= 1024
+ ? { x: left, y: top, width: box.width - left - 24, height: bottom - top }
+ : {
+ x: 8,
+ y: top,
+ width: box.width - 16,
+ height: Math.max(bottom - top, promptLayout ? 1 : box.height * 0.3),
+ };
+ const posterWidth = Math.max(1, Math.min(focus.width, focus.height * 640 / 569));
+ const posterHeight = posterWidth * 569 / 640;
+ root.style.setProperty("--film-focus-left", `${focus.x + (focus.width - posterWidth) / 2}px`);
+ root.style.setProperty("--film-focus-top", `${focus.y + (focus.height - posterHeight) / 2}px`);
+ root.style.setProperty("--film-focus-width", `${posterWidth}px`);
+ root.style.setProperty("--film-focus-height", `${posterHeight}px`);
+ controller.current?.setFocus(focus);
+ }, [promptLayout]);
+
+ /* The stage fills what is left of the first viewport under the site's header. */
+ useEffect(() => {
+ if (mode === "static") return;
+ const root = rootRef.current;
+ if (!root) return;
+ const measure = () => {
+ const top = Math.max(0, Math.round(root.getBoundingClientRect().top + window.scrollY));
+ root.style.setProperty("--film-top", `${top}px`);
+ reportFocus();
+ };
+ window.addEventListener("resize", measure);
+ const observer = new ResizeObserver(measure);
+ observer.observe(root);
+ if (copyRef.current) observer.observe(copyRef.current);
+ if (playerRef.current) observer.observe(playerRef.current);
+ measure();
+ return () => {
+ window.removeEventListener("resize", measure);
+ observer.disconnect();
+ };
+ }, [mode, reportFocus]);
+
+ /* Entering film mode requires an explicit Play click. */
+ useEffect(() => {
+ if (mode !== "film") return;
+ const host = sceneRef.current;
+ const root = rootRef.current;
+ if (!host || !root) return;
+ let cancelled = false;
+ let created: FilmController | null = null;
+
+ const onTime = (t: number) => {
+ // The progress line moves every frame, so it bypasses React.
+ root.style.setProperty("--film-progress", (t / DURATION).toFixed(4));
+ const index = shotIndexAt(t);
+ if (index !== shotRef.current) {
+ shotRef.current = index;
+ setShot(index);
+ }
+ };
+
+ const build = async () => {
+ try {
+ // Canvas textures bake text in, so the page font has to be loaded.
+ await Promise.race([document.fonts.ready, new Promise((resolve) => setTimeout(resolve, 1500))]);
+ if (cancelled) return;
+ const { createFilm } = await import("./scene");
+ if (cancelled) return;
+ created = createFilm(host, {
+ startPaused: true,
+ onReady: () => setReady(true),
+ onTime,
+ });
+ controller.current = created;
+ reportFocus();
+ created.seek(0);
+ created.setPlaying(true);
+ // Development builds expose the controller for visual checks.
+ if (process.env.NODE_ENV !== "production") debugWindow().__campaignFilm = created;
+ } catch (error) {
+ console.warn("Campaign film unavailable; showing the static page instead.", error);
+ if (!cancelled) {
+ setPlaying(false);
+ setStill(true);
+ setMode("static");
+ }
+ }
+ };
+ void build();
+
+ const pointer = (event: PointerEvent) => {
+ if (event.pointerType !== "mouse") return;
+ controller.current?.setPointer(
+ (event.clientX / window.innerWidth) * 2 - 1,
+ (event.clientY / window.innerHeight) * 2 - 1,
+ );
+ };
+ window.addEventListener("pointermove", pointer, { passive: true });
+
+ return () => {
+ cancelled = true;
+ window.removeEventListener("pointermove", pointer);
+ created?.dispose();
+ controller.current = null;
+ if (process.env.NODE_ENV !== "production") delete debugWindow().__campaignFilm;
+ setReady(false);
+ };
+ }, [mode, reportFocus]);
+
+ const toggle = () => {
+ if (mode === "poster") {
+ if (!supportsWebGL2()) {
+ setMode("static");
+ return;
+ }
+ setPlaying(true);
+ setStill(false);
+ setMode("film");
+ return;
+ }
+ const next = !playing;
+ if (next && still) {
+ // Leaving the still frame: start the film from its first shot.
+ controller.current?.seek(0);
+ setStill(false);
+ }
+ controller.current?.setPlaying(next);
+ setPlaying(next);
+ };
+
+ return (
+
+
+
+
+
+
+
+
+
+
+ {/* Clear space under the site header; the film is framed below it. */}
+
+
+
+
+ {/* The same story in words: on the page when the film is not playing by
+ itself, and for screen readers when it is. */}
+ {(mode === "poster" || mode === "film") && (!still || children) && }
+ {!children && hydrated && (mode === "static" || still) && }
+
+
+ );
+}
diff --git a/app/components/campaign/filmContent.ts b/app/components/campaign/filmContent.ts
new file mode 100644
index 0000000..659403a
--- /dev/null
+++ b/app/components/campaign/filmContent.ts
@@ -0,0 +1,77 @@
+// Narration for the film on the sample campaign pages. The film is not part of
+// the experiment: both variants play the same one, with the same words, so a
+// visitor of either page watches exactly the same thing. One tap in a shopping
+// app is followed from the phone to a PostgreSQL heap page and back. What the
+// variants compare is the copy around the film (headline, description, button
+// labels and the cards below), which each page supplies itself.
+//
+// Every technical statement here is taken from the DocumentDB source
+// (github.com/documentdb/documentdb): table and index naming from
+// pg_documentdb/src/commands, the gateway's port, protocol and SQL from
+// pg_documentdb_gw, and the extension dependencies from documentdb.control.
+// TrailyShop and Traily Run, the shop and the shoe in the film, are invented.
+
+import type { ShotKey } from "./scene/film";
+
+export interface FilmCaption {
+ /** Part of the film this line belongs to. */
+ shot: ShotKey;
+ /** A few words, set in bold. */
+ title: string;
+ /** One sentence of narration. */
+ text: string;
+ /** Exact identifiers for the written version, set in monospace. */
+ facts: string[];
+}
+
+/** One line per shot, in the order of SHOTS. */
+export const narration: FilmCaption[] = [
+ {
+ shot: "tap",
+ title: "One tap in your app.",
+ text: "A shopper buys a pair of Traily Run. The app sends one update to DocumentDB.",
+ facts: ["DocumentDB API", "updateOne", "$inc"],
+ },
+ {
+ shot: "doc",
+ title: "The product is one document.",
+ text: "Tags, stock, a location and an embedding live together and travel as BSON.",
+ facts: ["BSON", "arrays and nested fields", "up to 16 MB"],
+ },
+ {
+ shot: "wire",
+ title: "On its way to your server.",
+ text: "The bytes leave the phone for a machine you run. One container holds everything below.",
+ facts: ["Docker", "Linux packages", "Kubernetes operator"],
+ },
+ {
+ shot: "gateway",
+ title: "The DocumentDB gateway answers.",
+ text: "Port 10260 accepts the wire protocol and turns the command into a PostgreSQL call.",
+ facts: ["OP_MSG", "SCRAM-SHA-256 over TLS", "documentdb_api.update_txn_proc"],
+ },
+ {
+ shot: "btree",
+ title: "A B-tree finds the row.",
+ text: "_id is the table's primary key, so the lookup walks a B-tree down to one 8 kB heap page.",
+ facts: ["collection_pk_", "documentdb_data.documents_", "one row per document"],
+ },
+ {
+ shot: "mvcc",
+ title: "The update writes a new version.",
+ text: "The old row stays for reads already running, the change is logged, and vacuum reclaims it.",
+ facts: ["xmin / xmax", "write-ahead log", "READ COMMITTED"],
+ },
+ {
+ shot: "indexes",
+ title: "More indexes, same rows.",
+ text: "RUM answers tag queries, pgvector finds similar gear, PostGIS finds the nearest store.",
+ facts: ["RUM", "vector-hnsw", "2dsphere"],
+ },
+ {
+ shot: "stack",
+ title: "Answered. All of it yours.",
+ text: "DocumentDB on top, PostgreSQL underneath, MIT licensed, running where you choose.",
+ facts: ["MIT license", "PostgreSQL 15 to 18", "Linux Foundation"],
+ },
+];
diff --git a/app/components/campaign/promptContent.ts b/app/components/campaign/promptContent.ts
new file mode 100644
index 0000000..0311b93
--- /dev/null
+++ b/app/components/campaign/promptContent.ts
@@ -0,0 +1,53 @@
+export const galleryRevision = "d69f00ff9e86a7b0b9791c5eb32d47bd20e481d0";
+export const agentKitUrl = "https://github.com/documentdb/agent-kit";
+export const agentKitRevision = "d10f02a9fcd1694b390658d9098a6945948eff97";
+export const SAMPLES_GALLERY_URL = "https://github.com/documentdb/documentdb-samples-gallery";
+export const documentDbImage = "ghcr.io/documentdb/documentdb/documentdb-local@sha256:1d40546ccf53a0229f98a0848b7c3d6d74dc35a9fa535a1d1c8f70e3bed10d23";
+
+const setup = `Clone ${agentKitUrl} into a new, separate directory and check out commit ${agentKitRevision}, using separate shell commands for clone and checkout. Read its AGENTS.md and use the build-app, data-integrity, and verify-app skills under skills/ as each stage becomes relevant. No plugin or global installation is needed; do not change global agent settings.
+
+Follow the gallery sample's own setup below, not the Agent-Kit task starter or its full quickstart. Apply the skills to the sample's existing user flows, schema, and query shapes; do not replace the sample or add unrelated features to satisfy a generic CRUD checklist. Keep integrity checks read-only, scope verification writes to your new sample-only database, and report unsupported or unverified checks honestly.
+
+Clone ${SAMPLES_GALLERY_URL} into a new workspace and check out commit ${galleryRevision}, using separate shell commands for clone and checkout. Inspect the sample README, dependency manifests, and scripts before running them. If cloning, a prerequisite, or a permission is blocked, stop and ask; do not reconstruct or replace sample files.
+
+Use only a new, isolated local DocumentDB OSS container from ${documentDbImage} and synthetic data. Do not reuse, reseed, stop, or delete an existing database/container. Check for port conflicts and use free, loopback-only ports. Both samples listen on all interfaces by default: make a minimal local-only change to the HTTP app.listen call to bind 127.0.0.1 before starting, and explain that change. Generate random local credentials and keep them in an ignored private environment file with owner-only permissions; never print them. Use authSource=admin, tls=true, directConnection=true, and retryWrites=false. Self-signed certificate exceptions are for this local container only. Keep package-registry TLS verification enabled and use the user's approved registry. Ask before any cloud deployment, paid API, global installation, or browser/model download.`;
+
+export const samplePrompts = [
+ {
+ id: "retail",
+ label: "Retail storefront",
+ eyebrow: "FULL-STACK APPLICATION",
+ title: "From product data to a working storefront.",
+ description: "Seed a catalog, browse the shop, and test the APIs behind it. No model or cloud key needed.",
+ stack: "Node.js 22+ · Docker · Express",
+ folder: "retail-product-store-js",
+ expected: "8 products · search + filters · product details",
+ prompt: `${setup}
+
+Run retail-product-store-js end to end. Prerequisites: Git, Node.js 22+, and Docker.
+1. In that sample directory, use npm ci with its lockfile. Set DOCUMENTDB_URI to the isolated container, DB_NAME to a new sample-only database, and PORT to a free port in a private .env.
+2. Run npm run seed ONLY against that new database, then npm start. Wait for the database connection and HTTP readiness; do not declare success merely because the process started.
+3. Verify GET /api/products returns 8 products. Verify category=Electronics returns 3 products; price_asc sorts correctly; search=headphones returns one product; /api/products/ returns its details; and /api/categories includes All.
+4. Open the storefront in a browser, check that products render, and try search, category filtering, and a product detail. If no browser is available, ask before installing one and report browser verification as blocked, not passed.
+5. Give me the working local URL, the actual verification results, and exact commands to stop only the resources you created without deleting data. Leave the app running for me. If anything fails, report it explicitly rather than substituting MongoDB or mocked data.`,
+ },
+ {
+ id: "memory",
+ label: "AI memory",
+ eyebrow: "MCP + DOCUMENTDB",
+ title: "Give your AI a memory that lasts.",
+ description: "Run an authenticated MCP server. Save, retrieve, and remove synthetic memories backed by real documents.",
+ stack: "Node.js 22+ · Docker · optional Ollama",
+ folder: "personal-memory-mcp-ts",
+ expected: "Authenticated MCP · save + retrieve · soft delete",
+ prompt: `${setup}
+
+Run personal-memory-mcp-ts end to end. Prerequisites: Git, Node.js 22+, and Docker.
+1. Work in personal-memory-mcp-ts/mcp-server. Run npm ci and npm run build. This directory has no .env.example; read the parent template and create an ignored private .env with DOCUMENTDB_URI, a new DB_NAME, a free MCP_SERVER_PORT, and a random AUTH_TOKEN.
+2. Start with node --env-file=.env dist/index.js. Do not assume npm start loads .env: this sample does not import dotenv. Leave authentication enabled and keep the token out of logs/config snippets you show me.
+3. GET /health must report db=connected. An unauthenticated /mcp request must return 401.
+4. Use the installed MCP SDK Client and StreamableHTTPClientTransport, with the bearer header, to initialize, list tools, save a synthetic memory such as "The demo robot catalogs blue bicycles", retrieve it, get_profile, and delete_memory. Verify the record is persisted and deletion sets active=false. Do not store real personal information.
+5. Optional semantic mode: if Ollama is installed or I approve a separate local model container/download, pull nomic-embed-text, set OLLAMA_BASE_URL and EMBEDDING_DIMENSIONS=768, restart only this sample, and verify stored embeddings have 768 values and semantic retrieval works. Without Ollama, explicitly report text/tag/regex mode, not semantic success.
+6. Give me the local health URL, actual MCP results, and client configuration with a token placeholder plus the exact private file where I can obtain my token. Leave the app running and give stop commands limited to your own resources. Report failures explicitly; do not substitute a mocked service or MongoDB.`,
+ },
+] as const;
diff --git a/app/components/campaign/scene/film.ts b/app/components/campaign/scene/film.ts
new file mode 100644
index 0000000..7f96d50
--- /dev/null
+++ b/app/components/campaign/scene/film.ts
@@ -0,0 +1,104 @@
+// The film's clock. One tap on a phone is followed down to a PostgreSQL heap
+// page and back in a single continuous shot; this file names the eight parts of
+// that shot and the moments inside them that the scene is choreographed to.
+//
+// It must stay free of three.js imports: the page content (a server component)
+// and the tests read it without loading the renderer.
+
+import { envelope } from "./util";
+
+export type ShotKey = "tap" | "doc" | "wire" | "gateway" | "btree" | "mvcc" | "indexes" | "stack";
+
+export interface Shot {
+ key: ShotKey;
+ /** Seconds from the start of the film. */
+ start: number;
+ end: number;
+}
+
+/** Length of one loop, in seconds. */
+export const DURATION = 36;
+
+// Caption boundaries. Each one falls a little before the camera settles, so
+// the words arrive just ahead of the picture they describe.
+export const SHOTS: readonly Shot[] = [
+ { key: "tap", start: 0, end: 2.9 },
+ { key: "doc", start: 2.9, end: 6.9 },
+ { key: "wire", start: 6.9, end: 9.6 },
+ { key: "gateway", start: 9.6, end: 12.6 },
+ { key: "btree", start: 12.6, end: 16.2 },
+ { key: "mvcc", start: 16.2, end: 22.6 },
+ { key: "indexes", start: 22.6, end: 28.9 },
+ { key: "stack", start: 28.9, end: DURATION },
+];
+
+/** Index into SHOTS for a point in the film. */
+export function shotIndexAt(t: number) {
+ // Wrap only when needed: a second modulo would nudge exact boundaries down.
+ const time = t >= 0 && t < DURATION ? t : ((t % DURATION) + DURATION) % DURATION;
+ for (let i = SHOTS.length - 1; i > 0; i--) {
+ if (time >= SHOTS[i].start) return i;
+ }
+ return 0;
+}
+
+// Named moments, in seconds. Everything that moves in the scene is a function
+// of film time and these constants, so any frame can be drawn on its own.
+export const CUE = {
+ /* 1 · the tap */
+ finger: 1.1,
+ tap: 2.0,
+ /* 2 · inside the app: card, document, bytes */
+ docOut: 2.55,
+ docOpen: 3.45,
+ fieldTags: 3.75,
+ fieldGeo: 4.05,
+ fieldEmbedding: 4.35,
+ fieldStock: 4.75,
+ bson: 5.4,
+ pack: 6.25,
+ depart: 6.9,
+ /* 3 · to the backend: down to the hall, along the aisle, into one rack */
+ phoneEdge: 7.3,
+ mouth: 8.35,
+ roof: 9.05,
+ /* 4 · the gateway */
+ aboveRing: 9.75,
+ dive: 10.7,
+ cross: 11.0,
+ belowRing: 11.4,
+ leaveRing: 12.3,
+ /* 5 · finding the row */
+ root: 13.5,
+ inner: 14.1,
+ leaf: 14.7,
+ row: 15.3,
+ linePointer: 16.1,
+ tuple: 16.6,
+ /* 6 · a new version */
+ write: 17.1,
+ stamp: 17.8,
+ wal: 18.4,
+ walFlush: 19.1,
+ nextRead: 19.6,
+ vacuum: 20.5,
+ vacuumEnd: 21.7,
+ /* 7 · the way back: other indexes over the same rows */
+ tagQuery: 23.3,
+ vectorQuery: 26.0,
+ nearQuery: 27.0,
+ /* 8 · the whole stack, and the reply */
+ reply: 30.5,
+ replyGateway: 31.3,
+ replyRoof: 31.75,
+ replyMouth: 32.15,
+ replyPhone: 32.7,
+} as const;
+
+/** The frame shown when motion is reduced: the whole stack. */
+export const STILL_AT = 31.2;
+
+/** 0..1 while the camera stands back and shows every layer at once. */
+export function finaleAt(t: number) {
+ return envelope(t, 28.9, 30.2, 32.2, 33.3);
+}
diff --git a/app/components/campaign/scene/index.ts b/app/components/campaign/scene/index.ts
new file mode 100644
index 0000000..e9dcc39
--- /dev/null
+++ b/app/components/campaign/scene/index.ts
@@ -0,0 +1,345 @@
+// Entry point of the WebGL film. Loaded on demand by CampaignFilm, so three.js
+// never weighs on the first paint of the landing page.
+
+import {
+ Color,
+ FogExp2,
+ HalfFloatType,
+ MathUtils,
+ Mesh,
+ PlaneGeometry,
+ Scene,
+ Vector2,
+ WebGLRenderTarget,
+ WebGLRenderer,
+ type Material,
+ type Object3D,
+} from "three";
+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
+import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass.js";
+import { DURATION, STILL_AT, finaleAt } from "./film";
+import { backdropMaterial, shared } from "./materials";
+import { hex } from "./palette";
+import { Rig, type FocusRect } from "./rig";
+import { createShell } from "./shell";
+import { Signal } from "./signal";
+import { createDocStation } from "./stations/docStation";
+import { createGatewayStation } from "./stations/gatewayStation";
+import { createHallStation } from "./stations/hallStation";
+import { createHeapStation } from "./stations/heapStation";
+import { createIndexStation } from "./stations/indexStation";
+import { createPhoneStation } from "./stations/phoneStation";
+import { createVectorStation } from "./stations/vectorStation";
+import { TextureKit } from "./textures";
+import type { Frame, Kit, Station } from "./world";
+
+export interface FilmOptions {
+ /** Start paused on a still of the whole stack instead of playing. */
+ startPaused: boolean;
+ /** Called once the first frame is on screen. */
+ onReady(): void;
+ /** Called with the film time, in seconds, of every frame drawn. */
+ onTime(t: number): void;
+}
+
+export interface FilmController {
+ /** Plays or pauses the film. Pausing stops the frame loop altogether. */
+ setPlaying(playing: boolean): void;
+ /** Jumps to a point in the film, in seconds. */
+ seek(t: number): void;
+ /** Pointer position relative to the viewport centre, -1..1 on each axis. */
+ setPointer(x: number, y: number): void;
+ /** Area of the canvas not covered by copy, in CSS pixels. */
+ setFocus(rect: FocusRect): void;
+ /**
+ * Pauses, jumps to a film time (and optionally a point in the ambient
+ * clock) and draws one frame. For automated visual checks, which cannot
+ * wait on a frame loop that browsers throttle in background tabs.
+ */
+ drawAt(t: number, clock?: number): void;
+ dispose(): void;
+}
+
+/**
+ * Builds the scene inside `host`. The canvas is created here rather than passed
+ * in: disposing a renderer loses its WebGL context for good, so every scene
+ * instance needs a canvas of its own.
+ */
+export function createFilm(host: HTMLElement, options: FilmOptions): FilmController {
+ const canvas = document.createElement("canvas");
+ canvas.setAttribute("aria-hidden", "true");
+ host.appendChild(canvas);
+ try {
+ return build(canvas, options);
+ } catch (error) {
+ canvas.remove();
+ throw error;
+ }
+}
+
+function build(canvas: HTMLCanvasElement, options: FilmOptions): FilmController {
+ const coarse = window.matchMedia("(pointer: coarse)").matches;
+ const low =
+ coarse || Math.min(window.innerWidth, window.innerHeight) < 640 || (navigator.hardwareConcurrency ?? 8) <= 4;
+
+ const renderer = new WebGLRenderer({
+ canvas,
+ antialias: low,
+ alpha: false,
+ stencil: false,
+ powerPreference: "high-performance",
+ });
+ renderer.setClearColor(hex.bg, 1);
+ // Rendered pixels are capped so a large 2x display does not quadruple the
+ // fill cost: sharp enough for hairlines, bounded for integrated GPUs.
+ const pixelBudget = low ? 1.5e6 : 2.8e6;
+ let pixelCap = Math.min(window.devicePixelRatio || 1, low ? 1.5 : 2);
+ let pixelRatio = pixelCap;
+
+ const scene = new Scene();
+ scene.background = new Color(hex.bg);
+ const fog = new FogExp2(0x000000, 0.02);
+ scene.fog = fog;
+
+ const backdrop = backdropMaterial();
+ const backdropMesh = new Mesh(new PlaneGeometry(2, 2), backdrop);
+ backdropMesh.frustumCulled = false;
+ backdropMesh.renderOrder = -1000;
+ scene.add(backdropMesh);
+
+ const signal = new Signal();
+ const kit: Kit = {
+ tex: new TextureKit(
+ Math.min(8, renderer.capabilities.getMaxAnisotropy()),
+ window.getComputedStyle(document.body).fontFamily || "system-ui, sans-serif",
+ low ? 0.6 : 1,
+ ),
+ signal,
+ low,
+ compact: window.innerWidth < 1024,
+ };
+
+ const rig = new Rig(signal);
+ const shell = createShell(kit);
+ const stations: Station[] = [
+ createPhoneStation(kit),
+ createDocStation(kit),
+ createHallStation(kit),
+ createGatewayStation(kit),
+ createVectorStation(kit),
+ createIndexStation(kit),
+ createHeapStation(kit),
+ shell,
+ ];
+ for (const station of stations) scene.add(station.group);
+
+ /* Post-processing: bloom on capable devices, plain rendering otherwise. */
+ let composer: EffectComposer | null = null;
+ let bloom: UnrealBloomPass | null = null;
+ if (!low) {
+ const target = new WebGLRenderTarget(4, 4, { type: HalfFloatType, samples: 4 });
+ composer = new EffectComposer(renderer, target);
+ composer.addPass(new RenderPass(scene, rig.camera));
+ bloom = new UnrealBloomPass(new Vector2(4, 4), 0.44, 0.62, 0.9);
+ composer.addPass(bloom);
+ composer.addPass(new OutputPass());
+ }
+
+ let width = 0;
+ let height = 0;
+ let focused = false;
+ const resize = () => {
+ const w = canvas.clientWidth;
+ const h = canvas.clientHeight;
+ if (w === 0 || h === 0 || (w === width && h === height)) return false;
+ width = w;
+ height = h;
+ pixelRatio = Math.max(1, Math.min(pixelCap, Math.sqrt(pixelBudget / (w * h))));
+ renderer.setPixelRatio(pixelRatio);
+ renderer.setSize(w, h, false);
+ if (composer) {
+ composer.setPixelRatio(pixelRatio);
+ composer.setSize(w, h);
+ }
+ rig.resize(w, h);
+ backdrop.uniforms.uAspect.value = w / h;
+ if (!focused) backdrop.uniforms.uGlowPos.value.set(w >= 1024 ? 0.7 : 0.5, w >= 1024 ? 0.48 : 0.64);
+ return true;
+ };
+
+ /* The film's state: where it is, whether it runs, how often it has looped. */
+ let t = options.startPaused ? STILL_AT : 0;
+ let playing = !options.startPaused;
+ let loop = 0;
+ let clock = options.startPaused ? 4.6 : 0;
+ let ready = false;
+ const frame: Frame = { t: 0, time: 0, dt: 0, loop: 0, finale: 0 };
+
+ const draw = (dt: number) => {
+ frame.t = t;
+ frame.time = clock;
+ frame.dt = dt;
+ frame.loop = loop;
+ frame.finale = finaleAt(t);
+ rig.update(t, clock, dt, frame.finale, !playing);
+ shared.time.value = clock;
+ shared.fogDensity.value = rig.fog;
+ fog.density = rig.fog;
+ shared.pointScale.value =
+ (height * pixelRatio) / (2 * Math.tan(MathUtils.degToRad(rig.camera.fov) / 2));
+ for (const station of stations) station.update(frame);
+ backdrop.uniforms.uGlow.value.copy(shell.glow);
+ if (composer) composer.render(dt);
+ else renderer.render(scene, rig.camera);
+ options.onTime(t);
+ if (!ready) {
+ ready = true;
+ options.onReady();
+ }
+ };
+
+ /* Frame loop: runs only while playing, on screen and in a visible tab. */
+ let raf = 0;
+ let last = 0;
+ let onScreen = true;
+ let slowFrames = 0;
+ const tick = (now: number) => {
+ raf = requestAnimationFrame(tick);
+ const dt = Math.min(0.05, Math.max(0, (now - last) / 1000));
+ last = now;
+ clock += dt;
+ t += dt;
+ if (t >= DURATION) {
+ t -= DURATION;
+ loop += 1;
+ }
+ resize();
+ draw(dt);
+
+ // Shed work if the device cannot keep up: bloom first, then resolution.
+ slowFrames = dt > 0.03 ? slowFrames + 1 : Math.max(0, slowFrames - 2);
+ if (slowFrames > 70) {
+ slowFrames = 0;
+ if (composer) {
+ composer.dispose();
+ composer = null;
+ bloom = null;
+ } else if (pixelCap > 1) {
+ pixelCap = Math.max(1, pixelRatio - 0.4);
+ width = 0;
+ }
+ }
+ };
+ const start = () => {
+ if (!playing || raf || !onScreen || document.hidden) return;
+ last = performance.now();
+ raf = requestAnimationFrame(tick);
+ };
+ const stop = () => {
+ if (raf) cancelAnimationFrame(raf);
+ raf = 0;
+ };
+ // Paused: no loop at all, one frame whenever something changes.
+ const renderOnce = () => {
+ if (playing) return;
+ resize();
+ draw(0);
+ };
+
+ const visibility = () => (document.hidden ? stop() : start());
+ document.addEventListener("visibilitychange", visibility);
+ const observer = new IntersectionObserver(([entry]) => {
+ onScreen = entry.isIntersecting;
+ if (onScreen) start();
+ else stop();
+ });
+ observer.observe(canvas);
+ const resizeObserver = new ResizeObserver(() => {
+ if (!playing) {
+ width = 0;
+ renderOnce();
+ }
+ });
+ resizeObserver.observe(canvas);
+
+ const lost = (event: Event) => {
+ event.preventDefault();
+ stop();
+ };
+ const restored = () => {
+ width = 0;
+ if (playing) start();
+ else renderOnce();
+ };
+ canvas.addEventListener("webglcontextlost", lost);
+ canvas.addEventListener("webglcontextrestored", restored);
+
+ // Upload every texture up front so a scene does not hitch the first time
+ // the camera reaches it.
+ for (const texture of kit.tex.all) renderer.initTexture(texture);
+ resize();
+ if (playing) start();
+ else renderOnce();
+
+ return {
+ setPlaying(value: boolean) {
+ if (value === playing) return;
+ playing = value;
+ if (playing) start();
+ else {
+ stop();
+ renderOnce();
+ }
+ },
+ seek(value: number) {
+ t = MathUtils.clamp(value, 0, DURATION - 1e-3);
+ renderOnce();
+ },
+ setPointer(x: number, y: number) {
+ rig.setPointer(x, y);
+ },
+ drawAt(value: number, at?: number) {
+ playing = false;
+ stop();
+ t = MathUtils.clamp(value, 0, DURATION);
+ loop = 0;
+ if (at !== undefined) clock = at;
+ resize();
+ draw(0);
+ },
+ setFocus(rect: FocusRect) {
+ focused = true;
+ rig.setFocus(rect);
+ if (width > 0 && height > 0) {
+ backdrop.uniforms.uGlowPos.value.set(
+ (rect.x + rect.width / 2) / width,
+ 1 - (rect.y + rect.height / 2) / height,
+ );
+ }
+ renderOnce();
+ },
+ dispose() {
+ stop();
+ document.removeEventListener("visibilitychange", visibility);
+ observer.disconnect();
+ resizeObserver.disconnect();
+ canvas.removeEventListener("webglcontextlost", lost);
+ canvas.removeEventListener("webglcontextrestored", restored);
+ scene.traverse((object: Object3D) => {
+ const mesh = object as Mesh;
+ mesh.geometry?.dispose();
+ const material = mesh.material as Material | Material[] | undefined;
+ if (Array.isArray(material)) material.forEach((m) => m.dispose());
+ else material?.dispose();
+ });
+ kit.tex.dispose();
+ composer?.dispose();
+ bloom?.dispose();
+ renderer.dispose();
+ renderer.forceContextLoss();
+ canvas.remove();
+ },
+ };
+}
diff --git a/app/components/campaign/scene/materials.ts b/app/components/campaign/scene/materials.ts
new file mode 100644
index 0000000..b0f82e8
--- /dev/null
+++ b/app/components/campaign/scene/materials.ts
@@ -0,0 +1,473 @@
+import {
+ AdditiveBlending,
+ Color,
+ DoubleSide,
+ LineBasicMaterial,
+ NormalBlending,
+ ShaderMaterial,
+ SpriteMaterial,
+ Vector2,
+ type IUniform,
+ type Material,
+ type Texture,
+} from "three";
+
+// Uniforms every custom material reads. They are shared by reference, so the
+// render loop updates one object per frame instead of walking the materials.
+export const shared = {
+ fogDensity: { value: 0.03 } as IUniform,
+ time: { value: 0 } as IUniform,
+ // Projects a world-space point size to pixels: bufferHeight / (2 tan(fov/2)).
+ pointScale: { value: 800 } as IUniform,
+};
+
+// Exponential-squared distance fade. It multiplies alpha (or colour, for
+// additive materials) instead of mixing towards a fog colour, so additive
+// geometry fades to nothing rather than to a grey haze.
+const FOG = /* glsl */ `
+uniform float uFogDensity;
+varying float vDepth;
+float fogFactor() {
+ float f = uFogDensity * vDepth;
+ return exp(-f * f);
+}
+`;
+
+const OUTPUT = /* glsl */ `
+#include
+#include
+`;
+
+/* ------------------------------------------------------------------ holo -- */
+// Boxes and planes drawn as glowing outlines with a faint fill. The outline is
+// computed from the face UVs with screen-space derivatives, so it keeps a
+// constant pixel width at any scale or distance (GL lines cannot do that).
+
+const HOLO_VERT = /* glsl */ `
+varying vec2 vUv;
+varying float vDepth;
+varying vec3 vTint;
+void main() {
+ vUv = uv;
+ vec4 p = vec4(position, 1.0);
+ #ifdef USE_INSTANCING
+ p = instanceMatrix * p;
+ #endif
+ vec4 mv = modelViewMatrix * p;
+ vDepth = -mv.z;
+ vTint = vec3(1.0);
+ #ifdef USE_INSTANCING_COLOR
+ vTint = instanceColor;
+ #endif
+ gl_Position = projectionMatrix * mv;
+}
+`;
+
+const HOLO_FRAG = /* glsl */ `
+uniform vec3 uColor;
+uniform float uOpacity;
+uniform float uFill;
+uniform float uLine;
+uniform float uGlow;
+varying vec2 vUv;
+varying vec3 vTint;
+${FOG}
+void main() {
+ vec2 d = min(vUv, 1.0 - vUv);
+ vec2 w = max(fwidth(vUv), vec2(1e-6));
+ float e = min(d.x / w.x, d.y / w.y);
+ float line = 1.0 - smoothstep(uLine, uLine + 1.2, e);
+ float glow = uGlow * exp(-e * 0.085);
+ float a = clamp(uFill + line + glow, 0.0, 1.0);
+ gl_FragColor = vec4(uColor * vTint, a * uOpacity * fogFactor());
+ ${OUTPUT}
+}
+`;
+
+export interface HoloOptions {
+ color: number;
+ opacity?: number;
+ /** Face fill, 0..1. */
+ fill?: number;
+ /** Outline half-width in pixels. */
+ line?: number;
+ /** Soft inner glow hugging the outline. */
+ glow?: number;
+}
+
+export function holoMaterial(o: HoloOptions) {
+ return new ShaderMaterial({
+ uniforms: {
+ uColor: { value: new Color(o.color) },
+ uOpacity: { value: o.opacity ?? 1 },
+ uFill: { value: o.fill ?? 0.04 },
+ uLine: { value: o.line ?? 0.55 },
+ uGlow: { value: o.glow ?? 0.16 },
+ uFogDensity: shared.fogDensity,
+ },
+ vertexShader: HOLO_VERT,
+ fragmentShader: HOLO_FRAG,
+ transparent: true,
+ depthWrite: false,
+ side: DoubleSide,
+ blending: AdditiveBlending,
+ });
+}
+
+/* ----------------------------------------------------------------- panel -- */
+// A textured card with rounded corners and a lit border: app screens, JSON
+// documents, heap tuples.
+
+const PANEL_VERT = /* glsl */ `
+varying vec2 vUv;
+varying float vDepth;
+void main() {
+ vUv = uv;
+ vec4 mv = modelViewMatrix * vec4(position, 1.0);
+ vDepth = -mv.z;
+ gl_Position = projectionMatrix * mv;
+}
+`;
+
+const PANEL_FRAG = /* glsl */ `
+uniform sampler2D uMap;
+uniform vec2 uSize;
+uniform float uRadius;
+uniform vec3 uBorder;
+uniform float uBorderWidth;
+uniform float uOpacity;
+uniform float uBright;
+uniform vec3 uTint;
+varying vec2 vUv;
+${FOG}
+float sdRoundBox(vec2 p, vec2 b, float r) {
+ vec2 q = abs(p) - b + r;
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
+}
+void main() {
+ vec2 p = (vUv - 0.5) * uSize;
+ float sd = sdRoundBox(p, uSize * 0.5, uRadius);
+ float aa = max(fwidth(sd), 1e-6);
+ float inside = 1.0 - smoothstep(-aa, 0.0, sd);
+ if (inside < 0.004) discard;
+ vec4 tex = texture2D(uMap, vUv);
+ float bw = uBorderWidth * aa;
+ float border = (1.0 - smoothstep(bw, bw + aa, abs(sd + bw))) * step(0.001, uBorderWidth);
+ vec3 col = mix(tex.rgb * uTint * uBright, uBorder, border);
+ float alpha = max(tex.a, border) * inside;
+ float fog = fogFactor();
+ gl_FragColor = vec4(col * fog, alpha * uOpacity * fog);
+ ${OUTPUT}
+}
+`;
+
+export interface PanelOptions {
+ map: Texture;
+ size: [number, number];
+ radius?: number;
+ border?: number;
+ /** Border width in pixels; 0 disables it. */
+ borderWidth?: number;
+ opacity?: number;
+ /** Values above 1 push the texture into bloom range, like a lit screen. */
+ bright?: number;
+ tint?: number;
+}
+
+export function panelMaterial(o: PanelOptions) {
+ return new ShaderMaterial({
+ uniforms: {
+ uMap: { value: o.map },
+ uSize: { value: new Vector2(o.size[0], o.size[1]) },
+ uRadius: { value: o.radius ?? 0.06 },
+ uBorder: { value: new Color(o.border ?? 0x7dd3fc) },
+ uBorderWidth: { value: o.borderWidth ?? 1 },
+ uOpacity: { value: o.opacity ?? 1 },
+ uBright: { value: o.bright ?? 1 },
+ uTint: { value: new Color(o.tint ?? 0xffffff) },
+ uFogDensity: shared.fogDensity,
+ },
+ vertexShader: PANEL_VERT,
+ fragmentShader: PANEL_FRAG,
+ transparent: true,
+ depthWrite: false,
+ side: DoubleSide,
+ blending: NormalBlending,
+ });
+}
+
+/* ---------------------------------------------------------------- points -- */
+
+const POINTS_VERT = /* glsl */ `
+attribute float aSize;
+attribute vec3 aColor;
+attribute float aAlpha;
+uniform float uScale;
+uniform float uTime;
+uniform float uDrift;
+uniform float uTwinkle;
+varying vec3 vColor;
+varying float vAlpha;
+varying float vDepth;
+void main() {
+ vec3 p = position;
+ // Slow, per-particle bobbing; uDrift is 0 for points animated on the CPU.
+ float phase = dot(position, vec3(12.9898, 78.233, 37.719));
+ p.y += sin(uTime * 0.21 + phase) * uDrift;
+ p.x += cos(uTime * 0.17 + phase * 1.7) * uDrift * 0.6;
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ vDepth = -mv.z;
+ float px = aSize * uScale / max(vDepth, 0.001);
+ // Sub-pixel points flicker, so hold them at one pixel and dim them instead.
+ vAlpha = aAlpha * clamp(px, 0.0, 1.0);
+ // Status lights: each blinks at its own rate.
+ float blink = 0.5 + 0.5 * sin(uTime * (1.1 + fract(phase) * 2.8) + phase);
+ vAlpha *= mix(1.0, 0.25 + 0.75 * blink * blink, uTwinkle);
+ gl_PointSize = max(px, 1.0);
+ vColor = aColor;
+ gl_Position = projectionMatrix * mv;
+}
+`;
+
+const POINTS_FRAG = /* glsl */ `
+uniform float uOpacity;
+varying vec3 vColor;
+varying float vAlpha;
+${FOG}
+void main() {
+ vec2 q = gl_PointCoord * 2.0 - 1.0;
+ float r2 = dot(q, q);
+ if (r2 > 1.0) discard;
+ float a = 1.0 - r2;
+ gl_FragColor = vec4(vColor, a * a * vAlpha * uOpacity * fogFactor());
+ ${OUTPUT}
+}
+`;
+
+export function pointsMaterial(o: { opacity?: number; drift?: number; twinkle?: number } = {}) {
+ return new ShaderMaterial({
+ uniforms: {
+ uScale: shared.pointScale,
+ uTime: shared.time,
+ uDrift: { value: o.drift ?? 0 },
+ uTwinkle: { value: o.twinkle ?? 0 },
+ uOpacity: { value: o.opacity ?? 1 },
+ uFogDensity: shared.fogDensity,
+ },
+ vertexShader: POINTS_VERT,
+ fragmentShader: POINTS_FRAG,
+ transparent: true,
+ depthWrite: false,
+ blending: AdditiveBlending,
+ });
+}
+
+/* ------------------------------------------------------------------- rim -- */
+// Phone bodies: near-black solids with a fresnel edge, so they read as objects
+// lit from behind by their own screens.
+
+const RIM_VERT = /* glsl */ `
+varying vec3 vNormal;
+varying vec3 vView;
+varying float vDepth;
+varying vec3 vTint;
+void main() {
+ vec4 p = vec4(position, 1.0);
+ vec3 n = normal;
+ #ifdef USE_INSTANCING
+ p = instanceMatrix * p;
+ n = mat3(instanceMatrix) * n;
+ #endif
+ vec4 mv = modelViewMatrix * p;
+ // Extruded geometry can carry zero-length normals at degenerate triangles;
+ // normalising those would put NaN on screen, and bloom would spread it.
+ vec3 vn = normalMatrix * n;
+ float len = length(vn);
+ vNormal = len > 1e-6 ? vn / len : vec3(0.0, 0.0, 1.0);
+ vView = normalize(-mv.xyz);
+ vDepth = -mv.z;
+ vTint = vec3(1.0);
+ #ifdef USE_INSTANCING_COLOR
+ vTint = instanceColor;
+ #endif
+ gl_Position = projectionMatrix * mv;
+}
+`;
+
+const RIM_FRAG = /* glsl */ `
+uniform float uOpacity;
+uniform vec3 uBody;
+uniform vec3 uRim;
+varying vec3 vNormal;
+varying vec3 vView;
+varying vec3 vTint;
+${FOG}
+void main() {
+ float len = length(vNormal);
+ vec3 normal = len > 1e-6 ? vNormal / len : vec3(0.0, 0.0, 1.0);
+ float facing = clamp(dot(normal, normalize(vView)), 0.0, 1.0);
+ float rim = pow(1.0 - facing, 2.4);
+ vec3 col = uBody + vTint * uRim * (rim * 1.25 + 0.05);
+ float fog = fogFactor();
+ gl_FragColor = vec4(col * fog * uOpacity, uOpacity);
+ ${OUTPUT}
+}
+`;
+
+export function rimMaterial(rim = 0xffffff) {
+ return new ShaderMaterial({
+ uniforms: {
+ uOpacity: { value: 1 },
+ uBody: { value: new Color(0x04070b) },
+ uRim: { value: new Color(rim) },
+ uFogDensity: shared.fogDensity,
+ },
+ vertexShader: RIM_VERT,
+ fragmentShader: RIM_FRAG,
+ transparent: true,
+ depthWrite: true,
+ });
+}
+
+/* ---------------------------------------------------------------- ripple -- */
+// The gateway membrane: concentric waves travelling into the centre.
+
+const RIPPLE_FRAG = /* glsl */ `
+uniform vec3 uColorA;
+uniform vec3 uColorB;
+uniform float uOpacity;
+uniform float uTime;
+varying vec2 vUv;
+${FOG}
+void main() {
+ vec2 q = vUv * 2.0 - 1.0;
+ float r = length(q);
+ if (r > 1.0) discard;
+ float wave = 0.5 + 0.5 * sin(r * 26.0 + uTime * 2.4);
+ float falloff = smoothstep(1.0, 0.15, r);
+ float edge = smoothstep(0.9, 1.0, r);
+ vec3 col = mix(uColorB, uColorA, r);
+ float a = (0.05 + 0.2 * wave * wave * falloff) + edge * 0.35;
+ gl_FragColor = vec4(col, a * uOpacity * fogFactor());
+ ${OUTPUT}
+}
+`;
+
+export function rippleMaterial(colorA: number, colorB: number) {
+ return new ShaderMaterial({
+ uniforms: {
+ uColorA: { value: new Color(colorA) },
+ uColorB: { value: new Color(colorB) },
+ uOpacity: { value: 1 },
+ uTime: shared.time,
+ uFogDensity: shared.fogDensity,
+ },
+ vertexShader: PANEL_VERT,
+ fragmentShader: RIPPLE_FRAG,
+ transparent: true,
+ depthWrite: false,
+ side: DoubleSide,
+ blending: AdditiveBlending,
+ });
+}
+
+/* -------------------------------------------------------------- backdrop -- */
+
+const BACKDROP_VERT = /* glsl */ `
+varying vec2 vUv;
+void main() {
+ vUv = uv;
+ gl_Position = vec4(position.xy, 1.0, 1.0);
+}
+`;
+
+const BACKDROP_FRAG = /* glsl */ `
+uniform vec3 uTop;
+uniform vec3 uBottom;
+uniform vec3 uGlow;
+uniform vec2 uGlowPos;
+uniform float uAspect;
+varying vec2 vUv;
+float hash(vec2 p) {
+ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
+}
+void main() {
+ vec3 col = mix(uBottom, uTop, smoothstep(0.0, 1.0, vUv.y));
+ vec2 q = vUv - uGlowPos;
+ q.x *= uAspect;
+ col += uGlow * exp(-dot(q, q) * 2.6);
+ // Dither away the banding a dark gradient would otherwise show.
+ col += (hash(gl_FragCoord.xy) - 0.5) * 0.008;
+ gl_FragColor = vec4(max(col, 0.0), 1.0);
+ ${OUTPUT}
+}
+`;
+
+export function backdropMaterial() {
+ return new ShaderMaterial({
+ uniforms: {
+ uTop: { value: new Color(0x070b12) },
+ uBottom: { value: new Color(0x030405) },
+ uGlow: { value: new Color(0x0b2a3a) },
+ uGlowPos: { value: new Vector2(0.7, 0.45) },
+ uAspect: { value: 1.6 },
+ },
+ vertexShader: BACKDROP_VERT,
+ fragmentShader: BACKDROP_FRAG,
+ depthTest: false,
+ depthWrite: false,
+ });
+}
+
+/* --------------------------------------------------------------- helpers -- */
+
+export function lineMaterial(color: number, opacity = 0.5) {
+ return new LineBasicMaterial({
+ color,
+ transparent: true,
+ opacity,
+ depthWrite: false,
+ blending: AdditiveBlending,
+ });
+}
+
+export function glowSpriteMaterial(map: Texture, color: number, opacity = 0.5) {
+ return new SpriteMaterial({
+ map,
+ color,
+ transparent: true,
+ opacity,
+ depthWrite: false,
+ blending: AdditiveBlending,
+ });
+}
+
+/**
+ * Fades a whole station in and out. Materials with a `uOpacity` uniform and
+ * built-in materials are both handled; each keeps its own base opacity.
+ */
+export class Fader {
+ /** Current weight, for materials whose opacity is animated by hand. */
+ w = 1;
+ private items: { material: Material; base: number; uniform?: IUniform }[] = [];
+
+ add(material: T, base?: number): T {
+ const uniform = (material as unknown as ShaderMaterial).uniforms?.uOpacity as
+ | IUniform
+ | undefined;
+ this.items.push({
+ material,
+ uniform,
+ base: base ?? (uniform ? uniform.value : material.opacity),
+ });
+ return material;
+ }
+
+ set(w: number) {
+ this.w = w;
+ for (const item of this.items) {
+ if (item.uniform) item.uniform.value = item.base * w;
+ else item.material.opacity = item.base * w;
+ }
+ }
+}
diff --git a/app/components/campaign/scene/mockups.ts b/app/components/campaign/scene/mockups.ts
new file mode 100644
index 0000000..5c1cf87
--- /dev/null
+++ b/app/components/campaign/scene/mockups.ts
@@ -0,0 +1,419 @@
+// Canvas-drawn screens of the example application: TrailyShop, an invented
+// outdoor-gear shop, seen on a phone. The product page shows one shoe, the
+// Traily Run, with a stock count; buying it is the update the film follows.
+// Company and product names are made up for this page.
+
+import { css } from "./palette";
+import { roundRect, type Ctx, type TextureKit } from "./textures";
+
+/** A rectangle in texture space, as fractions of the texture (v down). */
+export interface UvRect {
+ u: number;
+ v: number;
+ w: number;
+ h: number;
+}
+
+export const SHOP = "TrailyShop";
+export const PRODUCT = {
+ name: "Traily Run",
+ kind: "Trail running shoe",
+ price: "$129",
+ tags: ["trail", "shoes", "new"],
+} as const;
+
+/** Stock before the tap and after it. */
+export const STOCK_BEFORE = 2;
+export const STOCK_AFTER = 1;
+
+/** Logical size of a phone screen texture. */
+export const PHONE_PX: [number, number] = [600, 1300];
+
+const CARD = { x: 24, y: 196, w: 552, h: 772 };
+const S = CARD.w / 336;
+const BUTTON = { x: CARD.x + 20 * S, y: CARD.y + CARD.h - 64 * S, w: CARD.w - 40 * S, h: 44 * S };
+
+const uv = (rect: { x: number; y: number; w: number; h: number }): UvRect => ({
+ u: rect.x / PHONE_PX[0],
+ v: rect.y / PHONE_PX[1],
+ w: rect.w / PHONE_PX[0],
+ h: rect.h / PHONE_PX[1],
+});
+
+/** The product card and its Buy button on the phone screen. */
+export const CARD_UV = uv(CARD);
+export const BUTTON_UV = uv(BUTTON);
+
+function text(
+ ctx: Ctx,
+ value: string,
+ x: number,
+ y: number,
+ font: string,
+ color: string,
+ align: CanvasTextAlign = "left",
+) {
+ ctx.font = font;
+ ctx.fillStyle = color;
+ ctx.textAlign = align;
+ ctx.textBaseline = "alphabetic";
+ ctx.fillText(value, x, y);
+}
+
+function fillRound(ctx: Ctx, x: number, y: number, w: number, h: number, r: number, fill: string) {
+ roundRect(ctx, x, y, w, h, r);
+ ctx.fillStyle = fill;
+ ctx.fill();
+}
+
+function strokeRound(ctx: Ctx, x: number, y: number, w: number, h: number, r: number, stroke: string, width = 2) {
+ roundRect(ctx, x, y, w, h, r);
+ ctx.strokeStyle = stroke;
+ ctx.lineWidth = width;
+ ctx.stroke();
+}
+
+function textWidth(ctx: Ctx, value: string, font: string) {
+ ctx.font = font;
+ return ctx.measureText(value).width;
+}
+
+/** Backdrop for product art: a ridge line under a low sun. */
+function ridge(ctx: Ctx, x: number, y: number, w: number, h: number, hue: [string, string], seed: number) {
+ ctx.save();
+ roundRect(ctx, x, y, w, h, Math.min(w, h) * 0.07);
+ ctx.clip();
+ const gradient = ctx.createLinearGradient(x, y, x, y + h);
+ gradient.addColorStop(0, hue[0]);
+ gradient.addColorStop(1, hue[1]);
+ ctx.fillStyle = gradient;
+ ctx.fillRect(x, y, w, h);
+ ctx.fillStyle = "rgba(255,255,255,0.9)";
+ ctx.beginPath();
+ ctx.arc(x + w * (0.76 - 0.1 * seed), y + h * 0.3, h * 0.12, 0, Math.PI * 2);
+ ctx.fill();
+ for (let layer = 0; layer < 2; layer++) {
+ ctx.fillStyle = layer === 0 ? "rgba(13,116,110,0.13)" : "rgba(13,116,110,0.22)";
+ ctx.beginPath();
+ ctx.moveTo(x, y + h);
+ const peaks = 4 + layer;
+ for (let i = 0; i <= peaks; i++) {
+ const px = x + (w * i) / peaks;
+ const wobble = Math.sin((i + 1) * (2.3 + seed) + layer * 1.7);
+ ctx.lineTo(px, y + h * (0.6 + layer * 0.16) - Math.abs(wobble) * h * (0.22 - layer * 0.08));
+ }
+ ctx.lineTo(x + w, y + h);
+ ctx.closePath();
+ ctx.fill();
+ }
+ ctx.restore();
+}
+
+/**
+ * A plain running shoe in profile, toe to the right, drawn in a unit box one
+ * shoe-length wide. It carries no stripes or marks, on purpose: it must not
+ * resemble any real brand's shoe.
+ */
+function shoe(ctx: Ctx, x: number, y: number, length: number, upper: [string, string]) {
+ ctx.save();
+ ctx.translate(x, y);
+ ctx.scale(length, length);
+ ctx.rotate(-0.07);
+
+ // Contact shadow.
+ ctx.fillStyle = "rgba(15,23,42,0.2)";
+ ctx.beginPath();
+ ctx.ellipse(0.52, 0.505, 0.47, 0.028, 0, 0, Math.PI * 2);
+ ctx.fill();
+
+ // Lugs under the outsole.
+ ctx.fillStyle = "#1c2836";
+ for (let i = 0; i < 9; i++) {
+ const lx = 0.075 + i * 0.086;
+ ctx.fillRect(lx, 0.462, 0.054, 0.03);
+ }
+
+ const midsoleTop = () => {
+ ctx.quadraticCurveTo(0.74, 0.385, 0.5, 0.385);
+ ctx.quadraticCurveTo(0.24, 0.385, 0.055, 0.315);
+ };
+
+ // Midsole.
+ const sole = ctx.createLinearGradient(0, 0.32, 0, 0.48);
+ sole.addColorStop(0, "#e9eef4");
+ sole.addColorStop(1, "#a3b2c2");
+ ctx.fillStyle = sole;
+ ctx.beginPath();
+ ctx.moveTo(0.045, 0.47);
+ ctx.lineTo(0.8, 0.47);
+ ctx.quadraticCurveTo(0.93, 0.47, 0.975, 0.39);
+ ctx.lineTo(0.98, 0.345);
+ midsoleTop();
+ ctx.quadraticCurveTo(0.005, 0.36, 0.045, 0.47);
+ ctx.closePath();
+ ctx.fill();
+
+ // Upper.
+ const body = ctx.createLinearGradient(0.1, 0.02, 0.8, 0.4);
+ body.addColorStop(0, upper[0]);
+ body.addColorStop(1, upper[1]);
+ ctx.fillStyle = body;
+ ctx.beginPath();
+ ctx.moveTo(0.055, 0.315);
+ ctx.bezierCurveTo(0.02, 0.22, 0.035, 0.1, 0.075, 0.035);
+ ctx.lineTo(0.115, 0.02);
+ ctx.quadraticCurveTo(0.16, 0.16, 0.27, 0.15);
+ ctx.quadraticCurveTo(0.33, 0.14, 0.37, 0.035);
+ ctx.lineTo(0.425, 0.045);
+ ctx.quadraticCurveTo(0.56, 0.2, 0.7, 0.235);
+ ctx.quadraticCurveTo(0.9, 0.265, 0.98, 0.345);
+ midsoleTop();
+ ctx.closePath();
+ ctx.fill();
+
+ // Heel counter and toe cap, a shade darker.
+ ctx.fillStyle = "rgba(2,30,34,0.42)";
+ ctx.beginPath();
+ ctx.moveTo(0.055, 0.315);
+ ctx.bezierCurveTo(0.02, 0.22, 0.035, 0.1, 0.075, 0.035);
+ ctx.lineTo(0.115, 0.02);
+ ctx.quadraticCurveTo(0.14, 0.12, 0.19, 0.15);
+ ctx.lineTo(0.2, 0.36);
+ ctx.quadraticCurveTo(0.12, 0.35, 0.055, 0.315);
+ ctx.closePath();
+ ctx.fill();
+ ctx.beginPath();
+ ctx.moveTo(0.8, 0.252);
+ ctx.quadraticCurveTo(0.92, 0.275, 0.98, 0.345);
+ ctx.quadraticCurveTo(0.86, 0.372, 0.76, 0.378);
+ ctx.quadraticCurveTo(0.74, 0.31, 0.8, 0.252);
+ ctx.closePath();
+ ctx.fill();
+
+ // Eyestay along the throat, with laces across it.
+ ctx.fillStyle = "rgba(255,255,255,0.17)";
+ ctx.beginPath();
+ ctx.moveTo(0.37, 0.035);
+ ctx.lineTo(0.425, 0.045);
+ ctx.quadraticCurveTo(0.56, 0.2, 0.7, 0.235);
+ ctx.lineTo(0.665, 0.29);
+ ctx.quadraticCurveTo(0.5, 0.25, 0.385, 0.12);
+ ctx.closePath();
+ ctx.fill();
+ ctx.strokeStyle = "rgba(255,255,255,0.92)";
+ ctx.lineWidth = 0.013;
+ ctx.lineCap = "round";
+ for (let k = 0; k < 5; k++) {
+ const t = 0.1 + k * 0.2;
+ const lx = (1 - t) ** 2 * 0.425 + 2 * (1 - t) * t * 0.56 + t * t * 0.7;
+ const ly = (1 - t) ** 2 * 0.045 + 2 * (1 - t) * t * 0.2 + t * t * 0.235;
+ ctx.beginPath();
+ ctx.moveTo(lx, ly);
+ ctx.lineTo(lx - 0.036, ly + 0.05);
+ ctx.stroke();
+ }
+
+ // Collar lining and a pinstripe on the midsole.
+ ctx.strokeStyle = "rgba(255,255,255,0.5)";
+ ctx.lineWidth = 0.008;
+ ctx.beginPath();
+ ctx.moveTo(0.115, 0.02);
+ ctx.quadraticCurveTo(0.16, 0.16, 0.27, 0.15);
+ ctx.quadraticCurveTo(0.33, 0.14, 0.37, 0.035);
+ ctx.stroke();
+ ctx.strokeStyle = "rgba(56,189,248,0.9)";
+ ctx.lineWidth = 0.011;
+ ctx.beginPath();
+ ctx.moveTo(0.09, 0.4);
+ ctx.quadraticCurveTo(0.5, 0.462, 0.9, 0.418);
+ ctx.stroke();
+
+ ctx.restore();
+}
+
+function stockLabel(stock: number) {
+ return `Only ${stock} left`;
+}
+
+/** The product card. `s` scales every measurement. */
+function productCard(ctx: Ctx, sans: string, x: number, y: number, w: number, h: number, s: number, stock: number) {
+ fillRound(ctx, x, y, w, h, 18 * s, css.uiSurface);
+ strokeRound(ctx, x, y, w, h, 18 * s, css.uiLine, 2 * s);
+
+ const artW = w - 28 * s;
+ const artH = 214 * s;
+ ridge(ctx, x + 14 * s, y + 14 * s, artW, artH, ["#cfe8f7", "#eef7f1"], 1);
+ shoe(ctx, x + 14 * s + artW * 0.1, y + 14 * s + artH * 0.34, artW * 0.8, ["#5eead4", "#0f766e"]);
+
+ text(ctx, PRODUCT.name, x + 22 * s, y + 270 * s, `700 ${27 * s}px ${sans}`, css.uiText);
+ text(ctx, PRODUCT.kind, x + 22 * s, y + 297 * s, `400 ${16 * s}px ${sans}`, css.uiMuted);
+ text(ctx, PRODUCT.price, x + 22 * s, y + 343 * s, `700 ${28 * s}px ${sans}`, css.uiText);
+
+ // Stock: the number the whole film is about.
+ const stockFont = `600 ${16 * s}px ${sans}`;
+ const label = stockLabel(stock);
+ const labelW = textWidth(ctx, label, stockFont);
+ fillRound(ctx, x + w - 22 * s - labelW - 36 * s, y + 320 * s, labelW + 36 * s, 30 * s, 15 * s, css.uiAmberSoft);
+ ctx.fillStyle = css.uiAmber;
+ ctx.beginPath();
+ ctx.arc(x + w - 22 * s - labelW - 20 * s, y + 335 * s, 4.5 * s, 0, Math.PI * 2);
+ ctx.fill();
+ text(ctx, label, x + w - 34 * s, y + 340.5 * s, stockFont, css.uiAmber, "right");
+
+ let chipX = x + 22 * s;
+ for (const tag of PRODUCT.tags) {
+ const font = `500 ${14 * s}px ${sans}`;
+ const chipW = textWidth(ctx, tag, font) + 22 * s;
+ fillRound(ctx, chipX, y + 362 * s, chipW, 27 * s, 13.5 * s, css.uiGreenSoft);
+ text(ctx, tag, chipX + 11 * s, y + 380.5 * s, font, css.uiGreen);
+ chipX += chipW + 8 * s;
+ }
+
+ fillRound(ctx, x + 20 * s, y + h - 64 * s, w - 40 * s, 44 * s, 12 * s, css.uiAccent);
+ text(ctx, "Buy now", x + w / 2, y + h - 64 * s + 29.5 * s, `700 ${19 * s}px ${sans}`, "#ffffff", "center");
+}
+
+function homeIndicator(ctx: Ctx) {
+ fillRound(ctx, PHONE_PX[0] / 2 - 90, 1276, 180, 6, 3, "#1e293b");
+}
+
+function productPage(ctx: Ctx, sans: string, stock: number) {
+ const [W, H] = PHONE_PX;
+ ctx.fillStyle = css.uiBg;
+ ctx.fillRect(0, 0, W, H);
+
+ // Status bar.
+ text(ctx, "9:41", 44, 50, `600 22px ${sans}`, css.uiText);
+ fillRound(ctx, W / 2 - 74, 22, 148, 36, 18, "#02040a");
+ strokeRound(ctx, W - 88, 30, 44, 22, 7, css.uiMuted, 2);
+ fillRound(ctx, W - 84, 34, 30, 14, 4, css.uiText);
+
+ // Shop header.
+ fillRound(ctx, 28, 92, 40, 40, 11, css.uiGreen);
+ ctx.fillStyle = "#ffffff";
+ ctx.beginPath();
+ ctx.moveTo(35, 124);
+ ctx.lineTo(45, 103);
+ ctx.lineTo(51, 114);
+ ctx.lineTo(55, 108);
+ ctx.lineTo(62, 124);
+ ctx.closePath();
+ ctx.fill();
+ text(ctx, SHOP, 80, 122, `700 28px ${sans}`, css.uiText);
+ strokeRound(ctx, W - 80, 98, 36, 30, 8, css.uiText, 2.5);
+ ctx.fillStyle = css.uiGreen;
+ ctx.beginPath();
+ ctx.arc(W - 42, 98, 13, 0, Math.PI * 2);
+ ctx.fill();
+ text(ctx, "1", W - 42, 104, `700 16px ${sans}`, "#ffffff", "center");
+
+ text(ctx, "‹ Trail running", 30, 174, `500 20px ${sans}`, css.uiMuted);
+
+ productCard(ctx, sans, CARD.x, CARD.y, CARD.w, CARD.h, S, stock);
+
+ // Pick-up row: the geospatial query in the story.
+ fillRound(ctx, 24, 986, 552, 92, 20, css.uiSurface);
+ strokeRound(ctx, 24, 986, 552, 92, 20, css.uiLine, 2);
+ ctx.fillStyle = css.uiGreen;
+ ctx.beginPath();
+ ctx.arc(64, 1024, 15, Math.PI, 0);
+ ctx.lineTo(64, 1058);
+ ctx.closePath();
+ ctx.fill();
+ ctx.fillStyle = css.uiSurface;
+ ctx.beginPath();
+ ctx.arc(64, 1024, 5.5, 0, Math.PI * 2);
+ ctx.fill();
+ text(ctx, "Pick up today", 98, 1026, `700 22px ${sans}`, css.uiText);
+ text(ctx, "Seattle store · 1.2 km", 98, 1056, `400 18px ${sans}`, css.uiMuted);
+ text(ctx, "›", 550, 1044, `500 30px ${sans}`, css.uiMuted, "right");
+
+ // Similar gear: the vector search in the story.
+ text(ctx, "Similar gear", 30, 1126, `700 22px ${sans}`, css.uiText);
+ const similar: [string, string][] = [
+ ["#c4b5fd", "#5b46b8"],
+ ["#7dd3fc", "#1d6fa5"],
+ ["#fcd34d", "#b45309"],
+ ["#f0abfc", "#86198f"],
+ ];
+ similar.forEach((upper, i) => {
+ const tx = 24 + i * 141;
+ fillRound(ctx, tx, 1144, 129, 112, 16, css.uiSurface);
+ strokeRound(ctx, tx, 1144, 129, 112, 16, css.uiLine, 2);
+ shoe(ctx, tx + 12, 1144 + 34, 105, upper);
+ });
+
+ homeIndicator(ctx);
+}
+
+/** The product page with a given stock count. */
+export function phonePage(kit: TextureKit, stock: number) {
+ return kit.draw(PHONE_PX[0], PHONE_PX[1], (ctx) => productPage(ctx, kit.sans, stock));
+}
+
+/** What the phone shows once the reply is back: the order, and one pair fewer. */
+export function confirmedPage(kit: TextureKit) {
+ const [W, H] = PHONE_PX;
+ const sans = kit.sans;
+ return kit.draw(W, H, (ctx) => {
+ productPage(ctx, sans, STOCK_AFTER);
+ ctx.fillStyle = "rgba(15,23,42,0.45)";
+ ctx.fillRect(0, 0, W, H);
+
+ // Bottom sheet.
+ roundRect(ctx, 0, 470, W, H - 470 + 60, 44);
+ ctx.fillStyle = css.uiSurface;
+ ctx.fill();
+ ctx.strokeStyle = css.uiLine;
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ fillRound(ctx, W / 2 - 28, 488, 56, 6, 3, "#cbd5e1");
+
+ ctx.fillStyle = css.uiGreen;
+ ctx.beginPath();
+ ctx.arc(W / 2, 600, 60, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.strokeStyle = "#ffffff";
+ ctx.lineWidth = 11;
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+ ctx.beginPath();
+ ctx.moveTo(W / 2 - 27, 602);
+ ctx.lineTo(W / 2 - 7, 622);
+ ctx.lineTo(W / 2 + 29, 580);
+ ctx.stroke();
+
+ text(ctx, "Order placed", W / 2, 722, `700 46px ${sans}`, css.uiText, "center");
+ text(ctx, `${PRODUCT.name} · ${PRODUCT.price} · order 1042`, W / 2, 762, `400 21px ${sans}`, css.uiMuted, "center");
+
+ fillRound(ctx, 36, 800, 528, 184, 20, css.uiSurface2);
+ text(ctx, "Pick up", 62, 852, `400 21px ${sans}`, css.uiMuted);
+ text(ctx, "Seattle store · today", 538, 852, `600 21px ${sans}`, css.uiText, "right");
+ ctx.fillStyle = css.uiLine;
+ ctx.fillRect(62, 884, 476, 2);
+ text(ctx, "Left in stock", 62, 942, `400 21px ${sans}`, css.uiMuted);
+ const left = `${STOCK_AFTER} left`;
+ const leftFont = `700 28px ${sans}`;
+ const leftW = textWidth(ctx, left, leftFont);
+ ctx.fillStyle = css.uiAmber;
+ ctx.beginPath();
+ ctx.arc(538 - leftW - 16, 933, 6, 0, Math.PI * 2);
+ ctx.fill();
+ text(ctx, left, 538, 943, leftFont, css.uiAmber, "right");
+
+ fillRound(ctx, 36, 1018, 528, 76, 20, css.uiAccent);
+ text(ctx, "View order", W / 2, 1066, `700 26px ${sans}`, "#ffffff", "center");
+ text(ctx, "Keep shopping", W / 2, 1152, `600 21px ${sans}`, css.uiAccent, "center");
+ homeIndicator(ctx);
+ });
+}
+
+/** The Buy button after the tap, while the request is on its way. */
+export function pressedButton(kit: TextureKit) {
+ const w = Math.round(BUTTON.w);
+ const h = Math.round(BUTTON.h);
+ return kit.draw(w, h, (ctx) => {
+ fillRound(ctx, 0, 0, w, h, 12 * S, "#075a99");
+ text(ctx, "Placing order…", w / 2, h / 2 + 10, `700 ${19 * S}px ${kit.sans}`, "#e6f6ff", "center");
+ });
+}
diff --git a/app/components/campaign/scene/palette.ts b/app/components/campaign/scene/palette.ts
new file mode 100644
index 0000000..155e931
--- /dev/null
+++ b/app/components/campaign/scene/palette.ts
@@ -0,0 +1,46 @@
+// Colour roles: emerald is the document API side, sky is the
+// PostgreSQL side, violet is vector search, amber marks superseded data.
+
+export const hex = {
+ bg: 0x05070a,
+ sky: 0x7dd3fc,
+ skyDeep: 0x38bdf8,
+ emerald: 0x6ee7b7,
+ emeraldDeep: 0x34d399,
+ amber: 0xfbbf24,
+ violet: 0xc4b5fd,
+ violetDeep: 0xa78bfa,
+ ink: 0xe6f1ff,
+ dim: 0x4b6477,
+} as const;
+
+export const css = {
+ sky: "#7dd3fc",
+ skyDeep: "#38bdf8",
+ emerald: "#6ee7b7",
+ amber: "#fbbf24",
+ violet: "#c4b5fd",
+ ink: "#e6f1ff",
+ dim: "#8aa2b6",
+ faint: "#5b7186",
+ // code tokens
+ key: "#7dd3fc",
+ string: "#a7f3d0",
+ number: "#fde68a",
+ punct: "#7388a0",
+ fn: "#c4b5fd",
+ // mock application chrome: a light, ordinary shopping app
+ uiBg: "#f1f4f8",
+ uiSurface: "#ffffff",
+ uiSurface2: "#eef2f7",
+ uiLine: "#dde4ec",
+ uiText: "#0f172a",
+ uiMuted: "#64748b",
+ uiAccent: "#0b74c4",
+ uiGreen: "#059669",
+ uiGreenSoft: "#dcfce7",
+ uiAmber: "#b45309",
+ uiAmberSoft: "#fef3c7",
+} as const;
+
+export type CssColor = keyof typeof css;
diff --git a/app/components/campaign/scene/rig.ts b/app/components/campaign/scene/rig.ts
new file mode 100644
index 0000000..0a8470f
--- /dev/null
+++ b/app/components/campaign/scene/rig.ts
@@ -0,0 +1,339 @@
+// The camera of the film. It never cuts: one spline runs from the phone down
+// to the heap page and back, with a rest at every shot. Position is a pure
+// function of film time, so a frame looks the same whether it is reached by
+// playing, by a loop or by a seek.
+
+import { CatmullRomCurve3, MathUtils, PerspectiveCamera, Vector3 } from "three";
+import { DURATION } from "./film";
+import type { Signal } from "./signal";
+import { clamp, lerp, smoother } from "./util";
+import { SERVER, Y } from "./world";
+
+type Triple = [number, number, number];
+
+interface Framing {
+ pos: Triple;
+ target: Triple;
+ /** World width that must stay visible around the target. */
+ span: number;
+ /** World height that must stay visible around the target. */
+ rise: number;
+}
+
+interface Key extends Framing {
+ /** Film time at which the camera is here. */
+ t: number;
+ /**
+ * How the camera gets here from the previous key:
+ * move a travel that comes to rest here,
+ * drift a slow, even glide between two rests (the length of a shot),
+ * pass a waypoint in the middle of a travel.
+ */
+ how: "move" | "drift" | "pass";
+ fog: number;
+ fov?: number;
+ /** How much the look-at point is pulled onto the travelling light, 0..1. */
+ follow?: number;
+ /** Tighter framing for narrow screens, which have a third of the width. */
+ narrow?: Partial;
+}
+
+/** Part of the canvas the scene may use, in CSS pixels from its top-left. */
+export interface FocusRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+const FOV = 38;
+const TOP = 3;
+const OVERVIEW_Y = (TOP + SERVER.bottom) / 2;
+const { gateway: G, vector: V, index: I, heap: H } = Y;
+
+// Opening framing; the film also ends on it, which is what lets it loop.
+const OPENING: Framing = { pos: [0.95, 1.8, 13.4], target: [0.12, 1.45, 6.5], span: 5.4, rise: 4.6 };
+
+const KEYS: Key[] = [
+ /* 1 · the phone, pushing in on the button */
+ { t: 0, how: "move", ...OPENING, fog: 0.016 },
+ { t: 2.3, how: "drift", pos: [0.8, 1.62, 12.3], target: [0.06, 1.3, 6.5], span: 3.9, rise: 3.5, fog: 0.018 },
+ /* 2 · phone and document side by side */
+ {
+ t: 3.3,
+ how: "move",
+ pos: [2.25, 1.95, 12.6],
+ target: [1.33, 1.62, 6.95],
+ span: 4.6,
+ rise: 3.3,
+ fog: 0.02,
+ narrow: { pos: [2.5, 1.78, 12.4], target: [2.05, 1.52, 7.05], span: 2.75, rise: 2.7 },
+ },
+ {
+ t: 6.8,
+ how: "drift",
+ pos: [2.2, 1.85, 12.2],
+ target: [1.4, 1.55, 6.95],
+ span: 4.45,
+ rise: 3.15,
+ fog: 0.02,
+ narrow: { pos: [2.45, 1.7, 12.1], target: [2.05, 1.42, 7.05], span: 2.7, rise: 2.6 },
+ },
+ /* 3 · down after the light, to the mouth of an aisle of server racks */
+ { t: 7.85, how: "pass", pos: [1.9, -1.6, 18.2], target: [0, -3.4, 10], span: 10, rise: 8, fog: 0.014, follow: 1 },
+ { t: 8.75, how: "pass", pos: [0.55, -5.3, 17], target: [0, -6.7, 4.5], span: 9, rise: 6.4, fog: 0.02, follow: 0.55 },
+ /* 4 · inside the last rack: the gateway */
+ {
+ t: 9.95,
+ how: "move",
+ pos: [6.4, G + 5.4, 11.6],
+ target: [0.5, G - 0.3, 0],
+ span: 9.6,
+ rise: 9.5,
+ fog: 0.028,
+ narrow: { pos: [4.2, G + 5.2, 12.4], target: [0, G - 0.5, 0], span: 7.6, rise: 8.6 },
+ },
+ {
+ t: 12.2,
+ how: "drift",
+ pos: [6.1, G + 4.9, 11.3],
+ target: [0.45, G - 0.7, 0],
+ span: 9.6,
+ rise: 9.5,
+ fog: 0.028,
+ narrow: { pos: [4.0, G + 4.7, 12.1], target: [0, G - 0.9, 0], span: 7.6, rise: 8.6 },
+ },
+ /* 5 · falling to the primary-key B-tree */
+ { t: 12.95, how: "pass", pos: [3.4, -23.5, 13.8], target: [-1, -24, 2], span: 9, rise: 9, fog: 0.022, follow: 1 },
+ { t: 13.7, how: "move", pos: [-0.9, I + 1.5, 14.6], target: [-2.75, I + 0.1, 0], span: 7.6, rise: 8.7, fog: 0.022 },
+ { t: 15.5, how: "drift", pos: [-0.8, I + 0.5, 14.4], target: [-2.6, I - 0.9, 0], span: 7.6, rise: 8.3, fog: 0.022 },
+ /* 6 · craning down to the heap page */
+ { t: 16.15, how: "pass", pos: [0.9, -44.6, 15], target: [-0.8, -46, 0], span: 9.6, rise: 9.4, fog: 0.022, follow: 0.7 },
+ {
+ t: 16.8,
+ how: "move",
+ pos: [2.2, H + 0.5, 15],
+ target: [0.7, H - 0.35, 0],
+ span: 11.5,
+ rise: 10.7,
+ fog: 0.022,
+ narrow: { pos: [1.0, H - 1.3, 15], target: [-0.25, H - 1.95, 0], span: 7.4, rise: 6.7 },
+ },
+ {
+ t: 22.3,
+ how: "drift",
+ pos: [2.0, H + 0.3, 14.4],
+ target: [0.8, H - 0.6, 0],
+ span: 10.9,
+ rise: 10.0,
+ fog: 0.022,
+ narrow: { pos: [0.9, H - 1.5, 14.6], target: [-0.25, H - 2.15, 0], span: 7.3, rise: 6.6 },
+ },
+ /* 7 · back up past the other indexes: RUM, then vector and geospatial */
+ { t: 23.4, how: "move", pos: [5.4, I + 1.4, 14.2], target: [3.3, I + 0.05, 0], span: 7.8, rise: 8.7, fog: 0.022 },
+ { t: 25.1, how: "drift", pos: [5.1, I + 1.0, 13.9], target: [3.2, I - 0.3, 0], span: 7.8, rise: 8.5, fog: 0.022 },
+ { t: 26.2, how: "move", pos: [-4.6, V + 4.4, 14], target: [1.1, V + 0.7, 0], span: 11.6, rise: 8.2, fog: 0.024 },
+ { t: 28.6, how: "drift", pos: [-3.7, V + 4.0, 14.2], target: [1.2, V + 0.6, 0], span: 11.6, rise: 8.2, fog: 0.024 },
+ /* 8 · the whole stack, then home to the phone */
+ {
+ t: 30.3,
+ how: "move",
+ pos: [46, OVERVIEW_Y + 12, 100],
+ target: [9.5, OVERVIEW_Y, 0],
+ span: 45,
+ rise: TOP - SERVER.bottom + 7,
+ fog: 0.0026,
+ fov: 40,
+ narrow: { target: [0, OVERVIEW_Y, 0], span: 24 },
+ },
+ {
+ t: 32.0,
+ how: "drift",
+ pos: [42, OVERVIEW_Y + 13.5, 101],
+ target: [9.5, OVERVIEW_Y + 1, 0],
+ span: 45,
+ rise: TOP - SERVER.bottom + 7,
+ fog: 0.0026,
+ fov: 40,
+ narrow: { target: [0, OVERVIEW_Y + 1, 0], span: 24 },
+ },
+ { t: 33.8, how: "move", pos: [1.02, 1.9, 13.95], target: [0.12, 1.48, 6.5], span: 5.9, rise: 5.0, fog: 0.016 },
+ { t: DURATION, how: "drift", ...OPENING, fog: 0.016 },
+];
+
+const tmp = new Vector3();
+const right = new Vector3();
+const up = new Vector3();
+const light = new Vector3();
+
+export class Rig {
+ readonly camera = new PerspectiveCamera(FOV, 1.6, 0.1, 480);
+ fog = KEYS[0].fog;
+
+ private positions!: CatmullRomCurve3;
+ private targets!: CatmullRomCurve3;
+ private framings: Framing[] = [];
+ private narrow: boolean | null = null;
+ private readonly pos = new Vector3();
+ private readonly target = new Vector3();
+ private readonly pointer = { x: 0, y: 0, tx: 0, ty: 0 };
+ private width = 1;
+ private height = 1;
+ private focus: FocusRect = { x: 0, y: 0, width: 1, height: 1 };
+ private hasFocus = false;
+
+ constructor(private readonly signal: Signal) {
+ this.layout(false);
+ }
+
+ /** Builds the camera path for wide or narrow framing. */
+ private layout(narrow: boolean) {
+ if (narrow === this.narrow) return;
+ this.narrow = narrow;
+ this.framings = KEYS.map((key) => {
+ const base: Framing = { pos: key.pos, target: key.target, span: key.span, rise: key.rise };
+ return narrow ? { ...base, ...key.narrow } : base;
+ });
+ this.positions = new CatmullRomCurve3(
+ this.framings.map((framing) => new Vector3(...framing.pos)),
+ false,
+ "centripetal",
+ );
+ this.targets = new CatmullRomCurve3(
+ this.framings.map((framing) => new Vector3(...framing.target)),
+ false,
+ "centripetal",
+ );
+ }
+
+ resize(width: number, height: number) {
+ this.width = width;
+ this.height = height;
+ this.layout(width < 1024);
+ if (!this.hasFocus) this.focus = this.defaultFocus();
+ this.applyProjection(this.camera.fov);
+ }
+
+ /** The page tells the rig which part of the canvas is free of copy. */
+ setFocus(rect: FocusRect) {
+ this.focus = rect;
+ this.hasFocus = true;
+ this.applyProjection(this.camera.fov);
+ }
+
+ // Until the page reports the real layout: copy on the left for wide
+ // canvases, at the bottom for narrow ones.
+ private defaultFocus(): FocusRect {
+ const { width, height } = this;
+ return width >= 1024
+ ? { x: width * 0.46, y: height * 0.1, width: width * 0.5, height: height * 0.78 }
+ : { x: 0, y: height * 0.08, width, height: height * 0.42 };
+ }
+
+ private applyProjection(fov: number) {
+ const { width, height, focus } = this;
+ this.camera.fov = fov;
+ this.camera.aspect = width / Math.max(height, 1);
+ // Shift the optical centre to the middle of the focus area.
+ const dx = focus.x + focus.width / 2 - width / 2;
+ const dy = focus.y + focus.height / 2 - height / 2;
+ this.camera.setViewOffset(width, height, -dx, -dy, width, height);
+ }
+
+ setPointer(x: number, y: number) {
+ this.pointer.tx = clamp(x, -1, 1);
+ this.pointer.ty = clamp(y, -1, 1);
+ }
+
+ /**
+ * Bends time so that every travel between two rests eases out of the first
+ * and into the second, however many waypoints lie between them. Drifts are
+ * left linear: they are the slow glide during a shot.
+ */
+ private warp(t: number) {
+ let from = 0;
+ for (let i = 1; i < KEYS.length; i++) {
+ const key = KEYS[i];
+ if (key.how === "pass") continue;
+ if (t <= key.t) {
+ if (key.how === "drift") return t;
+ const start = KEYS[from].t;
+ return start + smoother((t - start) / (key.t - start)) * (key.t - start);
+ }
+ from = i;
+ }
+ return t;
+ }
+
+ /**
+ * Places the camera for film time `t`. `time` and `dt` only feed the idle
+ * sway and the pointer parallax, which `still` switches off.
+ */
+ update(t: number, time: number, dt: number, finale: number, still: boolean) {
+ const last = KEYS.length - 1;
+ const warped = this.warp(clamp(t, 0, DURATION));
+ let index = 0;
+ while (index < last - 1 && warped >= KEYS[index + 1].t) index++;
+ const a = KEYS[index];
+ const b = KEYS[index + 1];
+ const local = clamp((warped - a.t) / (b.t - a.t), 0, 1);
+ const u = (index + local) / last;
+ this.positions.getPoint(u, this.pos);
+ this.targets.getPoint(u, this.target);
+
+ // The light the film follows pulls the look-at point onto itself in transit.
+ const follow = lerp(a.follow ?? 0, b.follow ?? 0, local);
+ if (follow > 0) this.target.lerp(this.signal.position(t, light), follow);
+
+ const fa = this.framings[index];
+ const fb = this.framings[index + 1];
+ const fov = lerp(a.fov ?? FOV, b.fov ?? FOV, local);
+ const span = lerp(fa.span, fb.span, local);
+ const rise = lerp(fa.rise, fb.rise, local);
+ // Density is interpolated in log space: the overview is ten times clearer
+ // than a close-up, and a linear blend would hide it until the last moment.
+ this.fog = Math.exp(lerp(Math.log(a.fog), Math.log(b.fog), local));
+
+ // Pull the camera back until the subject fits the focus area both ways.
+ const distance = this.pos.distanceTo(this.target);
+ const visibleHeight = 2 * distance * Math.tan(MathUtils.degToRad(fov) / 2);
+ const visibleWidth = (visibleHeight * this.width) / Math.max(this.height, 1);
+ const fitWidth = span / Math.max(visibleWidth * (this.focus.width / this.width), 1e-3);
+ const fitHeight = rise / Math.max(visibleHeight * (this.focus.height / this.height), 1e-3);
+ const fit = clamp(Math.max(fitWidth, fitHeight), 0.82, 4);
+ this.pos.sub(this.target).multiplyScalar(fit).add(this.target);
+ // Fog is tuned for a wide screen. A narrow one makes the camera stand
+ // further back, so the haze thins by the same factor and the subject keeps
+ // its brightness.
+ this.fog *= clamp(1.3 / fit, 0.4, 1);
+
+ if (!still) {
+ // Slow sway in the overview; elsewhere a barely perceptible drift.
+ const orbit = finale * Math.sin(time * 0.12) * 0.12;
+ if (orbit !== 0) {
+ tmp.copy(this.pos).sub(this.target);
+ const cos = Math.cos(orbit);
+ const sin = Math.sin(orbit);
+ this.pos.set(
+ this.target.x + tmp.x * cos + tmp.z * sin,
+ this.pos.y,
+ this.target.z - tmp.x * sin + tmp.z * cos,
+ );
+ }
+ const scale = this.pos.distanceTo(this.target) / 16;
+ const k = 1 - Math.exp(-dt * 3.2);
+ this.pointer.x += (this.pointer.tx - this.pointer.x) * k;
+ this.pointer.y += (this.pointer.ty - this.pointer.y) * k;
+ tmp.copy(this.target).sub(this.pos).normalize();
+ right.crossVectors(tmp, up.set(0, 1, 0)).normalize();
+ up.crossVectors(right, tmp);
+ const dx = (Math.sin(time * 0.23) * 0.16 + this.pointer.x * 0.5) * scale;
+ const dy = (Math.sin(time * 0.31 + 1.3) * 0.09 - this.pointer.y * 0.28) * scale;
+ this.pos.addScaledVector(right, dx).addScaledVector(up, dy);
+ }
+
+ this.camera.position.copy(this.pos);
+ this.camera.lookAt(this.target);
+ if (Math.abs(this.camera.fov - fov) > 1e-3) this.applyProjection(fov);
+ }
+}
diff --git a/app/components/campaign/scene/shell.ts b/app/components/campaign/scene/shell.ts
new file mode 100644
index 0000000..f215eb3
--- /dev/null
+++ b/app/components/campaign/scene/shell.ts
@@ -0,0 +1,291 @@
+// Everything that spans the levels: the link from the phone and the spine down
+// the machine, the machine's outline, dust for parallax, the light the camera
+// follows, and the captions of the closing overview.
+
+import {
+ AdditiveBlending,
+ BufferAttribute,
+ BufferGeometry,
+ Color,
+ Group,
+ Line,
+ LineBasicMaterial,
+ LineSegments,
+ Points,
+ Sprite,
+ Vector3,
+} from "three";
+import { CUE } from "./film";
+import { Fader, glowSpriteMaterial, lineMaterial, pointsMaterial } from "./materials";
+import { hex } from "./palette";
+import { envelope, fract, lerp, mulberry32, smoothstep } from "./util";
+import { HEAP, PHONE, SERVER, TRUNK_TOP, Y, entryRoute, type Frame, type Kit, type Station } from "./world";
+
+const HALF = SERVER.half;
+const TOP = SERVER.top;
+const BOTTOM = SERVER.bottom;
+/** Seconds between samples of the light's tail. */
+const TAIL_STEP = 0.011;
+
+function segments(points: number[], material: LineBasicMaterial) {
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(points), 3));
+ const lines = new LineSegments(geometry, material);
+ lines.frustumCulled = false;
+ return lines;
+}
+
+function square(points: number[], y: number, half: number) {
+ const corners = [
+ [-half, -half],
+ [half, -half],
+ [half, half],
+ [-half, half],
+ ];
+ for (let i = 0; i < 4; i++) {
+ const [x0, z0] = corners[i];
+ const [x1, z1] = corners[(i + 1) % 4];
+ points.push(x0, y, z0, x1, y, z1);
+ }
+}
+
+export interface Shell extends Station {
+ /** Colour of the backdrop glow for the current part of the film. */
+ glow: Color;
+}
+
+export function createShell(kit: Kit): Shell {
+ const group = new Group();
+ const rng = mulberry32(21);
+ const glowTexture = kit.tex.glow();
+ const { signal } = kit;
+ const emerald = new Color(hex.emerald);
+ const sky = new Color(hex.sky);
+
+ /* Link and spine: emerald from the phone to the gateway, sky below it. */
+ const spineBottom = Y.heap + HEAP.h / 2;
+ {
+ const route = entryRoute();
+ const points = route.link.getPoints(64);
+ points.push(route.front, route.heart);
+ const steps = 36;
+ for (let i = 1; i <= steps; i++) points.push(new Vector3(0, lerp(TRUNK_TOP, spineBottom, i / steps), 0));
+ const positions = new Float32Array(points.length * 3);
+ const colors = new Float32Array(points.length * 3);
+ const top = new Color(hex.emeraldDeep);
+ const bottom = new Color(hex.skyDeep);
+ const mixed = new Color();
+ points.forEach((point, i) => {
+ point.toArray(positions, i * 3);
+ mixed.copy(top).lerp(bottom, smoothstep(Y.gateway + 0.6, Y.gateway - 0.6, point.y));
+ mixed.toArray(colors, i * 3);
+ });
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
+ geometry.setAttribute("color", new BufferAttribute(colors, 3));
+ const line = new Line(
+ geometry,
+ new LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.42, depthWrite: false, blending: AdditiveBlending }),
+ );
+ line.frustumCulled = false;
+ group.add(line);
+ }
+
+ /* Other requests on the spine, shown only in the overview. */
+ const trafficFader = new Fader();
+ const trafficCount = 7;
+ const trafficPositions = new Float32Array(trafficCount * 3);
+ const trafficColors = new Float32Array(trafficCount * 3);
+ const trafficAlpha = new Float32Array(trafficCount);
+ const trafficGeometry = new BufferGeometry();
+ trafficGeometry.setAttribute("position", new BufferAttribute(trafficPositions, 3));
+ trafficGeometry.setAttribute("aColor", new BufferAttribute(trafficColors, 3));
+ trafficGeometry.setAttribute("aAlpha", new BufferAttribute(trafficAlpha, 1));
+ trafficGeometry.setAttribute("aSize", new BufferAttribute(new Float32Array(trafficCount).fill(0.5), 1));
+ const traffic = new Points(trafficGeometry, trafficFader.add(pointsMaterial()));
+ traffic.frustumCulled = false;
+ group.add(traffic);
+
+ /* The machine: edges, level plates and corner brackets. */
+ const shellFader = new Fader();
+ {
+ const edges: number[] = [];
+ square(edges, TOP, HALF);
+ square(edges, BOTTOM, HALF);
+ for (const [x, z] of [
+ [-HALF, -HALF],
+ [HALF, -HALF],
+ [HALF, HALF],
+ [-HALF, HALF],
+ ]) {
+ edges.push(x, TOP, z, x, BOTTOM, z);
+ }
+ group.add(segments(edges, shellFader.add(lineMaterial(0x1f5878, 0.34))));
+
+ const plates: number[] = [];
+ for (const y of [(Y.gateway + Y.vector) / 2, (Y.vector + Y.index) / 2, (Y.index + Y.heap) / 2]) {
+ square(plates, y, HALF);
+ square(plates, y, HALF * 0.62);
+ }
+ group.add(segments(plates, shellFader.add(lineMaterial(0x1a4a66, 0.24))));
+
+ const brackets: number[] = [];
+ const reach = 1.8;
+ for (const y of [TOP, BOTTOM]) {
+ for (const sx of [-1, 1]) {
+ for (const sz of [-1, 1]) {
+ const x = sx * HALF;
+ const z = sz * HALF;
+ brackets.push(x, y, z, x - sx * reach, y, z);
+ brackets.push(x, y, z, x, y, z - sz * reach);
+ brackets.push(x, y, z, x, y + (y === TOP ? -reach : reach), z);
+ }
+ }
+ }
+ group.add(segments(brackets, shellFader.add(lineMaterial(hex.sky, 0.6))));
+ }
+
+ /* Dust: faint motes so camera travel has parallax. */
+ const dustFader = new Fader();
+ {
+ const count = kit.low ? 520 : 1300;
+ const positions = new Float32Array(count * 3);
+ const colors = new Float32Array(count * 3);
+ const alpha = new Float32Array(count);
+ const size = new Float32Array(count);
+ const tints = [new Color(hex.sky), new Color(hex.emerald), new Color(hex.ink), new Color(hex.violet)];
+ for (let i = 0; i < count; i++) {
+ const radius = 2.5 + Math.sqrt(rng()) * 19;
+ const angle = rng() * Math.PI * 2;
+ positions.set([Math.cos(angle) * radius, lerp(9, BOTTOM - 6, rng()), Math.sin(angle) * radius], i * 3);
+ tints[Math.floor(rng() * (rng() < 0.2 ? 4 : 3))].toArray(colors, i * 3);
+ alpha[i] = 0.18 + rng() * 0.5;
+ size[i] = 0.05 + rng() * rng() * 0.16;
+ }
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
+ geometry.setAttribute("aColor", new BufferAttribute(colors, 3));
+ geometry.setAttribute("aAlpha", new BufferAttribute(alpha, 1));
+ geometry.setAttribute("aSize", new BufferAttribute(size, 1));
+ const dust = new Points(geometry, dustFader.add(pointsMaterial({ drift: 0.4 })));
+ dust.frustumCulled = false;
+ group.add(dust);
+ }
+
+ /* The light: a glow, a white core and a tail along the way it came. */
+ const lightGlow = new Sprite(glowSpriteMaterial(glowTexture, hex.emerald, 0));
+ const lightCore = new Sprite(glowSpriteMaterial(glowTexture, 0xffffff, 0));
+ lightGlow.renderOrder = 30;
+ lightCore.renderOrder = 31;
+ group.add(lightGlow, lightCore);
+ const tailSteps = 28;
+ const tailPositions = new Float32Array(tailSteps * 3);
+ const tailColors = new Float32Array(tailSteps * 3);
+ const tailGeometry = new BufferGeometry();
+ tailGeometry.setAttribute("position", new BufferAttribute(tailPositions, 3));
+ tailGeometry.setAttribute("color", new BufferAttribute(tailColors, 3));
+ const tail = new Line(
+ tailGeometry,
+ new LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 1, depthWrite: false, blending: AdditiveBlending }),
+ );
+ tail.frustumCulled = false;
+ group.add(tail);
+ const lightColor = new Color();
+ const scratch = new Vector3();
+
+ /* Layer captions for the overview. */
+ const captionFader = new Fader();
+ const captions: [number, string, string, "emerald" | "sky" | "violet"][] = [
+ [PHONE.y + 0.4, "YOUR APP", "DocumentDB API", "emerald"],
+ [Y.gateway, "GATEWAY", "wire protocol · :10260", "emerald"],
+ [Y.vector, "VECTOR + GEO", "pgvector · PostGIS", "violet"],
+ [Y.index, "INDEXES", "PostgreSQL B-tree · RUM", "sky"],
+ [Y.heap, "HEAP + MVCC", "PostgreSQL rows · WAL", "sky"],
+ ];
+ {
+ const leaders: number[] = [];
+ for (const [y, title, sub, color] of captions) {
+ const label = kit.tex.label(title, 3.3, { color, sub, pill: false });
+ label.position.set(HALF + 3.2, y, 0);
+ captionFader.add(label.material);
+ group.add(label);
+ leaders.push(HALF + 0.4, y, 0, HALF + 2.8, y, 0);
+ }
+ group.add(segments(leaders, captionFader.add(lineMaterial(hex.sky, 0.55))));
+ }
+
+ // Backdrop tint for each part of the film: [time, colour].
+ const backdrop: [number, Color][] = [
+ [0, new Color(0x30445a)],
+ [6.9, new Color(0x0a3038)],
+ [9.9, new Color(0x08332c)],
+ [13.7, new Color(0x0a2c36)],
+ [16.8, new Color(0x0c2140)],
+ [22.3, new Color(0x0c2140)],
+ [23.4, new Color(0x0a2c36)],
+ [26.2, new Color(0x1c1a44)],
+ [28.6, new Color(0x1c1a44)],
+ [30.3, new Color(0x0a2233)],
+ [32, new Color(0x0a2233)],
+ [33.8, new Color(0x30445a)],
+ ];
+ const glow = new Color();
+
+ return {
+ group,
+ glow,
+ update(frame: Frame) {
+ const { t, time, finale } = frame;
+
+ let stop = 0;
+ while (stop < backdrop.length - 2 && t >= backdrop[stop + 1][0]) stop++;
+ const [from, fromColor] = backdrop[stop];
+ const [to, toColor] = backdrop[stop + 1];
+ glow.copy(fromColor).lerp(toColor, smoothstep(from, to, t));
+
+ // The machine's outline appears as the light enters it and stays to the end.
+ const inside = envelope(t, CUE.roof - 0.4, CUE.aboveRing, 32.6, 33.6);
+ shellFader.set(Math.max(inside, finale));
+ // Around the phone the backdrop is a plain studio wall: hardly any dust.
+ const studio = 1 - envelope(t, CUE.depart, CUE.mouth, 32.3, 33.4);
+ dustFader.set((1 - finale * 0.45) * (1 - studio * 0.85));
+ captionFader.set(smoothstep(0.55, 1, finale));
+
+ trafficFader.set(finale);
+ for (let i = 0; i < trafficCount; i++) {
+ const u = fract(time * 0.085 + i / trafficCount);
+ const y = lerp(TRUNK_TOP, spineBottom, u);
+ trafficPositions.set([0, y, 0], i * 3);
+ lightColor.copy(emerald).lerp(sky, smoothstep(Y.gateway + 0.4, Y.gateway - 0.4, y));
+ lightColor.toArray(trafficColors, i * 3);
+ trafficAlpha[i] = Math.sqrt(Math.max(Math.sin(Math.PI * u), 0)) * 0.6;
+ }
+ trafficGeometry.attributes.position.needsUpdate = true;
+ trafficGeometry.attributes.aColor.needsUpdate = true;
+ trafficGeometry.attributes.aAlpha.needsUpdate = true;
+
+ // The light and its tail.
+ const visible = signal.presence(t);
+ signal.position(t, lightGlow.position);
+ lightCore.position.copy(lightGlow.position);
+ lightColor.copy(emerald).lerp(sky, signal.side(t));
+ lightGlow.material.color.copy(lightColor);
+ const size = signal.size(t);
+ lightGlow.scale.setScalar(size);
+ lightCore.scale.setScalar(size * 0.3);
+ lightGlow.material.opacity = visible * 0.85;
+ lightCore.material.opacity = visible;
+ // The tail never reaches back past the start of the current trip.
+ const since = t >= CUE.reply ? CUE.reply : CUE.depart;
+ for (let i = 0; i < tailSteps; i++) {
+ const u = i / (tailSteps - 1);
+ signal.position(Math.max(since, t - i * TAIL_STEP), scratch).toArray(tailPositions, i * 3);
+ const fade = (1 - u) ** 2 * visible;
+ tailColors.set([lightColor.r * fade, lightColor.g * fade, lightColor.b * fade], i * 3);
+ }
+ tailGeometry.attributes.position.needsUpdate = true;
+ tailGeometry.attributes.color.needsUpdate = true;
+ tail.visible = visible > 0.01;
+ },
+ };
+}
diff --git a/app/components/campaign/scene/signal.ts b/app/components/campaign/scene/signal.ts
new file mode 100644
index 0000000..b1c119e
--- /dev/null
+++ b/app/components/campaign/scene/signal.ts
@@ -0,0 +1,120 @@
+// The light the camera follows: the update on its way from the phone to the
+// row it changes, and later the reply on its way back. Its position is a pure
+// function of film time, so the camera, the stations and the tests all agree
+// on where it is in any frame.
+
+import { CatmullRomCurve3, LineCurve3, QuadraticBezierCurve3, Vector3, type Curve } from "three";
+import { CUE } from "./film";
+import { clamp, lerp, smoothstep } from "./util";
+import { DOC, HEAP, PHONE, Y, entryRoute, pkLookupPath, pointerX } from "./world";
+
+type Ease = (u: number) => number;
+const linear: Ease = (u) => u;
+const easeIn: Ease = (u) => u * u;
+const easeOut: Ease = (u) => 1 - (1 - u) * (1 - u);
+const easeInOut: Ease = (u) => u * u * (3 - 2 * u);
+
+interface Leg {
+ from: number;
+ to: number;
+ curve: Curve;
+ ease: Ease;
+}
+
+const v = (x: number, y: number, z: number) => new Vector3(x, y, z);
+const line = (a: Vector3, b: Vector3) => new LineCurve3(a, b);
+
+export class Signal {
+ private readonly legs: Leg[];
+
+ constructor() {
+ const { link, mouth, front, heart } = entryRoute();
+ const ribbon = v(PHONE.x + DOC.bson.x, PHONE.y + DOC.bson.y, PHONE.z + DOC.bson.z);
+ const edge = link.getPoint(0);
+ const ring = Y.gateway;
+ // In front of the trees and the page, so it is never hidden by them.
+ const pk = pkLookupPath().map((point) => point.setZ(0.25));
+ const pointer = v(pointerX(HEAP.oldPointer), Y.heap + HEAP.pointerY, HEAP.z + 0.1);
+ const tuple = v(-2.3, Y.heap + HEAP.oldY, HEAP.z + 0.1);
+ const pageTop = v(0, Y.heap + HEAP.h / 2, 0);
+
+ this.legs = [
+ /* The update: out of the phone, down to the hall, along the aisle, into the rack. */
+ { from: CUE.depart, to: CUE.phoneEdge, curve: new QuadraticBezierCurve3(ribbon, v(0.95, ribbon.y - 0.7, PHONE.z + 0.5), edge), ease: easeInOut },
+ { from: CUE.phoneEdge, to: CUE.mouth, curve: link, ease: easeIn },
+ { from: CUE.mouth, to: CUE.roof, curve: line(mouth, front), ease: linear },
+ { from: CUE.roof, to: CUE.roof + 0.12, curve: line(front, heart), ease: linear },
+ { from: CUE.roof + 0.12, to: CUE.aboveRing, curve: line(heart, v(0, ring + 2.7, 0)), ease: easeOut },
+ /* It waits above the gateway as a document command, crosses, and waits below as SQL. */
+ { from: CUE.aboveRing, to: CUE.dive, curve: line(v(0, ring + 2.7, 0), v(0, ring + 1.5, 0)), ease: linear },
+ { from: CUE.dive, to: CUE.cross, curve: line(v(0, ring + 1.5, 0), v(0, ring, 0)), ease: easeIn },
+ { from: CUE.cross, to: CUE.belowRing, curve: line(v(0, ring, 0), v(0, ring - 1.5, 0)), ease: easeOut },
+ { from: CUE.belowRing, to: CUE.leaveRing, curve: line(v(0, ring - 1.5, 0), v(0, ring - 2.3, 0)), ease: linear },
+ /* Past the vector level to the root of the primary-key B-tree. */
+ {
+ from: CUE.leaveRing,
+ to: CUE.root,
+ curve: new CatmullRomCurve3([v(0, ring - 2.3, 0), v(-0.7, -22.5, 3.4), v(-2.3, -30.5, 3.2), pk[0]]),
+ ease: easeInOut,
+ },
+ { from: CUE.root, to: CUE.inner, curve: line(pk[0], pk[1]), ease: easeInOut },
+ { from: CUE.inner, to: CUE.leaf, curve: line(pk[1], pk[2]), ease: easeInOut },
+ { from: CUE.leaf, to: CUE.row, curve: line(pk[2], pk[3]), ease: easeInOut },
+ /* The leaf's row pointer leads to a line pointer in the heap page, and that to the tuple. */
+ {
+ from: CUE.row,
+ to: CUE.linePointer,
+ curve: new CatmullRomCurve3([pk[3], v(-1.5, -43.2, 0.7), v(-1.6, -45.6, 0.4), pointer]),
+ ease: easeInOut,
+ },
+ { from: CUE.linePointer, to: CUE.tuple, curve: line(pointer, tuple), ease: easeInOut },
+
+ /* The reply: up the spine, through the gateway, back to the phone. */
+ { from: CUE.reply, to: CUE.replyGateway, curve: line(pageTop, v(0, ring, 0)), ease: easeIn },
+ { from: CUE.replyGateway, to: CUE.replyRoof, curve: line(v(0, ring, 0), heart), ease: linear },
+ { from: CUE.replyRoof, to: CUE.replyMouth, curve: line(heart, mouth), ease: linear },
+ { from: CUE.replyMouth, to: CUE.replyPhone, curve: new CatmullRomCurve3(link.points.slice().reverse()), ease: easeOut },
+ ];
+ }
+
+ /** Where the light is at film time `t`; between legs it rests where it last arrived. */
+ position(t: number, out: Vector3) {
+ const legs = this.legs;
+ if (t <= legs[0].from) return legs[0].curve.getPointAt(0, out);
+ for (let i = 0; i < legs.length; i++) {
+ const leg = legs[i];
+ if (t < leg.from) return legs[i - 1].curve.getPointAt(1, out);
+ if (t <= leg.to) {
+ return leg.curve.getPointAt(clamp(leg.ease((t - leg.from) / (leg.to - leg.from)), 0, 1), out);
+ }
+ }
+ return legs[legs.length - 1].curve.getPointAt(1, out);
+ }
+
+ /** 0 when there is nothing to see, 1 while the light is travelling. */
+ presence(t: number) {
+ const request = smoothstep(CUE.depart, CUE.depart + 0.12, t) * (1 - smoothstep(CUE.tuple, CUE.tuple + 0.25, t));
+ const reply = smoothstep(CUE.reply - 0.05, CUE.reply + 0.15, t) * (1 - smoothstep(CUE.replyPhone, CUE.replyPhone + 0.2, t));
+ return Math.max(request, reply);
+ }
+
+ /** 0 on the document side of the gateway, 1 on the PostgreSQL side. */
+ side(t: number) {
+ return t < (CUE.tuple + CUE.reply) / 2
+ ? smoothstep(CUE.cross - 0.05, CUE.cross + 0.12, t)
+ : 1 - smoothstep(CUE.replyGateway - 0.05, CUE.replyGateway + 0.12, t);
+ }
+
+ /** World-space size of the glow. */
+ size(t: number) {
+ if (t >= CUE.reply - 0.5) {
+ // Large enough to read from the overview, small again at the phone.
+ return lerp(3.3, 0.5, smoothstep(CUE.replyGateway, CUE.replyPhone, t));
+ }
+ const leaving = lerp(0.3, 0.44, smoothstep(CUE.depart, CUE.phoneEdge, t));
+ // Rack-sized in the hall, larger once it is inside the machine.
+ const entering = lerp(leaving, 0.8, smoothstep(CUE.phoneEdge, CUE.mouth, t));
+ const falling = lerp(entering, 1.5, smoothstep(CUE.roof, CUE.aboveRing, t));
+ return lerp(falling, 1.0, smoothstep(CUE.leaveRing, CUE.root, t));
+ }
+}
diff --git a/app/components/campaign/scene/stations/docStation.ts b/app/components/campaign/scene/stations/docStation.ts
new file mode 100644
index 0000000..8843582
--- /dev/null
+++ b/app/components/campaign/scene/stations/docStation.ts
@@ -0,0 +1,206 @@
+// "Inside the app": the product card on the phone is one document. It slides
+// out of the card as JSON, its array, location and embedding light up, the one
+// field this tap changes is marked, and then the whole document packs down to
+// the BSON bytes that actually leave the phone. Those bytes become the light
+// the camera follows for the rest of the film.
+
+import {
+ BufferAttribute,
+ BufferGeometry,
+ Group,
+ LineSegments,
+ Mesh,
+ PlaneGeometry,
+ Sprite,
+ Vector3,
+ type ShaderMaterial,
+} from "three";
+import { CUE } from "../film";
+import { glowSpriteMaterial, holoMaterial, lineMaterial, panelMaterial } from "../materials";
+import { CARD_UV, PRODUCT, STOCK_BEFORE } from "../mockups";
+import { hex } from "../palette";
+import type { Tok } from "../textures";
+import { lerp, pulse, smoothstep } from "../util";
+import { DOC, PHONE, type Frame, type Kit, type Station } from "../world";
+
+const p = (text: string): Tok => [text, "punct"];
+const k = (text: string): Tok => [text, "key"];
+const s = (text: string): Tok => [text, "string"];
+const n = (text: string): Tok => [text, "number"];
+
+const STOCK_PREFIX = [p(" "), k('"stock"'), p(": { "), k('"store"'), p(": "), s('"SEA-1"'), p(", "), k('"qty"'), p(": ")];
+
+// The example document. With a 128-float embedding its BSON encoding is 1,776
+// bytes; the hex further down is the real start of that encoding.
+const DOCUMENT: Tok[][] = [
+ [p("{")],
+ [p(" "), k('"_id"'), p(": "), ["ObjectId", "fn"], p("("), s('"6741c0de…6f70"'), p("),")],
+ [p(" "), k('"name"'), p(": "), s(`"${PRODUCT.name}"`), p(",")],
+ [p(" "), k('"price"'), p(": "), n("129"), p(",")],
+ [p(" "), k('"tags"'), p(": ["), s('"trail"'), p(", "), s('"shoes"'), p(", "), s('"new"'), p("],")],
+ [...STOCK_PREFIX, n(String(STOCK_BEFORE)), p(" },")],
+ [p(" "), k('"geo"'), p(": { "), k('"type"'), p(": "), s('"Point"'), p(", "), k('"coordinates"'), p(":")],
+ [p(" ["), n("-122.33"), p(", "), n("47.61"), p("] },")],
+ [p(" "), k('"embedding"'), p(": ["), n("0.12"), p(", "), n("-0.48"), p(", "), n("0.91"), p(", … ]")],
+ [p("}")],
+];
+const ROW = { tags: 4, stock: 5, geo: 6, embedding: 8 };
+/** Column of the stock count on its line. */
+const QTY_COLUMN = STOCK_PREFIX.reduce((sum, [text]) => sum + text.length, 0);
+
+// f0 06 00 00 is the length, 1776; then _id, then the name, byte for byte.
+const BSON: Tok[][] = [
+ [n("f0 06 00 00"), [" 07", "fn"], k(" 5f 69 64 00"), s(" 67 41 c0 de 9f 1b 2a 3c 4d 5e 6f 70")],
+ [["02", "fn"], k(" 6e 61 6d 65 00"), n(" 0b 00 00 00"), s(" 54 72 61 69 6c 79 20 52 75 6e 00"), p(" …")],
+];
+
+export function createDocStation(kit: Kit): Station {
+ const group = new Group();
+ group.position.set(PHONE.x, PHONE.y, PHONE.z);
+
+ /* The document, as the application's driver sees it. */
+ const json = kit.tex.code(DOCUMENT, { title: "shop.products · one document", titleColor: "emerald", fontPx: 30 });
+ const jsonW = 2.4;
+ const jsonH = jsonW / json.aspect;
+ const jsonMesh: Mesh = new Mesh(
+ new PlaneGeometry(jsonW, jsonH),
+ panelMaterial({ map: json.texture, size: [jsonW, jsonH], radius: 0.07, border: hex.emerald, borderWidth: 1.2, bright: 1.08 }),
+ );
+ jsonMesh.renderOrder = 10;
+ group.add(jsonMesh);
+
+ // It starts where the card is drawn on the phone's screen.
+ const cardHome = new Vector3((CARD_UV.u + CARD_UV.w / 2 - 0.5) * PHONE.w, (0.5 - CARD_UV.v - CARD_UV.h / 2) * PHONE.h, 0.06);
+ const cardEdgeX = cardHome.x + (CARD_UV.w * PHONE.w) / 2;
+
+ /* Outlines over the parts a relational row would have needed more tables for. */
+ const lineY = (row: number) => (0.5 - json.lineV(row)) * jsonH;
+ const lineH = json.lineHeightV * jsonH;
+ const marker = (rows: [number, number], color: number, at: number) => {
+ const endU = Math.max(json.lineEndU(rows[0]), json.lineEndU(rows[1]));
+ const width = (endU - json.startU) * jsonW + 0.09;
+ const height = lineH * (rows[1] - rows[0] + 1) - 0.012;
+ const mesh = new Mesh(
+ new PlaneGeometry(width, height),
+ holoMaterial({ color, fill: 0.09, line: 0.6, glow: 0.3, opacity: 0 }),
+ );
+ mesh.position.set((json.startU - 0.5) * jsonW + width / 2 - 0.045, (lineY(rows[0]) + lineY(rows[1])) / 2, 0.012);
+ mesh.renderOrder = 11;
+ jsonMesh.add(mesh);
+ return { mesh, at };
+ };
+ const markers = [
+ marker([ROW.tags, ROW.tags], hex.emerald, CUE.fieldTags),
+ marker([ROW.geo, ROW.geo + 1], hex.emerald, CUE.fieldGeo),
+ marker([ROW.embedding, ROW.embedding], hex.violet, CUE.fieldEmbedding),
+ ];
+
+ /* The field this tap changes, and the change itself. */
+ const qtyX = (json.startU + (QTY_COLUMN + 0.5) * json.charU - 0.5) * jsonW;
+ const qtyBox = new Mesh(
+ new PlaneGeometry(json.charU * jsonW * 2.1, lineH * 0.92),
+ holoMaterial({ color: hex.amber, fill: 0.16, line: 0.8, glow: 0.4, opacity: 0 }),
+ );
+ qtyBox.position.set(qtyX, lineY(ROW.stock), 0.014);
+ qtyBox.renderOrder = 12;
+ jsonMesh.add(qtyBox);
+
+ const change = kit.tex.label('$inc "stock.qty": -1', 0.17, {
+ color: "amber",
+ sub: "the one change this tap makes",
+ pill: true,
+ align: "center",
+ });
+ const changeY = jsonH / 2 + 0.3;
+ change.position.set(Math.min(qtyX, jsonW / 2 - change.scale.x / 2), changeY, 0.02);
+ change.renderOrder = 22;
+ jsonMesh.add(change);
+ const leaderMaterial = lineMaterial(hex.amber, 0);
+ const leader = new LineSegments(
+ new BufferGeometry().setFromPoints([
+ new Vector3(qtyX, changeY - change.scale.y / 2, 0.016),
+ new Vector3(qtyX, lineY(ROW.stock) + lineH * 0.5, 0.016),
+ ]),
+ leaderMaterial,
+ );
+ jsonMesh.add(leader);
+
+ /* The bytes that actually leave the application. */
+ const bson = kit.tex.code(BSON, { title: "as BSON · 1,776 bytes", titleColor: "sky", fontPx: 26 });
+ const bsonW = 2.4;
+ const bsonH = bsonW / bson.aspect;
+ const bsonMesh: Mesh = new Mesh(
+ new PlaneGeometry(bsonW, bsonH),
+ panelMaterial({ map: bson.texture, size: [bsonW, bsonH], radius: 0.06, border: hex.sky, borderWidth: 1.2, bright: 1.08 }),
+ );
+ bsonMesh.renderOrder = 13;
+ group.add(bsonMesh);
+
+ // A spark where the ribbon closes, handing over to the travelling light.
+ const spark = new Sprite(glowSpriteMaterial(kit.tex.glow(), hex.emerald, 0));
+ spark.position.copy(DOC.bson);
+ spark.renderOrder = 30;
+ group.add(spark);
+
+ /* Card → document connector. */
+ const linkPositions = new Float32Array(6);
+ const linkGeometry = new BufferGeometry();
+ linkGeometry.setAttribute("position", new BufferAttribute(linkPositions, 3));
+ const linkMaterial = lineMaterial(hex.emerald, 0);
+ const link = new LineSegments(linkGeometry, linkMaterial);
+ link.frustumCulled = false;
+ group.add(link);
+
+ const position = new Vector3();
+
+ return {
+ group,
+ update(frame: Frame) {
+ const { t } = frame;
+ group.visible = t > CUE.docOut - 0.05 && t < CUE.depart + 0.2;
+ if (!group.visible) return;
+
+ const out = smoothstep(CUE.docOut, CUE.docOpen, t);
+ const packing = smoothstep(CUE.pack, CUE.pack + 0.42, t);
+ const closing = smoothstep(CUE.depart - 0.3, CUE.depart, t);
+
+ // The document slides out of the card and grows to reading size, then
+ // folds flat onto the ribbon below it.
+ position.lerpVectors(cardHome, DOC.json, out);
+ position.y = lerp(position.y, DOC.bson.y + bsonH / 2, packing);
+ jsonMesh.position.copy(position);
+ const scale = lerp(0.28, 1, out);
+ jsonMesh.scale.set(scale, scale * lerp(1, 0.03, packing), 1);
+ const shown = out * (1 - packing ** 1.4);
+ jsonMesh.material.uniforms.uOpacity.value = shown;
+ jsonMesh.visible = shown > 0.002;
+
+ for (const { mesh, at } of markers) {
+ mesh.material.uniforms.uOpacity.value = shown * smoothstep(at, at + 0.18, t) * (0.7 + 0.6 * pulse(t, at, 3.5));
+ }
+ const marked = smoothstep(CUE.fieldStock, CUE.fieldStock + 0.2, t);
+ qtyBox.material.uniforms.uOpacity.value = shown * marked * (0.8 + 0.5 * pulse(t, CUE.fieldStock, 3));
+ change.material.opacity = shown * marked * (1 - packing);
+ leaderMaterial.opacity = shown * marked * 0.9;
+
+ // The ribbon drops out from under the document, brightens as the
+ // document folds into it, and closes to a point.
+ const ribbon = smoothstep(CUE.bson, CUE.bson + 0.45, t);
+ bsonMesh.position.set(DOC.bson.x, lerp(DOC.json.y - jsonH / 2 + bsonH / 2, DOC.bson.y, ribbon), DOC.bson.z);
+ bsonMesh.scale.set(lerp(1, 0.02, closing), lerp(1, 0.4, closing), 1);
+ bsonMesh.material.uniforms.uOpacity.value = ribbon * (1 - smoothstep(CUE.depart - 0.06, CUE.depart + 0.04, t));
+ bsonMesh.material.uniforms.uBright.value = 1.08 + packing * 0.7 + closing * 1.2;
+ bsonMesh.visible = ribbon > 0.002;
+
+ const handover = closing * (1 - smoothstep(CUE.depart, CUE.depart + 0.18, t));
+ spark.material.opacity = handover;
+ spark.scale.setScalar(0.3 + closing * 0.25);
+
+ // Card → document: drawn once the document has cleared the phone.
+ const left = jsonMesh.position.x - (jsonW / 2) * scale;
+ linkPositions.set([cardEdgeX, cardHome.y, 0.03, left, jsonMesh.position.y, jsonMesh.position.z]);
+ linkGeometry.attributes.position.needsUpdate = true;
+ linkMaterial.opacity = 0.75 * smoothstep(0.75, 1, out) * (1 - packing);
+ },
+ };
+}
diff --git a/app/components/campaign/scene/stations/gatewayStation.ts b/app/components/campaign/scene/stations/gatewayStation.ts
new file mode 100644
index 0000000..1577712
--- /dev/null
+++ b/app/components/campaign/scene/stations/gatewayStation.ts
@@ -0,0 +1,221 @@
+// The gateway: the port in the top of the server. The update arrives from
+// above as a document command, crosses the ring, and leaves below as the exact
+// statement the gateway issues for it (pg_documentdb_gw, query_catalog.rs).
+// Other commands keep passing through more faintly around it.
+
+import {
+ AdditiveBlending,
+ BoxGeometry,
+ BufferAttribute,
+ BufferGeometry,
+ Color,
+ Group,
+ InstancedMesh,
+ LineSegments,
+ Matrix4,
+ Mesh,
+ MeshBasicMaterial,
+ PlaneGeometry,
+ Quaternion,
+ Sprite,
+ TorusGeometry,
+ Vector3,
+} from "three";
+import { CUE } from "../film";
+import { Fader, glowSpriteMaterial, holoMaterial, lineMaterial, rippleMaterial } from "../materials";
+import { hex } from "../palette";
+import { envelope, fract, lerp, pulse, smoothstep } from "../util";
+import { Y, type Frame, type Kit, type Station } from "../world";
+
+const RADIUS = 2.7;
+
+// Background traffic: what other drivers send, and what it becomes.
+const TRAFFIC: [string, string][] = [
+ ["find", "documentdb_api.find_cursor_first_page(…)"],
+ ["insert", "documentdb_api.insert_txn_proc(…)"],
+ ["aggregate", "documentdb_api.aggregate_cursor_first_page(…)"],
+];
+
+export function createGatewayStation(kit: Kit): Station {
+ const group = new Group();
+ group.position.set(0, Y.gateway, 0);
+ const fader = new Fader();
+
+ /* The port: two rings with a rippling membrane between them. */
+ const torus = new TorusGeometry(RADIUS, 0.03, 10, 144);
+ torus.rotateX(Math.PI / 2);
+ const ringMaterial = (color: number) =>
+ fader.add(
+ new MeshBasicMaterial({
+ color,
+ transparent: true,
+ opacity: 0.95,
+ depthWrite: false,
+ blending: AdditiveBlending,
+ }),
+ );
+ const upper = new Mesh(torus, ringMaterial(hex.emerald));
+ upper.position.y = 0.18;
+ const lower = new Mesh(torus, ringMaterial(hex.sky));
+ lower.position.y = -0.18;
+ const membrane = new Mesh(new PlaneGeometry(RADIUS * 2, RADIUS * 2), fader.add(rippleMaterial(hex.emerald, hex.sky)));
+ membrane.rotation.x = -Math.PI / 2;
+ group.add(upper, lower, membrane);
+
+ /* A collar of segments turning slowly around the port. */
+ const segmentCount = 44;
+ const collar = new InstancedMesh(
+ new BoxGeometry(0.36, 0.1, 0.15),
+ fader.add(holoMaterial({ color: 0xffffff, fill: 0.08, line: 0.5, glow: 0.22 })),
+ segmentCount,
+ );
+ {
+ const matrix = new Matrix4();
+ const rotation = new Quaternion();
+ const up = new Vector3(0, 1, 0);
+ const one = new Vector3(1, 1, 1);
+ const position = new Vector3();
+ const bright = new Color(hex.sky).multiplyScalar(1.5);
+ const dim = new Color(hex.skyDeep).multiplyScalar(0.55);
+ for (let i = 0; i < segmentCount; i++) {
+ const angle = (i / segmentCount) * Math.PI * 2;
+ position.set(Math.cos(angle) * 3.4, 0, Math.sin(angle) * 3.4);
+ rotation.setFromAxisAngle(up, -angle + Math.PI / 2);
+ matrix.compose(position, rotation, one);
+ collar.setMatrixAt(i, matrix);
+ collar.setColorAt(i, i % 4 === 0 ? bright : dim);
+ }
+ }
+ group.add(collar);
+
+ {
+ const ticks: number[] = [];
+ for (let i = 0; i < 96; i++) {
+ const angle = (i / 96) * Math.PI * 2;
+ const inner = 3.8;
+ const outer = i % 8 === 0 ? 4.2 : 3.97;
+ ticks.push(Math.cos(angle) * inner, 0, Math.sin(angle) * inner, Math.cos(angle) * outer, 0, Math.sin(angle) * outer);
+ }
+ for (let i = 0; i < 128; i++) {
+ const a0 = (i / 128) * Math.PI * 2;
+ const a1 = ((i + 1) / 128) * Math.PI * 2;
+ ticks.push(Math.cos(a0) * 4.55, 0, Math.sin(a0) * 4.55, Math.cos(a1) * 4.55, 0, Math.sin(a1) * 4.55);
+ }
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(ticks), 3));
+ group.add(new LineSegments(geometry, fader.add(lineMaterial(hex.skyDeep, 0.4))));
+ }
+
+ /* Background traffic: commands above, statements below. */
+ const cards = TRAFFIC.map(([command, statement]) => {
+ const above = kit.tex.label(command, 0.42, { color: "emerald", pill: true, align: "center" });
+ const below = kit.tex.label(statement, 0.3, { color: "sky", pill: true, align: "center" });
+ const aboveScale = above.scale.clone();
+ const belowScale = below.scale.clone();
+ group.add(above, below);
+ return { above, below, aboveScale, belowScale };
+ });
+
+ /* The update the film follows, before and after the ring. */
+ const command = kit.tex.label("update", kit.compact ? 0.68 : 0.52, {
+ color: "emerald",
+ sub: '$inc "stock.qty": -1',
+ subColor: "ink",
+ pill: true,
+ align: "center",
+ });
+ // The statement exactly as the gateway sends it; abbreviated where it would not fit.
+ const statement = kit.compact
+ ? kit.tex.label("CALL documentdb_api.update_txn_proc(…)", 0.56, { color: "sky", pill: true, align: "center" })
+ : kit.tex.label("CALL documentdb_api.update_txn_proc($1, $2, $3, NULL)", 0.4, { color: "sky", pill: true, align: "center" });
+ command.renderOrder = 34;
+ statement.renderOrder = 34;
+ const commandScale = command.scale.clone();
+ const statementScale = statement.scale.clone();
+ group.add(command, statement);
+
+ const flash = new Sprite(glowSpriteMaterial(kit.tex.glow(), 0xffffff, 0));
+ flash.scale.setScalar(3.4);
+ group.add(flash);
+
+ /* Fixed captions on the camera side of the ring. */
+ const port = kit.tex.label("port 10260", kit.compact ? 0.56 : 0.44, { color: "emerald", pill: true, align: "center" });
+ port.position.set(-2.55, 0.62, 2.35);
+ const protocol = kit.tex.label("DocumentDB wire protocol", 0.42, {
+ color: "emerald",
+ sub: "OP_MSG · SCRAM-SHA-256 · TLS",
+ align: "right",
+ });
+ protocol.position.set(kit.compact ? 3.5 : 4.3, 2.3, -2.8);
+ const postgres = kit.tex.label("PostgreSQL", 0.42, {
+ color: "sky",
+ sub: "calls into documentdb_api",
+ align: "right",
+ });
+ postgres.position.set(kit.compact ? 3.7 : 5.1, kit.compact ? -3.3 : -2.6, -1.1);
+ group.add(port, protocol, postgres);
+
+ const light = new Vector3();
+
+ return {
+ group,
+ update(frame: Frame) {
+ const { t, time } = frame;
+ const w = Math.max(envelope(t, 8.9, 9.8, 13.2, 14.3), frame.finale);
+ group.visible = w > 0.002;
+ if (!group.visible) return;
+ fader.set(w);
+ collar.rotation.y = time * 0.1;
+ // Captions and SQL are unreadable from the overview distance; drop them.
+ const detail = w * (1 - frame.finale);
+ port.material.opacity = detail;
+ protocol.material.opacity = detail;
+ postgres.material.opacity = detail;
+
+ let heat = 0;
+ cards.forEach((card, i) => {
+ const u = fract(time * 0.07 + (i + 0.5) / cards.length);
+ const turn = (i * Math.PI * 2) / cards.length + 0.9;
+ const faint = detail * 0.42;
+
+ const down = u / 0.5;
+ const falling = down <= 1;
+ const radius = 2.2 * (1 - down) ** 1.25 + 0.5;
+ const angle = turn + down * 1.5;
+ card.above.position.set(Math.cos(angle) * radius, lerp(5.2, 0.3, down ** 1.3), Math.sin(angle) * radius - 0.6);
+ card.above.scale.copy(card.aboveScale).multiplyScalar(lerp(1, 0.3, smoothstep(0.55, 1, down)));
+ card.above.material.opacity = falling ? faint * smoothstep(0, 0.14, down) * (1 - smoothstep(0.8, 1, down)) : 0;
+
+ const out = (u - 0.5) / 0.5;
+ const leaving = out >= 0;
+ const spread = 0.5 + 2.4 * Math.max(out, 0) ** 0.9;
+ const exit = turn + 1.5 + out * 0.5;
+ card.below.position.set(Math.cos(exit) * spread, lerp(-0.35, -5.2, Math.max(out, 0) ** 0.85), Math.sin(exit) * spread - 0.6);
+ card.below.scale.copy(card.belowScale).multiplyScalar(lerp(0.3, 1, smoothstep(0, 0.4, out)));
+ card.below.material.opacity = leaving ? faint * smoothstep(0, 0.14, out) * (1 - smoothstep(0.75, 1, out)) : 0;
+
+ const crossing = (u - 0.5) / 0.035;
+ heat += Math.exp(-crossing * crossing) * 0.25;
+ });
+
+ // The followed update rides the light: a command above the ring, SQL below.
+ kit.signal.position(t, light).sub(group.position);
+ const arriving = smoothstep(CUE.roof + 0.2, CUE.aboveRing, t);
+ const entering = smoothstep(CUE.dive, CUE.cross - 0.03, t);
+ command.position.set(light.x, light.y + 0.05, light.z + 0.05);
+ command.scale.copy(commandScale).multiplyScalar(lerp(0.4, 1, arriving) * lerp(1, 0.25, entering));
+ command.material.opacity = detail * arriving * (1 - entering);
+
+ const emerging = smoothstep(CUE.cross + 0.03, CUE.belowRing, t);
+ const leaving = smoothstep(CUE.leaveRing, CUE.leaveRing + 0.75, t);
+ statement.position.set(light.x, light.y - 0.05, light.z + 0.05);
+ statement.scale.copy(statementScale).multiplyScalar(lerp(0.25, 1, emerging) * lerp(1, 0.55, leaving));
+ statement.material.opacity = detail * emerging * (1 - leaving);
+
+ heat += pulse(t, CUE.cross, 3.2) * (t < CUE.cross + 2 ? 1 : 0);
+ // The reply crosses the other way near the end of the film.
+ heat += pulse(t, CUE.replyGateway, 4) * 0.8;
+ flash.material.opacity = Math.min(heat, 1) * 0.85 * w;
+ },
+ };
+}
diff --git a/app/components/campaign/scene/stations/hallStation.ts b/app/components/campaign/scene/stations/hallStation.ts
new file mode 100644
index 0000000..7d9d551
--- /dev/null
+++ b/app/components/campaign/scene/stations/hallStation.ts
@@ -0,0 +1,233 @@
+// "To the backend": a hall of server racks under the phone. The light comes
+// down in front of an aisle, runs along it between the cabinets and enters the
+// one at the end. Everything below this station is the inside of that one
+// machine, drawn large.
+
+import {
+ BoxGeometry,
+ BufferAttribute,
+ BufferGeometry,
+ Color,
+ Group,
+ InstancedMesh,
+ LineSegments,
+ Matrix4,
+ Mesh,
+ MeshBasicMaterial,
+ PlaneGeometry,
+ Points,
+ Quaternion,
+ Sprite,
+ Vector3,
+} from "three";
+import { CUE } from "../film";
+import { Fader, glowSpriteMaterial, holoMaterial, lineMaterial, panelMaterial, pointsMaterial } from "../materials";
+import { css, hex } from "../palette";
+import { roundRect, type Ctx } from "../textures";
+import { envelope, mulberry32, pulse } from "../util";
+import { HALL, type Frame, type Kit, type Station } from "../world";
+
+const { w: RW, h: RH, d: RD } = HALL.rack;
+const FRONT_PX: [number, number] = [256, 580];
+const UNITS = 14;
+
+/** One cabinet's front: rack units with status lights, drive bays or vents. */
+function paintFront(ctx: Ctx, seed: number) {
+ const [w, h] = FRONT_PX;
+ const rng = mulberry32(seed);
+ ctx.fillStyle = "#050a12";
+ ctx.fillRect(0, 0, w, h);
+ const lights = [css.emerald, css.emerald, css.sky, css.sky, css.amber];
+ const pitch = (h - 24) / UNITS;
+ for (let unit = 0; unit < UNITS; unit++) {
+ const y = 12 + unit * pitch;
+ roundRect(ctx, 14, y + 2, w - 28, pitch - 5, 5);
+ ctx.fillStyle = "#0b1624";
+ ctx.fill();
+ ctx.strokeStyle = "#2a4c69";
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ for (let k = 0; k < 2; k++) {
+ ctx.globalAlpha = 0.45 + rng() * 0.55;
+ ctx.fillStyle = lights[Math.floor(rng() * lights.length)];
+ ctx.beginPath();
+ ctx.arc(30 + k * 15, y + pitch / 2, 4.4, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ ctx.globalAlpha = 1;
+ if (rng() < 0.55) {
+ ctx.fillStyle = "#17304a";
+ for (let bay = 0; bay < 8; bay++) ctx.fillRect(66 + bay * 21, y + 9, 15, pitch - 19);
+ } else {
+ ctx.strokeStyle = "#1a3550";
+ ctx.lineWidth = 2;
+ for (let vent = 0; vent < 13; vent++) {
+ ctx.beginPath();
+ ctx.moveTo(68 + vent * 13, y + 10);
+ ctx.lineTo(68 + vent * 13, y + pitch - 10);
+ ctx.stroke();
+ }
+ }
+ }
+}
+
+interface Rack {
+ /** Centre of the cabinet. */
+ position: Vector3;
+ /** Direction its front faces, as a rotation about y. */
+ facing: number;
+ /** How bright it is; the far rows are only there for depth. */
+ level: number;
+}
+
+export function createHallStation(kit: Kit): Station {
+ const group = new Group();
+ const fader = new Fader();
+ const rng = mulberry32(44);
+ const centreY = HALL.floor + RH / 2;
+
+ /* Cabinets: two rows facing each other across the aisle, two more behind them. */
+ const racks: Rack[] = [];
+ for (let i = 0; i < HALL.perRow; i++) {
+ const z = HALL.mouth - RW / 2 - 0.25 - i * (RW + 0.22);
+ for (const side of [-1, 1]) {
+ racks.push({ position: new Vector3(side * HALL.aisle, centreY, z), facing: (-side * Math.PI) / 2, level: 1 });
+ racks.push({ position: new Vector3(side * (HALL.aisle + 4.7), centreY, z), facing: (-side * Math.PI) / 2, level: 0.5 });
+ }
+ }
+ // The one at the end of the aisle is the machine the film goes into.
+ const target: Rack = { position: new Vector3(0, centreY, 0), facing: 0, level: 1.2 };
+
+ const boxes = new InstancedMesh(
+ new BoxGeometry(RW, RH, RD),
+ fader.add(holoMaterial({ color: 0xffffff, fill: 0.025, line: 0.6, glow: 0.14 })),
+ racks.length + 1,
+ );
+ // Solid, near-black bodies inside the outlines, so a cabinet hides what is behind it.
+ const bodyMaterial = fader.add(new MeshBasicMaterial({ color: 0x04080e, transparent: true }));
+ const bodies = new InstancedMesh(new BoxGeometry(RW - 0.03, RH - 0.03, RD - 0.03), bodyMaterial, racks.length + 1);
+ bodies.renderOrder = 1;
+ const fronts = [0, 1, 2].map((seed) => kit.tex.draw(FRONT_PX[0], FRONT_PX[1], (ctx) => paintFront(ctx, 31 + seed * 7)));
+ const frontGeometry = new PlaneGeometry(RW - 0.12, RH - 0.12);
+ const frontMaterials = fronts.map((map) =>
+ fader.add(panelMaterial({ map, size: [RW - 0.12, RH - 0.12], radius: 0.05, border: hex.skyDeep, borderWidth: 0.9, bright: 1.25 })),
+ );
+ const targetMaterial = fader.add(
+ panelMaterial({ map: fronts[0], size: [RW - 0.12, RH - 0.12], radius: 0.05, border: hex.emerald, borderWidth: 1.6, bright: 1.7 }),
+ );
+
+ const lights: number[] = [];
+ {
+ const matrix = new Matrix4();
+ const rotation = new Quaternion();
+ const up = new Vector3(0, 1, 0);
+ const one = new Vector3(1, 1, 1);
+ const normal = new Vector3();
+ const across = new Vector3();
+ const tint = new Color();
+ [...racks, target].forEach((rack, index) => {
+ rotation.setFromAxisAngle(up, rack.facing);
+ matrix.compose(rack.position, rotation, one);
+ boxes.setMatrixAt(index, matrix);
+ bodies.setMatrixAt(index, matrix);
+ boxes.setColorAt(index, tint.set(rack === target ? hex.emerald : hex.sky).multiplyScalar(rack.level));
+
+ normal.set(Math.sin(rack.facing), 0, Math.cos(rack.facing));
+ across.set(Math.cos(rack.facing), 0, -Math.sin(rack.facing));
+ const front = new Mesh(frontGeometry, rack === target ? targetMaterial : frontMaterials[index % frontMaterials.length]);
+ front.position.copy(rack.position).addScaledVector(normal, RD / 2 + 0.012);
+ front.rotation.y = rack.facing;
+ front.renderOrder = 3;
+ group.add(front);
+
+ // A few status lights per cabinet that blink on their own.
+ const count = rack.level < 1 ? 2 : 4;
+ for (let k = 0; k < count; k++) {
+ const unit = Math.floor(rng() * UNITS);
+ const y = rack.position.y + (RH - 0.12) * (0.5 - (12 + (unit + 0.5) * ((FRONT_PX[1] - 24) / UNITS)) / FRONT_PX[1]);
+ const x = (RW - 0.12) * ((30 + (rng() < 0.5 ? 0 : 15)) / FRONT_PX[0] - 0.5);
+ lights.push(
+ rack.position.x + normal.x * (RD / 2 + 0.03) + across.x * x,
+ y,
+ rack.position.z + normal.z * (RD / 2 + 0.03) + across.z * x,
+ );
+ }
+ });
+ }
+ boxes.frustumCulled = false;
+ boxes.renderOrder = 2;
+ bodies.frustumCulled = false;
+ group.add(bodies, boxes);
+
+ {
+ const count = lights.length / 3;
+ const colors = new Float32Array(count * 3);
+ const tints = [new Color(hex.emerald), new Color(hex.emerald), new Color(hex.sky), new Color(hex.amber)];
+ for (let i = 0; i < count; i++) tints[Math.floor(rng() * tints.length)].toArray(colors, i * 3);
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(lights), 3));
+ geometry.setAttribute("aColor", new BufferAttribute(colors, 3));
+ geometry.setAttribute("aAlpha", new BufferAttribute(new Float32Array(count).fill(1), 1));
+ geometry.setAttribute("aSize", new BufferAttribute(new Float32Array(count).fill(0.13), 1));
+ const leds = new Points(geometry, fader.add(pointsMaterial({ twinkle: 1 })));
+ leds.frustumCulled = false;
+ leds.renderOrder = 4;
+ group.add(leds);
+ }
+
+ /* Floor: a grid under the cabinets, with the aisle picked out. */
+ {
+ const y = HALL.floor;
+ const grid: number[] = [];
+ const halfX = HALL.aisle + 7.2;
+ const fromZ = -3;
+ const toZ = HALL.mouth + 4.5;
+ for (let x = -halfX; x <= halfX + 1e-3; x += 1.2) grid.push(x, y, fromZ, x, y, toZ);
+ for (let z = fromZ; z <= toZ + 1e-3; z += 1.2) grid.push(-halfX, y, z, halfX, y, z);
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(grid), 3));
+ group.add(new LineSegments(geometry, fader.add(lineMaterial(0x1d5a7c, 0.2))));
+
+ const edge = HALL.aisle - RD / 2 - 0.12;
+ const aisle = [-edge, y, RD / 2, -edge, y, toZ, edge, y, RD / 2, edge, y, toZ];
+ const aisleGeometry = new BufferGeometry();
+ aisleGeometry.setAttribute("position", new BufferAttribute(new Float32Array(aisle), 3));
+ group.add(new LineSegments(aisleGeometry, fader.add(lineMaterial(hex.emeraldDeep, 0.5))));
+ }
+
+ /* Where the light goes in, and whose machine it is. */
+ const port = new Sprite(glowSpriteMaterial(kit.tex.glow(), hex.emerald, 0));
+ port.position.set(0, HALL.port, RD / 2 + 0.05);
+ port.renderOrder = 28;
+ group.add(port);
+ const nameplate = kit.tex.label("DocumentDB", 0.46, {
+ color: "emerald",
+ sub: "gateway + PostgreSQL, one container",
+ align: "center",
+ mono: false,
+ });
+ nameplate.position.set(0, HALL.floor + RH + 0.62, RD / 2);
+ group.add(nameplate);
+
+ return {
+ group,
+ update(frame: Frame) {
+ const { t } = frame;
+ // Only on the way in and on the way home; the overview shows the stack alone.
+ // It also clears quickly once the light is inside the rack, because the
+ // camera then drops through the floor between the cabinets.
+ const w = Math.max(1 - envelope(t, CUE.roof + 0.05, CUE.roof + 0.7, 32.3, 33.2) - frame.finale, 0);
+ group.visible = w > 0.002;
+ if (!group.visible) return;
+ fader.set(w);
+ // Fading bodies must stop hiding what is behind them.
+ bodyMaterial.depthWrite = w > 0.98;
+
+ const entering = Math.max(pulse(t, CUE.roof, 2.6), pulse(t, CUE.replyRoof, 3.5));
+ targetMaterial.uniforms.uBright.value = 1.7 + entering * 1.6;
+ port.material.opacity = w * (0.35 + 0.65 * entering) * envelope(t, 7.4, 8.2, 10.2, 10.9);
+ port.scale.setScalar(0.9 + entering * 1.9);
+ nameplate.material.opacity = w * envelope(t, 7.5, 8.2, 9.0, 9.3);
+ },
+ };
+}
diff --git a/app/components/campaign/scene/stations/heapStation.ts b/app/components/campaign/scene/stations/heapStation.ts
new file mode 100644
index 0000000..83b52c0
--- /dev/null
+++ b/app/components/campaign/scene/stations/heapStation.ts
@@ -0,0 +1,501 @@
+// One 8 kB heap page of documentdb_data.documents_3, drawn the way PostgreSQL
+// lays it out: header, line pointers growing down, tuples growing up, free
+// space between. The update plays out on it once per loop:
+//
+// the light arrives at the product's row version,
+// the update writes a new version above it and stamps the old one's xmax,
+// another shopper's read that was already running still sees the old version,
+// the change goes to the write-ahead log before the reply is sent,
+// once nobody can see the old version, vacuum removes it.
+
+import {
+ AdditiveBlending,
+ BoxGeometry,
+ BufferAttribute,
+ BufferGeometry,
+ Color,
+ Group,
+ InstancedMesh,
+ Line,
+ LineSegments,
+ Matrix4,
+ Mesh,
+ MeshBasicMaterial,
+ PlaneGeometry,
+ QuadraticBezierCurve3,
+ Sprite,
+ Vector3,
+ type CanvasTexture,
+ type ShaderMaterial,
+} from "three";
+import { CUE } from "../film";
+import { Fader, glowSpriteMaterial, holoMaterial, lineMaterial, panelMaterial } from "../materials";
+import { STOCK_AFTER, STOCK_BEFORE } from "../mockups";
+import { css, hex } from "../palette";
+import { MONO, type Ctx } from "../textures";
+import { envelope, fract, lerp, pulse, smoothstep } from "../util";
+import { HEAP, HEAP_INNER, Y, pointerX, type Frame, type Kit, type Station } from "../world";
+
+const { w: W, h: H, tupleH } = HEAP;
+const INNER = HEAP_INNER;
+const TUPLE_PX: [number, number] = [1320, 150];
+const READER_PX: [number, number] = [470, 120];
+/** Transaction that wrote the version on the page, and the one that updates it. */
+const XID = { before: 1041, update: 1042 };
+
+interface TupleState {
+ xmin: number;
+ xmax: number;
+ oid: string;
+ /** Plain preview text, or the stock count drawn large. */
+ preview: string | number;
+ dead: boolean;
+}
+
+function paintTuple(ctx: Ctx, state: TupleState) {
+ const [w, h] = TUPLE_PX;
+ ctx.clearRect(0, 0, w, h);
+ ctx.fillStyle = state.dead ? "rgba(40,28,6,0.92)" : "rgba(6,14,22,0.92)";
+ ctx.fillRect(0, 0, w, h);
+ const accent = state.dead ? css.amber : css.sky;
+ const cells: [number, string, string, string][] = [
+ [0, "xmin", String(state.xmin), css.ink],
+ [176, "xmax", String(state.xmax), state.xmax ? css.amber : css.faint],
+ [352, "object_id", state.oid, css.string],
+ ];
+ ctx.textBaseline = "middle";
+ ctx.textAlign = "left";
+ const rule = (x: number) => {
+ ctx.fillStyle = state.dead ? "rgba(251,191,36,0.3)" : "rgba(125,211,252,0.28)";
+ ctx.fillRect(x, 16, 2, h - 32);
+ };
+ const heading = (x: number, label: string) => {
+ ctx.font = `500 25px ${MONO}`;
+ ctx.fillStyle = accent;
+ ctx.globalAlpha = 0.8;
+ ctx.fillText(label, x + 24, 44);
+ ctx.globalAlpha = 1;
+ };
+ for (const [x, label, value, color] of cells) {
+ if (x > 0) rule(x);
+ heading(x, label);
+ ctx.font = `600 37px ${MONO}`;
+ ctx.fillStyle = color;
+ ctx.fillText(value, x + 24, 100);
+ }
+
+ rule(572);
+ heading(572, "document · bson");
+ ctx.font = `600 37px ${MONO}`;
+ ctx.fillStyle = state.dead ? css.dim : css.ink;
+ if (typeof state.preview === "string") {
+ ctx.fillText(state.preview, 596, 100);
+ return;
+ }
+ // The row the film follows: its stock count is the one thing worth reading.
+ const lead = '{ …, "stock": { "qty": ';
+ ctx.fillText(lead, 596, 100);
+ const x = 596 + ctx.measureText(lead).width;
+ ctx.font = `700 66px ${MONO}`;
+ ctx.fillStyle = state.dead ? css.amber : css.number;
+ ctx.fillText(String(state.preview), x, 94);
+ const digit = ctx.measureText(String(state.preview)).width;
+ ctx.font = `600 37px ${MONO}`;
+ ctx.fillStyle = state.dead ? css.dim : css.ink;
+ ctx.fillText(" } }", x + digit, 100);
+}
+
+function paintReader(ctx: Ctx, who: string, sees: string, boxed: boolean) {
+ const [w, h] = READER_PX;
+ ctx.clearRect(0, 0, w, h);
+ if (boxed) {
+ // Inside the page the note needs a backing to stand off the hatching.
+ ctx.fillStyle = "rgba(4,12,18,0.9)";
+ ctx.fillRect(0, 0, w, h);
+ ctx.strokeStyle = "rgba(110,231,183,0.55)";
+ ctx.lineWidth = 3;
+ ctx.strokeRect(1.5, 1.5, w - 3, h - 3);
+ }
+ const x = boxed ? 18 : 8;
+ ctx.textBaseline = "middle";
+ ctx.font = `600 27px ${MONO}`;
+ ctx.fillStyle = css.emerald;
+ ctx.fillText(who, x, 34);
+ ctx.font = `600 40px ${MONO}`;
+ ctx.fillStyle = css.ink;
+ ctx.fillText(sees, x, 86);
+}
+
+interface Slot {
+ y: number;
+ mesh: Mesh;
+ ctx: Ctx;
+ texture: CanvasTexture;
+ drawn: string;
+ reader: Mesh;
+ readerLine: Line>;
+}
+
+export function createHeapStation(kit: Kit): Station {
+ const group = new Group();
+ group.position.set(0, Y.heap, HEAP.z);
+ const fader = new Fader();
+
+ /* Page outline, with the neighbouring pages of the table behind it. */
+ group.add(new Mesh(new PlaneGeometry(W, H), fader.add(holoMaterial({ color: hex.sky, fill: 0.03, line: 0.9, glow: 0.22 }))));
+ for (let i = 1; i <= 4; i++) {
+ const ghost = new Mesh(
+ new PlaneGeometry(W, H),
+ fader.add(holoMaterial({ color: hex.skyDeep, fill: 0.004, line: 0.5, glow: 0.05, opacity: 0.5 / i })),
+ );
+ ghost.position.set(i * 0.2, i * 0.17, -i * 0.5);
+ ghost.renderOrder = -i;
+ group.add(ghost);
+ }
+
+ /* Header. */
+ const headerY = H / 2 - 0.46;
+ const headerTexture = kit.tex.draw(1320, 120, (ctx) => {
+ ctx.fillStyle = "rgba(8,22,34,0.94)";
+ ctx.fillRect(0, 0, 1320, 120);
+ ctx.textBaseline = "middle";
+ ctx.font = `600 34px ${MONO}`;
+ ctx.fillStyle = css.sky;
+ ctx.fillText("PageHeaderData", 28, 62);
+ ctx.font = `500 27px ${MONO}`;
+ ctx.fillStyle = css.dim;
+ ctx.fillText("pd_lsn · pd_checksum · pd_lower · pd_upper · pd_special", 360, 63);
+ });
+ const header = new Mesh(
+ new PlaneGeometry(INNER, 0.56),
+ fader.add(panelMaterial({ map: headerTexture, size: [INNER, 0.56], radius: 0.05, border: hex.sky, borderWidth: 1 })),
+ );
+ header.position.set(0, headerY, 0.01);
+ group.add(header);
+
+ /* Line pointers: one small cell per tuple, filled from the left. */
+ const pointerCount = 10;
+ const pointerY = HEAP.pointerY;
+ const pointers = new InstancedMesh(
+ new PlaneGeometry(0.5, 0.36),
+ fader.add(holoMaterial({ color: 0xffffff, fill: 0.14, line: 0.6, glow: 0.2 })),
+ pointerCount,
+ );
+ {
+ const matrix = new Matrix4();
+ for (let i = 0; i < pointerCount; i++) {
+ matrix.makeTranslation(pointerX(i), pointerY, 0.01);
+ pointers.setMatrixAt(i, matrix);
+ }
+ }
+ group.add(pointers);
+ const pointerLive = new Color(hex.sky);
+ const pointerFree = new Color(hex.skyDeep).multiplyScalar(0.22);
+
+ /* Tuples that never change: two other products. */
+ const bottom = -H / 2 + 0.2;
+ const staticTuple = (row: number, state: TupleState) => {
+ const texture = kit.tex.draw(TUPLE_PX[0], TUPLE_PX[1], (ctx) => paintTuple(ctx, state));
+ const mesh = new Mesh(
+ new PlaneGeometry(INNER, tupleH),
+ fader.add(panelMaterial({ map: texture, size: [INNER, tupleH], radius: 0.05, border: hex.skyDeep, borderWidth: 0.8, tint: 0xaab8c8 }), 0.62),
+ );
+ mesh.position.set(0, bottom + tupleH / 2 + row * (tupleH + 0.1), 0.01);
+ group.add(mesh);
+ };
+ staticTuple(0, { xmin: 987, xmax: 0, oid: "…6f6e", preview: '{ "name": "Traily Peak", … }', dead: false });
+ staticTuple(1, { xmin: 1012, xmax: 0, oid: "…6f6f", preview: '{ "name": "Traily Hike", … }', dead: false });
+
+ /* The product's row version, the version the update writes, and who reads which. */
+ const readerWidth = 2.8;
+ const readerHeight = readerWidth * (READER_PX[1] / READER_PX[0]);
+ const freeBottom = HEAP.newY + tupleH / 2 + 0.12;
+ // A note names who sees each version. It sits beside the page, level with
+ // its row; on a narrow screen that would fall outside the frame, so there the
+ // notes stack in the page's free space and a line runs down the margin.
+ const note = (y: number, row: number): { at: Vector3; path: Vector3[] } => {
+ if (!kit.compact) {
+ return {
+ at: new Vector3(W / 2 + 0.62 + readerWidth / 2, y, 0.02),
+ path: [new Vector3(INNER / 2 + 0.05, y, 0.02), new Vector3(W / 2 + 0.55, y, 0.02)],
+ };
+ }
+ const noteY = freeBottom + 0.5 + row * (readerHeight + 0.14);
+ const margin = W / 2 - 0.08;
+ return {
+ at: new Vector3(INNER / 2 - 0.2 - readerWidth / 2, noteY, 0.03),
+ path: [
+ new Vector3(INNER / 2 - 0.18, noteY, 0.03),
+ new Vector3(margin, noteY, 0.03),
+ new Vector3(margin, y, 0.03),
+ new Vector3(INNER / 2 + 0.02, y, 0.03),
+ ],
+ };
+ };
+ const makeSlot = (y: number, who: string, sees: string, row: number): Slot => {
+ const [canvas, ctx] = kit.tex.canvas(TUPLE_PX[0], TUPLE_PX[1]);
+ const texture = kit.tex.texture(canvas);
+ const mesh = new Mesh(
+ new PlaneGeometry(INNER, tupleH),
+ panelMaterial({ map: texture, size: [INNER, tupleH], radius: 0.05, border: hex.sky, borderWidth: 1.4, bright: 1.1 }),
+ );
+ mesh.position.set(0, y, 0.02);
+ group.add(mesh);
+
+ const readerTexture = kit.tex.draw(READER_PX[0], READER_PX[1], (readerCtx) => paintReader(readerCtx, who, sees, kit.compact));
+ const placed = note(y, row);
+ const reader = new Mesh(
+ new PlaneGeometry(readerWidth, readerHeight),
+ new MeshBasicMaterial({ map: readerTexture, transparent: true, opacity: 0, depthWrite: false }),
+ );
+ reader.position.copy(placed.at);
+ reader.renderOrder = 6;
+ group.add(reader);
+
+ const line = new Line(new BufferGeometry().setFromPoints(placed.path), lineMaterial(hex.emerald, 0));
+ group.add(line);
+ return { y, mesh, ctx, texture, drawn: "", reader, readerLine: line };
+ };
+ const older = makeSlot(HEAP.oldY, "another shopper, mid-read", `still sees qty ${STOCK_BEFORE}`, 1);
+ const newer = makeSlot(HEAP.newY, "reads after the commit", `see qty ${STOCK_AFTER}`, 0);
+
+ /* Free space between the pointers and the newest tuple. */
+ const freeTop = pointerY - 0.3;
+ const hatchPx: [number, number] = [1248, Math.round((1248 * (freeTop - freeBottom)) / INNER)];
+ const hatch = kit.tex.draw(hatchPx[0], hatchPx[1], (ctx) => {
+ const [w, h] = hatchPx;
+ ctx.strokeStyle = "rgba(125,211,252,0.13)";
+ ctx.lineWidth = 3;
+ for (let x = -h; x < w; x += 44) {
+ ctx.beginPath();
+ ctx.moveTo(x, h);
+ ctx.lineTo(x + h, 0);
+ ctx.stroke();
+ }
+ // What grows into the free space from either end.
+ ctx.font = `500 30px ${MONO}`;
+ ctx.fillStyle = css.dim;
+ ctx.textBaseline = "middle";
+ ctx.fillText("↑ line pointers, one per tuple", 26, 34);
+ ctx.fillText("↓ tuples, one per row version", 26, h - 34);
+ ctx.textAlign = "center";
+ ctx.font = `600 36px ${MONO}`;
+ ctx.fillStyle = css.sky;
+ ctx.globalAlpha = 0.75;
+ ctx.fillText("free space", w / 2, h / 2);
+ });
+ const free = new Mesh(
+ new PlaneGeometry(INNER, freeTop - freeBottom),
+ fader.add(panelMaterial({ map: hatch, size: [INNER, freeTop - freeBottom], radius: 0.05, border: hex.skyDeep, borderWidth: 0.6 }), 0.9),
+ );
+ free.position.set(0, (freeTop + freeBottom) / 2, 0.005);
+ group.add(free);
+
+ /* Captions. */
+ const labels: Sprite[] = [];
+ const title = kit.tex.label("8 kB heap page", 0.42, {
+ color: "sky",
+ align: "center",
+ sub: "page 7 of documentdb_data.documents_3",
+ });
+ title.position.set(0, H / 2 + 0.7, 0.05);
+ labels.push(title);
+ group.add(title);
+
+ /* The old version's pointer to its successor. */
+ const ctidX = -W / 2 - 0.12;
+ const ctidCurve = new QuadraticBezierCurve3(
+ new Vector3(ctidX, HEAP.oldY, 0.02),
+ new Vector3(ctidX - 0.75, (HEAP.oldY + HEAP.newY) / 2, 0.02),
+ new Vector3(ctidX, HEAP.newY, 0.02),
+ );
+ const ctidMaterial = lineMaterial(hex.amber, 0);
+ group.add(new Line(new BufferGeometry().setFromPoints(ctidCurve.getPoints(20)), ctidMaterial));
+ const arrowGeometry = new BufferGeometry();
+ arrowGeometry.setAttribute(
+ "position",
+ new BufferAttribute(
+ new Float32Array([
+ ctidX, HEAP.newY, 0.02, ctidX - 0.2, HEAP.newY - 0.08, 0.02,
+ ctidX, HEAP.newY, 0.02, ctidX - 0.06, HEAP.newY - 0.22, 0.02,
+ ]),
+ 3,
+ ),
+ );
+ group.add(new LineSegments(arrowGeometry, ctidMaterial));
+ const ctidLabel = kit.tex.label("t_ctid", 0.3, { color: "amber", align: "right" });
+ ctidLabel.position.set(ctidX - 0.5, (HEAP.oldY + HEAP.newY) / 2, 0.05);
+ group.add(ctidLabel);
+
+ /* Write-ahead log: a rail under the page that every change is appended to. */
+ const walY = HEAP.walY;
+ const walFrom = 4.2;
+ const walLength = 8.4;
+ const walCount = 14;
+ const wal = new InstancedMesh(
+ new BoxGeometry(0.4, 0.17, 0.32),
+ fader.add(holoMaterial({ color: 0xffffff, fill: 0.2, line: 0.5, glow: 0.3 })),
+ walCount,
+ );
+ wal.frustumCulled = false;
+ group.add(wal);
+ {
+ const geometry = new BufferGeometry().setFromPoints([
+ new Vector3(walFrom - walLength, walY - 0.17, 0.02),
+ new Vector3(walFrom, walY - 0.17, 0.02),
+ ]);
+ group.add(new LineSegments(geometry, fader.add(lineMaterial(hex.sky, 0.45))));
+ }
+ const walLabel = kit.tex.label("WAL", 0.36, {
+ color: "ink",
+ align: "center",
+ sub: "write-ahead log · every change, before the reply",
+ });
+ walLabel.position.set(0, walY - 0.78, 0.05);
+ labels.push(walLabel);
+ group.add(walLabel);
+
+ // The record for this update: from the new version down onto the rail.
+ const recordPath = new QuadraticBezierCurve3(
+ new Vector3(INNER / 2, HEAP.newY, 0.08),
+ new Vector3(5.2, -3.4, 0.5),
+ new Vector3(walFrom - 0.2, walY, 0.08),
+ );
+ const record = new Mesh(
+ new BoxGeometry(0.46, 0.2, 0.34),
+ holoMaterial({ color: hex.ink, fill: 0.5, line: 0.6, glow: 0.5, opacity: 0 }),
+ );
+ record.renderOrder = 26;
+ const recordGlow = new Sprite(glowSpriteMaterial(kit.tex.glow(), hex.sky, 0));
+ recordGlow.scale.setScalar(1.3);
+ recordGlow.renderOrder = 25;
+ const commit = kit.tex.label(`COMMIT ${XID.update}`, 0.3, { color: "sky", sub: "flushed to the log", pill: true, align: "center" });
+ commit.renderOrder = 27;
+ group.add(record, recordGlow, commit);
+
+ /* Vacuum sweep. */
+ const sweepMaterial = new MeshBasicMaterial({
+ color: 0xffffff,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: AdditiveBlending,
+ });
+ const sweep = new Mesh(new PlaneGeometry(W + 0.3, 0.05), sweepMaterial);
+ const sweepGlow = new Sprite(glowSpriteMaterial(kit.tex.glow(), hex.ink, 0));
+ sweepGlow.scale.set(W * 1.3, 0.9, 1);
+ const vacuumLabel = kit.tex.label("VACUUM", 0.32, { color: "ink", align: "right" });
+ group.add(sweep, sweepGlow, vacuumLabel);
+ const sweepFrom = freeBottom + 1.1;
+ const sweepTo = bottom - 0.2;
+
+ const arrival = new Sprite(glowSpriteMaterial(kit.tex.glow(), hex.sky, 0));
+ arrival.scale.set(W * 1.1, 1.9, 1);
+ group.add(arrival);
+
+ const matrix = new Matrix4();
+ const tint = new Color();
+ const walColor = new Color(hex.ink);
+ const point = new Vector3();
+
+ return {
+ group,
+ update(frame: Frame) {
+ const { t, time } = frame;
+ const w = Math.max(envelope(t, 15.3, 16.5, 22.7, 23.7), frame.finale);
+ group.visible = w > 0.002;
+ if (!group.visible) return;
+ fader.set(w);
+ const detail = w * (1 - frame.finale);
+ for (const label of labels) label.material.opacity = detail;
+
+ /* The two row versions. */
+ const stamped = t >= CUE.stamp;
+ const states: [Slot, TupleState][] = [
+ [older, { xmin: XID.before, xmax: stamped ? XID.update : 0, oid: "…6f70", preview: STOCK_BEFORE, dead: stamped }],
+ [newer, { xmin: XID.update, xmax: 0, oid: "…6f70", preview: STOCK_AFTER, dead: false }],
+ ];
+ for (const [slot, state] of states) {
+ const key = `${state.xmax}|${state.dead}`;
+ if (slot.drawn !== key) {
+ paintTuple(slot.ctx, state);
+ slot.texture.needsUpdate = true;
+ slot.drawn = key;
+ slot.mesh.material.uniforms.uBorder.value.set(state.dead ? hex.amber : hex.sky);
+ }
+ }
+
+ // Vacuum passes down the page; the old version goes as the sweep reaches it.
+ const sweeping = smoothstep(CUE.vacuum, CUE.vacuumEnd, t);
+ const sweepY = lerp(sweepFrom, sweepTo, sweeping);
+ const reached = (sweepFrom - HEAP.oldY) / (sweepFrom - sweepTo);
+ const removed = smoothstep(reached - 0.07, reached + 0.07, sweeping);
+ const written = smoothstep(CUE.write, CUE.write + 0.55, t);
+ older.mesh.material.uniforms.uOpacity.value = w * (1 - removed);
+ newer.mesh.material.uniforms.uOpacity.value = w * written;
+ newer.mesh.position.x = (1 - written) * 0.7;
+ newer.mesh.visible = written > 0.002;
+
+ // Who sees which version.
+ const midRead = detail * envelope(t, CUE.tuple + 0.2, CUE.tuple + 0.6, CUE.nextRead, CUE.nextRead + 0.45);
+ const nextRead = detail * smoothstep(CUE.nextRead + 0.1, CUE.nextRead + 0.55, t);
+ older.reader.material.opacity = midRead;
+ older.readerLine.material.opacity = midRead * 0.8;
+ newer.reader.material.opacity = nextRead;
+ newer.readerLine.material.opacity = nextRead * 0.8;
+
+ // t_ctid: the superseded version points at its successor.
+ const linked = smoothstep(CUE.stamp, CUE.stamp + 0.4, t) * (1 - removed);
+ ctidMaterial.opacity = detail * linked * 0.95;
+ ctidLabel.material.opacity = detail * linked;
+
+ const sweepOn = t > CUE.vacuum && t < CUE.vacuumEnd ? Math.sin(Math.PI * sweeping) ** 0.6 : 0;
+ sweep.position.set(0, sweepY, 0.04);
+ sweepGlow.position.set(0, sweepY, 0.03);
+ vacuumLabel.position.set(-W / 2 - 0.3, sweepY, 0.05);
+ sweepMaterial.opacity = w * sweepOn * 0.9;
+ sweepGlow.material.opacity = w * sweepOn * 0.4;
+ vacuumLabel.material.opacity = detail * sweepOn;
+
+ // The light lands on the old version; the new one flares as it is written.
+ const landing = pulse(t, CUE.tuple, 2.2);
+ const writing = pulse(t, CUE.write + 0.1, 2.4);
+ arrival.position.set(0, writing > landing ? HEAP.newY : HEAP.oldY, 0.03);
+ arrival.material.opacity = w * Math.max(landing, writing) * 0.5;
+
+ for (let i = 0; i < pointerCount; i++) {
+ let level = i < 2 ? 1 : 0;
+ if (i === HEAP.oldPointer) level = (1 - removed) * (1 + 1.4 * pulse(t, CUE.linePointer, 2.5));
+ if (i === HEAP.newPointer) level = written;
+ pointers.setColorAt(i, tint.copy(pointerFree).lerp(pointerLive, Math.min(level, 1)).multiplyScalar(Math.max(level, 1)));
+ }
+ if (pointers.instanceColor) pointers.instanceColor.needsUpdate = true;
+
+ /* Write-ahead log. Records enter at the right and are carried left. */
+ const appended = smoothstep(CUE.wal, CUE.walFlush, t);
+ for (let i = 0; i < walCount; i++) {
+ const offset = fract(i / walCount + time * 0.04);
+ const age = offset * walLength;
+ matrix.makeTranslation(walFrom - age, walY, 0.02);
+ wal.setMatrixAt(i, matrix);
+ const edge = smoothstep(0, 0.5, age) * (1 - smoothstep(walLength - 1.2, walLength, age));
+ wal.setColorAt(i, tint.copy(walColor).multiplyScalar((0.3 + 1.1 * Math.exp(-age * 0.55)) * edge));
+ }
+ wal.instanceMatrix.needsUpdate = true;
+ if (wal.instanceColor) wal.instanceColor.needsUpdate = true;
+
+ // This update's record: off the new tuple, onto the rail, then along it.
+ const riding = Math.max(0, t - CUE.walFlush) * 0.34;
+ recordPath.getPoint(appended, point);
+ point.x -= riding;
+ record.position.copy(point);
+ recordGlow.position.copy(point);
+ const recorded = smoothstep(CUE.wal, CUE.wal + 0.15, t) * (1 - smoothstep(CUE.vacuumEnd, CUE.vacuumEnd + 0.8, t));
+ record.material.uniforms.uOpacity.value = w * recorded;
+ record.visible = recorded > 0.002;
+ recordGlow.material.opacity = w * recorded * (0.35 + 0.5 * pulse(t, CUE.walFlush, 2.5));
+ commit.position.set(point.x - 0.2, walY + 0.5, 0.06);
+ commit.material.opacity = detail * envelope(t, CUE.walFlush - 0.05, CUE.walFlush + 0.2, CUE.vacuum + 0.2, CUE.vacuum + 0.8);
+ },
+ };
+}
diff --git a/app/components/campaign/scene/stations/indexStation.ts b/app/components/campaign/scene/stations/indexStation.ts
new file mode 100644
index 0000000..72a0a16
--- /dev/null
+++ b/app/components/campaign/scene/stations/indexStation.ts
@@ -0,0 +1,337 @@
+// Two indexes over the same heap rows.
+//
+// Left, in sky: collection_pk_3, the B-tree primary key on
+// (shard_key_value, object_id) that serves _id lookups. One key, one row. The
+// update finds its row here on the way down.
+//
+// Right, in emerald: documents_rum_index_11 on "tags". RUM is an inverted
+// index: every indexed path/value pair is a term with a posting list of the
+// rows that contain it, so one array element can lead to many rows. It answers
+// a tag query on the way back up.
+
+import {
+ BoxGeometry,
+ BufferAttribute,
+ BufferGeometry,
+ Color,
+ Group,
+ InstancedMesh,
+ LineSegments,
+ Matrix4,
+ Quaternion,
+ Sprite,
+ Vector3,
+} from "three";
+import { CUE } from "../film";
+import { Fader, glowSpriteMaterial, holoMaterial, lineMaterial } from "../materials";
+import { hex } from "../palette";
+import { clamp, envelope, lerp, pulse } from "../util";
+import { TREE, Y, rowX, type Frame, type Kit, type Station } from "../world";
+
+const LEVEL_Y = TREE.levelY;
+const HEAP_Y = TREE.rowY;
+
+interface Node {
+ position: Vector3;
+ size: [number, number];
+ color: Color;
+ /** 0 for the B-tree, 1 for RUM. */
+ side: number;
+}
+
+/** Position `distance` along a polyline. */
+function along(points: Vector3[], distance: number, out: Vector3) {
+ let remaining = distance;
+ for (let i = 0; i < points.length - 1; i++) {
+ const length = points[i].distanceTo(points[i + 1]);
+ if (remaining <= length) return out.lerpVectors(points[i], points[i + 1], length > 0 ? remaining / length : 0);
+ remaining -= length;
+ }
+ return out.copy(points[points.length - 1]);
+}
+
+function polylineLength(points: Vector3[]) {
+ let total = 0;
+ for (let i = 0; i < points.length - 1; i++) total += points[i].distanceTo(points[i + 1]);
+ return total;
+}
+
+function segments(points: number[], material: ReturnType) {
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(points), 3));
+ return new LineSegments(geometry, material);
+}
+
+export function createIndexStation(kit: Kit): Station {
+ const group = new Group();
+ group.position.set(0, Y.index, 0);
+ const fader = new Fader();
+ const sky = new Color(hex.sky);
+ const emerald = new Color(hex.emerald);
+
+ const nodes: Node[] = [];
+ const edges: [number[], number[]] = [[], []];
+ const addNode = (x: number, y: number, width: number, side: number) => {
+ nodes.push({ position: new Vector3(x, y, 0), size: [width, 0.42], color: side === 0 ? sky : emerald, side });
+ return nodes.length - 1;
+ };
+ const link = (parent: number, child: number) => {
+ const a = nodes[parent];
+ const b = nodes[child];
+ edges[a.side].push(a.position.x, a.position.y - 0.21, 0, b.position.x, b.position.y + 0.21, 0);
+ };
+
+ /* B-tree: root, two internal pages, six leaves. */
+ const bx = TREE.btreeX;
+ const bRoot = addNode(bx, LEVEL_Y[0], 1.5, 0);
+ const bInner = TREE.btreeInner.map((dx) => addNode(bx + dx, LEVEL_Y[1], 1.25, 0));
+ const bLeaves = TREE.btreeLeaves.map((dx) => addNode(bx + dx, LEVEL_Y[2], 0.8, 0));
+ bInner.forEach((inner) => link(bRoot, inner));
+ bLeaves.forEach((leaf, i) => link(bInner[i < 3 ? 0 : 1], leaf));
+ // Leaf pages are chained left to right.
+ for (let i = 0; i < bLeaves.length - 1; i++) {
+ const a = nodes[bLeaves[i]].position;
+ const b = nodes[bLeaves[i + 1]].position;
+ edges[0].push(a.x + 0.4, a.y, 0, b.x - 0.4, b.y, 0);
+ }
+
+ /* RUM: an entry tree whose leaves are terms. */
+ const rx = TREE.rumX;
+ const rRoot = addNode(rx, LEVEL_Y[0], 1.5, 1);
+ const rInner = [-1.0, 1.0].map((dx) => addNode(rx + dx, LEVEL_Y[1], 1.25, 1));
+ const terms = ['"new"', '"shoes"', '"trail"', '"wide"'];
+ const termX = [-1.65, -0.55, 0.55, 1.65].map((dx) => rx + dx);
+ termX.forEach((x, i) => {
+ const parent = nodes[rInner[i < 2 ? 0 : 1]].position;
+ edges[1].push(parent.x, parent.y - 0.21, 0, x, LEVEL_Y[2] + 0.2, 0);
+ });
+ rInner.forEach((inner) => link(rRoot, inner));
+
+ const boxes = new InstancedMesh(
+ new BoxGeometry(1, 1, 1),
+ fader.add(holoMaterial({ color: 0xffffff, fill: 0.07, line: 0.7, glow: 0.24 })),
+ nodes.length,
+ );
+ {
+ const matrix = new Matrix4();
+ const identity = new Quaternion();
+ nodes.forEach((node, i) => {
+ matrix.compose(node.position, identity, new Vector3(node.size[0], node.size[1], 0.3));
+ boxes.setMatrixAt(i, matrix);
+ boxes.setColorAt(i, node.color);
+ });
+ }
+ boxes.frustumCulled = false;
+ group.add(boxes);
+
+ const termLabels = terms.map((term, i) => {
+ const label = kit.tex.label(term, 0.34, { color: "emerald", pill: true, align: "center" });
+ label.position.set(termX[i], LEVEL_Y[2], 0.05);
+ group.add(label);
+ return label;
+ });
+
+ /* Heap rows both indexes point into. */
+ const rowCount = TREE.rows;
+ const rows = new InstancedMesh(
+ new BoxGeometry(0.72, 0.26, 0.2),
+ fader.add(holoMaterial({ color: 0xffffff, fill: 0.14, line: 0.6, glow: 0.26 })),
+ rowCount,
+ );
+ const rowBase = new Color(hex.ink).multiplyScalar(0.5);
+ {
+ const matrix = new Matrix4();
+ for (let i = 0; i < rowCount; i++) {
+ matrix.makeTranslation(rowX(i), HEAP_Y, 0);
+ rows.setMatrixAt(i, matrix);
+ rows.setColorAt(i, rowBase);
+ }
+ }
+ rows.frustumCulled = false;
+ group.add(rows);
+
+ /* Posting lists: the rows each term appears in. */
+ const postings: number[][] = [
+ [7, 9, 11],
+ [6, 8, 9, 10, 11],
+ [7, 8, 10, 11],
+ [6, 10],
+ ];
+ const postingCells: { term: number; order: number; row: number; position: Vector3 }[] = [];
+ postings.forEach((list, term) => {
+ list.forEach((row, order) => {
+ postingCells.push({ term, order, row, position: new Vector3(termX[term], LEVEL_Y[2] - 0.5 - order * 0.26, 0) });
+ });
+ });
+ const cells = new InstancedMesh(
+ new BoxGeometry(0.34, 0.18, 0.12),
+ fader.add(holoMaterial({ color: 0xffffff, fill: 0.2, line: 0.5, glow: 0.25 })),
+ postingCells.length,
+ );
+ const cellBase = new Color(hex.emeraldDeep).multiplyScalar(0.7);
+ {
+ const matrix = new Matrix4();
+ postingCells.forEach((cell, i) => {
+ matrix.makeTranslation(cell.position.x, cell.position.y, 0);
+ cells.setMatrixAt(i, matrix);
+ cells.setColorAt(i, cellBase);
+ });
+ }
+ cells.frustumCulled = false;
+ group.add(cells);
+
+ /* Static lines: tree edges, and leaf → row pointers for the B-tree. */
+ const leafRows = [0, 1, 2, 3, 4, 5];
+ bLeaves.forEach((leaf, i) => {
+ const from = nodes[leaf].position;
+ edges[0].push(from.x, from.y - 0.21, 0, rowX(leafRows[i]), HEAP_Y + 0.13, 0);
+ });
+ const edgeMaterials = [lineMaterial(0x4f9fc4, 0.5), lineMaterial(0x4fc4a0, 0.5)];
+ group.add(segments(edges[0], edgeMaterials[0]), segments(edges[1], edgeMaterials[1]));
+
+ /* The posting → row lines only show while a lookup is fanning out. */
+ const fanTerm = 2;
+ const fanCells = postingCells.filter((cell) => cell.term === fanTerm);
+ const fan: number[] = [];
+ fanCells.forEach((cell) => {
+ fan.push(cell.position.x + 0.17, cell.position.y, 0, rowX(cell.row), HEAP_Y + 0.13, 0);
+ });
+ const fanMaterial = lineMaterial(hex.emerald, 0);
+ group.add(segments(fan, fanMaterial));
+
+ /* The row the primary key leads to continues down into its heap page. */
+ const pkRow = leafRows[TREE.pkLeaf];
+ const dropMaterial = lineMaterial(hex.sky, 0);
+ group.add(segments([rowX(pkRow), HEAP_Y - 0.13, 0, rowX(pkRow), HEAP_Y - 2.6, 0.25], dropMaterial));
+ const tid = kit.tex.label("ctid (7,3)", 0.3, { color: "sky", sub: "heap page 7, line pointer 3", align: "left" });
+ tid.position.set(rowX(pkRow) + 0.3, HEAP_Y - 0.95, 0.05);
+ group.add(tid);
+
+ /* Captions. */
+ const caption = (
+ text: string,
+ sub: string,
+ x: number,
+ y: number,
+ color: "sky" | "emerald" | "ink" | "dim",
+ align: "left" | "center" | "right" = "center",
+ size = 0.32,
+ ) => {
+ const sprite = kit.tex.label(text, size, { color, sub, align });
+ sprite.position.set(x, y, 0.05);
+ group.add(sprite);
+ return sprite;
+ };
+ const sideLabels: [Sprite, number][] = [
+ [caption("collection_pk_3", "B-tree · _id · one key, one row", bx, LEVEL_Y[0] + 1.15, "sky", "center", 0.38), 0],
+ [caption("documents_rum_index_11", "RUM · tags · one term per element", rx, LEVEL_Y[0] + 1.15, "emerald", "center", 0.38), 1],
+ [caption("heap rows of documents_3", "", rowX(rowCount - 1) + 0.36, HEAP_Y - 0.62, "dim", "right", 0.3), 1],
+ ];
+ const pkQuery = kit.tex.label('_id: ObjectId("…6f70")', 0.32, { color: "ink", pill: true, align: "center" });
+ pkQuery.position.set(bx, LEVEL_Y[0] + 0.02, 0.6);
+ const tagQuery = kit.tex.label('find({ tags: "trail" })', 0.32, { color: "ink", pill: true, align: "center" });
+ tagQuery.position.set(rx, LEVEL_Y[0] + 0.02, 0.6);
+ group.add(pkQuery, tagQuery);
+
+ /* The tag lookup, as a path with the time each node is reached. */
+ const speed = 4.4;
+ const tagPath = [
+ nodes[rRoot].position,
+ nodes[rInner[1]].position,
+ new Vector3(termX[fanTerm], LEVEL_Y[2], 0),
+ fanCells[fanCells.length - 1].position,
+ ];
+ const reach = (index: number) => CUE.tagQuery + polylineLength(tagPath.slice(0, index + 1)) / speed;
+ const tagEnd = reach(3);
+
+ const spark = new Sprite(glowSpriteMaterial(kit.tex.glow(), hex.emerald, 0));
+ spark.scale.setScalar(0.95);
+ spark.renderOrder = 25;
+ group.add(spark);
+
+ const nodeHeat = new Float32Array(nodes.length);
+ const rowHeat = new Float32Array(rowCount);
+ const tint = new Color();
+ const scratch = new Vector3();
+
+ return {
+ group,
+ update(frame: Frame) {
+ const { t } = frame;
+ const w = Math.max(envelope(t, 12.7, 13.6, 25.8, 26.7), frame.finale);
+ group.visible = w > 0.002;
+ if (!group.visible) return;
+ fader.set(w);
+ const detail = w * (1 - frame.finale);
+
+ // Whichever index is not being used steps back.
+ const usingRum = envelope(t, 21.8, 23.0, 26, 27);
+ const usingPk = 1 - envelope(t, 21.2, 22.4, 27, 28);
+ const emphasis = [
+ Math.max(lerp(0.4, 1, usingPk), frame.finale),
+ Math.max(lerp(0.4, 1, usingRum), frame.finale),
+ ];
+ edgeMaterials.forEach((material, side) => {
+ material.opacity = 0.5 * w * emphasis[side];
+ });
+ for (const [label, side] of sideLabels) label.material.opacity = detail * emphasis[side];
+
+ nodeHeat.fill(0);
+ rowHeat.fill(0);
+
+ // Primary-key lookup: the update's light arrives at each page in turn.
+ nodeHeat[bRoot] = pulse(t, CUE.root, 1.6);
+ nodeHeat[bInner[TREE.pkInner]] = pulse(t, CUE.inner, 1.6);
+ nodeHeat[bLeaves[TREE.pkLeaf]] = pulse(t, CUE.leaf, 1.6);
+ const found = pulse(t, CUE.row, 0.9) * (t < CUE.tagQuery - 1 ? 1 : 0);
+ rowHeat[pkRow] = found;
+
+ // Tag lookup: one term, a posting list, several rows.
+ nodeHeat[rRoot] = pulse(t, CUE.tagQuery, 1.4);
+ nodeHeat[rInner[1]] = pulse(t, reach(1), 1.4);
+ const termAt = reach(2);
+ let fanned = 0;
+ postingCells.forEach((cell, i) => {
+ let level = 0;
+ if (cell.term === fanTerm) {
+ const at = termAt + 0.1 + cell.order * 0.14;
+ level = pulse(t, at, 0.7);
+ rowHeat[cell.row] = Math.max(rowHeat[cell.row], pulse(t, at + 0.16, 0.7));
+ fanned = Math.max(fanned, level);
+ }
+ cells.setColorAt(i, tint.copy(cellBase).lerp(emerald, level).multiplyScalar((1 + level * 1.6) * emphasis[1]));
+ });
+ if (cells.instanceColor) cells.instanceColor.needsUpdate = true;
+ fanMaterial.opacity = w * fanned * 0.9;
+ termLabels.forEach((label, i) => {
+ label.material.opacity = detail * emphasis[1] * (i === fanTerm ? 1 : 0.62);
+ });
+
+ nodes.forEach((node, i) => {
+ boxes.setColorAt(i, tint.copy(node.color).multiplyScalar((0.8 + nodeHeat[i] * 2.6) * emphasis[node.side]));
+ });
+ if (boxes.instanceColor) boxes.instanceColor.needsUpdate = true;
+ const rowsShown = Math.max(emphasis[0], emphasis[1]);
+ for (let i = 0; i < rowCount; i++) {
+ const level = rowHeat[i];
+ const glow = i === pkRow && t < CUE.tagQuery - 1 ? sky : emerald;
+ rows.setColorAt(i, tint.copy(rowBase).lerp(glow, clamp(level, 0, 1)).multiplyScalar((1 + level * 2) * rowsShown));
+ }
+ if (rows.instanceColor) rows.instanceColor.needsUpdate = true;
+
+ // The pulse that walks the RUM entry tree.
+ const inTag = t >= CUE.tagQuery && t <= tagEnd;
+ if (inTag) along(tagPath, (t - CUE.tagQuery) * speed, scratch);
+ spark.position.copy(scratch).setZ(0.25);
+ spark.material.opacity = inTag ? w : 0;
+
+ pkQuery.material.opacity = detail * envelope(t, 12.9, 13.4, 15.7, 16.3);
+ tagQuery.material.opacity = detail * envelope(t, CUE.tagQuery - 0.5, CUE.tagQuery - 0.1, 25.3, 25.9);
+
+ // Row pointer → heap page.
+ const dropping = envelope(t, CUE.row - 0.1, CUE.row + 0.25, 17.4, 18.2);
+ dropMaterial.opacity = w * dropping * 0.8;
+ tid.material.opacity = detail * dropping;
+ },
+ };
+}
diff --git a/app/components/campaign/scene/stations/phoneStation.ts b/app/components/campaign/scene/stations/phoneStation.ts
new file mode 100644
index 0000000..5a68927
--- /dev/null
+++ b/app/components/campaign/scene/stations/phoneStation.ts
@@ -0,0 +1,267 @@
+// Where the film starts and ends: a phone showing the TrailyShop product page.
+// A touch lands on "Buy now"; much later the reply comes back and the screen
+// shows the order. It is the only thing in the frame, lit like a product
+// shot, so the eye stays on the app.
+
+import {
+ AdditiveBlending,
+ CircleGeometry,
+ ExtrudeGeometry,
+ Group,
+ Mesh,
+ MeshBasicMaterial,
+ NormalBlending,
+ PlaneGeometry,
+ RingGeometry,
+ Shape,
+ Sprite,
+ type ShaderMaterial,
+ type Texture,
+} from "three";
+import { CUE } from "../film";
+import { Fader, glowSpriteMaterial, holoMaterial, panelMaterial, rimMaterial } from "../materials";
+import {
+ BUTTON_UV,
+ CARD_UV,
+ STOCK_BEFORE,
+ confirmedPage,
+ phonePage,
+ pressedButton,
+ type UvRect,
+} from "../mockups";
+import { envelope, lerp, pulse, smoothstep } from "../util";
+import { PHONE, type Frame, type Kit, type Station } from "../world";
+
+const { w: W, h: H } = PHONE;
+const BEZEL = 0.05;
+/** Screen brightness: a lit white page, kept just under the bloom threshold so its text stays crisp. */
+const SCREEN = 0.88;
+const DEPTH = 0.1;
+
+/** Centre and size of a texture region in the screen's local space. */
+function place(rect: UvRect) {
+ return {
+ x: (rect.u + rect.w / 2 - 0.5) * W,
+ y: (0.5 - rect.v - rect.h / 2) * H,
+ w: rect.w * W,
+ h: rect.h * H,
+ };
+}
+
+/** A slab with rounded corners; its front face lies in the z = 0 plane. */
+function bodyGeometry() {
+ const w = W + BEZEL * 2;
+ const h = H + BEZEL * 2;
+ const r = 0.2;
+ const shape = new Shape();
+ shape.moveTo(-w / 2 + r, -h / 2);
+ shape.lineTo(w / 2 - r, -h / 2);
+ shape.quadraticCurveTo(w / 2, -h / 2, w / 2, -h / 2 + r);
+ shape.lineTo(w / 2, h / 2 - r);
+ shape.quadraticCurveTo(w / 2, h / 2, w / 2 - r, h / 2);
+ shape.lineTo(-w / 2 + r, h / 2);
+ shape.quadraticCurveTo(-w / 2, h / 2, -w / 2, h / 2 - r);
+ shape.lineTo(-w / 2, -h / 2 + r);
+ shape.quadraticCurveTo(-w / 2, -h / 2, -w / 2 + r, -h / 2);
+ const geometry = new ExtrudeGeometry(shape, {
+ depth: DEPTH,
+ bevelEnabled: true,
+ bevelSize: 0.018,
+ bevelThickness: 0.018,
+ bevelSegments: 3,
+ curveSegments: 10,
+ });
+ geometry.translate(0, 0, -DEPTH - 0.018);
+ return geometry;
+}
+
+interface Handset {
+ root: Group;
+ before: Mesh;
+ after: Mesh;
+ halo: Sprite;
+ /** How bright this phone is next to the one in front. */
+ level: number;
+ phase: number;
+ y: number;
+}
+
+export function createPhoneStation(kit: Kit): Station {
+ const group = new Group();
+ const fader = new Fader();
+ const glow = kit.tex.glow();
+
+ const stocked = phonePage(kit.tex, STOCK_BEFORE);
+ const confirmed = confirmedPage(kit.tex);
+
+ const body = bodyGeometry();
+ const screen = new PlaneGeometry(W, H);
+ const shell = fader.add(rimMaterial(0x8fa3b8));
+
+ const handsets: Handset[] = [];
+ const handset = (
+ position: [number, number, number],
+ turn: [number, number],
+ level: number,
+ before: Texture,
+ after: Texture,
+ ) => {
+ const root = new Group();
+ root.position.set(...position);
+ root.rotation.set(turn[0], turn[1], 0);
+
+ const back = new Mesh(body, shell);
+ back.renderOrder = 1;
+ const panel = (map: Texture, z: number) => {
+ const mesh = new Mesh(
+ screen,
+ panelMaterial({ map, size: [W, H], radius: 0.16, border: 0x0b1220, borderWidth: 1.4, bright: SCREEN * level }),
+ );
+ mesh.position.z = z;
+ mesh.renderOrder = 2;
+ return mesh;
+ };
+ const first = panel(before, 0.004);
+ const second = panel(after, 0.008);
+ second.renderOrder = 3;
+
+ const halo = new Sprite(glowSpriteMaterial(glow, 0xcfe2f3, 0));
+ halo.position.z = -0.4;
+ halo.scale.set(W * 3.1, H * 2.1, 1);
+
+ root.add(halo, back, first, second);
+ group.add(root);
+ const item: Handset = { root, before: first, after: second, halo, level, phase: handsets.length * 2.1, y: position[1] };
+ handsets.push(item);
+ return item;
+ };
+
+ const hero = handset([PHONE.x, PHONE.y, PHONE.z], [0, 0], 1, stocked, confirmed);
+
+ /* The touch: a fingertip, the ripple it leaves, and the button's response. */
+ const button = place(BUTTON_UV);
+ const overlay = (color: number, additive: boolean) =>
+ new MeshBasicMaterial({
+ color,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: additive ? AdditiveBlending : NormalBlending,
+ });
+
+ const pressed = new Mesh(
+ new PlaneGeometry(button.w, button.h),
+ panelMaterial({ map: pressedButton(kit.tex), size: [button.w, button.h], radius: 0.04, borderWidth: 0, opacity: 0 }),
+ );
+ pressed.position.set(button.x, button.y, 0.012);
+ pressed.renderOrder = 4;
+
+ const flashMaterial = overlay(0xffffff, true);
+ const flash = new Mesh(new PlaneGeometry(button.w, button.h), flashMaterial);
+ flash.position.set(button.x, button.y, 0.014);
+ flash.renderOrder = 5;
+
+ const fingerMaterial = overlay(0x0f172a, false);
+ const finger = new Mesh(new CircleGeometry(0.085, 32), fingerMaterial);
+ finger.renderOrder = 7;
+ const fingerEdgeMaterial = overlay(0x0f172a, false);
+ const fingerEdge = new Mesh(new RingGeometry(0.085, 0.097, 40), fingerEdgeMaterial);
+ fingerEdge.renderOrder = 8;
+
+ const rippleMaterial = overlay(0x0b74c4, false);
+ const ripple = new Mesh(new RingGeometry(0.9, 1, 56), rippleMaterial);
+ ripple.renderOrder = 6;
+ const echoMaterial = overlay(0x0b74c4, false);
+ const echo = new Mesh(new RingGeometry(0.94, 1, 56), echoMaterial);
+ echo.renderOrder = 6;
+
+ /* The product card lights up once the document starts to slide out of it. */
+ const card = place(CARD_UV);
+ const cardEdge = new Mesh(
+ new PlaneGeometry(card.w, card.h),
+ holoMaterial({ color: 0x059669, fill: 0, line: 1.3, glow: 0.3, opacity: 0 }),
+ );
+ // The screen is light, so the outline is painted over it instead of added to it.
+ cardEdge.material.blending = NormalBlending;
+ cardEdge.position.set(card.x, card.y, 0.016);
+ cardEdge.renderOrder = 5;
+
+ hero.root.add(pressed, flash, ripple, echo, finger, fingerEdge, cardEdge);
+
+ return {
+ group,
+ update(frame: Frame) {
+ const { t, time } = frame;
+ // Out of sight while the camera is inside the server.
+ const w = 1 - envelope(t, 8.5, 9.4, 28.8, 29.7);
+ group.visible = w > 0.002;
+ if (!group.visible) return;
+ fader.set(w);
+
+ // The document is the subject of the second shot; the screens step back.
+ const reading = envelope(t, CUE.docOut, CUE.docOpen, CUE.pack + 0.3, CUE.phoneEdge);
+ const firstLoop = frame.loop === 0;
+
+ handsets.forEach((item, index) => {
+ const isHero = index === 0;
+ // The reply reaches the phone in front first; the others catch up on
+ // their next read, a moment apart. Each loop then starts afresh.
+ const arrives = CUE.replyPhone + (isHero ? 0 : 0.35 + index * 0.22);
+ const landed =
+ t >= arrives - 0.1
+ ? smoothstep(arrives, arrives + 0.4, t)
+ : firstLoop
+ ? 0
+ : 1 - smoothstep(0.15, 0.8, t);
+ const level = item.level * (isHero ? lerp(1, 0.72, reading) : lerp(1, 0.16, reading));
+ item.before.material.uniforms.uOpacity.value = w;
+ item.before.material.uniforms.uBright.value = SCREEN * level;
+ // Once the new screen has fully arrived there is nothing left to show of the old one.
+ item.before.visible = landed < 0.999;
+ item.after.material.uniforms.uOpacity.value = w * landed;
+ item.after.material.uniforms.uBright.value = SCREEN * level;
+ item.after.visible = landed > 0.002;
+ const arrival = isHero ? pulse(t, CUE.replyPhone, 2.2) : 0;
+ item.halo.material.opacity = w * (0.1 * level + arrival * 0.3);
+ if (!isHero) {
+ item.root.position.y = item.y + Math.sin(time * 0.55 + item.phase) * 0.06;
+ item.root.rotation.z = Math.sin(time * 0.4 + item.phase * 1.3) * 0.02;
+ }
+ });
+
+ // Fingertip: drifts in from the lower right, presses, lifts.
+ const approach = smoothstep(CUE.finger, CUE.tap, t);
+ const contact = smoothstep(CUE.tap - 0.12, CUE.tap, t) * (1 - smoothstep(CUE.tap + 0.1, CUE.tap + 0.3, t));
+ const shown = smoothstep(CUE.finger, CUE.finger + 0.3, t) * (1 - smoothstep(CUE.tap + 0.18, CUE.tap + 0.5, t));
+ const fx = button.x + 0.1 + (1 - approach) * 0.34;
+ const fy = button.y - 0.01 - (1 - approach) * 0.5;
+ finger.position.set(fx, fy, 0.03);
+ fingerEdge.position.set(fx, fy, 0.031);
+ const press = lerp(1.25, 0.82, contact);
+ finger.scale.setScalar(press);
+ fingerEdge.scale.setScalar(press);
+ fingerMaterial.opacity = w * shown * lerp(0.16, 0.34, contact);
+ fingerEdgeMaterial.opacity = w * shown * 0.6;
+
+ // Two rings spread from the point of contact.
+ const spread = (t - CUE.tap) / 0.75;
+ ripple.position.set(button.x + 0.1, button.y - 0.01, 0.02);
+ ripple.scale.setScalar(0.06 + Math.max(spread, 0) * 0.62);
+ rippleMaterial.opacity = spread > 0 && spread < 1 ? w * (1 - spread) ** 1.5 * 0.95 : 0;
+ const second = (t - CUE.tap - 0.16) / 0.85;
+ echo.position.copy(ripple.position);
+ echo.scale.setScalar(0.06 + Math.max(second, 0) * 0.95);
+ echoMaterial.opacity = second > 0 && second < 1 ? w * (1 - second) ** 2 * 0.5 : 0;
+
+ // The button answers the touch, then says the order is on its way.
+ flashMaterial.opacity = w * pulse(t, CUE.tap, 5) * 0.75;
+ const waiting = smoothstep(CUE.tap + 0.05, CUE.tap + 0.25, t) * (t < CUE.replyPhone ? 1 : 0);
+ pressed.material.uniforms.uOpacity.value = w * waiting;
+ pressed.visible = waiting > 0.002;
+
+ const lit = envelope(t, CUE.tap + 0.25, CUE.docOut + 0.2, CUE.pack, CUE.depart + 0.2);
+ cardEdge.material.uniforms.uOpacity.value = w * lit * (0.6 + 0.4 * Math.sin(time * 3.1) ** 2);
+ cardEdge.visible = lit > 0.002;
+ },
+ };
+}
diff --git a/app/components/campaign/scene/stations/vectorStation.ts b/app/components/campaign/scene/stations/vectorStation.ts
new file mode 100644
index 0000000..028698a
--- /dev/null
+++ b/app/components/campaign/scene/stations/vectorStation.ts
@@ -0,0 +1,412 @@
+// Beyond CRUD: vector and geospatial search over the same rows. On the way
+// back up, the film stops here for the two queries behind the phone's
+// "Similar gear" and "Pick up today" rows.
+//
+// The layered graph is a small, real HNSW: every node lives on layer 0, a
+// subset on layer 1, a few on layer 2, each connected to its nearest
+// neighbours on that layer. The search shown is the actual greedy descent for
+// the query point, so the highlighted path is what the algorithm would take.
+//
+// The globe stands for 2dsphere indexes, which DocumentDB builds on PostGIS.
+
+import {
+ BufferAttribute,
+ BufferGeometry,
+ Color,
+ Group,
+ Line,
+ LineSegments,
+ Mesh,
+ PlaneGeometry,
+ Points,
+ RingGeometry,
+ Sprite,
+ Vector3,
+ MeshBasicMaterial,
+ AdditiveBlending,
+ DoubleSide,
+} from "three";
+import { CUE } from "../film";
+import { Fader, glowSpriteMaterial, holoMaterial, lineMaterial, pointsMaterial } from "../materials";
+import { PRODUCT } from "../mockups";
+import { hex } from "../palette";
+import { envelope, mulberry32, pulse, smoothstep } from "../util";
+import { Y, type Frame, type Kit, type Station } from "../world";
+
+const LAYER_Y = [-1.5, 0.3, 2.1];
+/** The top-layer node where every search starts, in the layer plane. */
+const ENTRY: [number, number] = [-1.5, 0.35];
+/** Seconds per hop of the greedy search. */
+const HOP = 0.2;
+/** Where the query embedding falls in the layer plane. */
+const QUERY: [number, number] = [2.1, -0.9];
+const TOP_K = 4;
+
+interface Hop {
+ layer: number;
+ node: number;
+}
+
+function buildGraph() {
+ const rng = mulberry32(33);
+ const points: [number, number][] = [ENTRY];
+ let guard = 0;
+ while (points.length < 54 && guard++ < 4000) {
+ const angle = rng() * Math.PI * 2;
+ const radius = Math.sqrt(rng());
+ const candidate: [number, number] = [Math.cos(angle) * radius * 3.2, Math.sin(angle) * radius * 2.2];
+ if (points.every(([x, z]) => Math.hypot(x - candidate[0], z - candidate[1]) > 0.5)) points.push(candidate);
+ }
+ const distance = (a: number, b: number) => Math.hypot(points[a][0] - points[b][0], points[a][1] - points[b][1]);
+
+ // Layer membership: everything on 0, about a third on 1, a handful on 2.
+ const all = points.map((_, i) => i);
+ const layer1 = all.filter((i) => i === 0 || rng() < 0.3);
+ const layer2 = layer1.filter((i) => i === 0 || rng() < 0.28);
+ const members = [all, layer1, layer2];
+ const degree = [3, 3, 2];
+ const neighbours = members.map((layer, level) => {
+ const map = new Map>();
+ for (const node of layer) map.set(node, new Set());
+ for (const node of layer) {
+ const nearest = layer
+ .filter((other) => other !== node)
+ .sort((a, b) => distance(node, a) - distance(node, b))
+ .slice(0, degree[level]);
+ for (const other of nearest) {
+ map.get(node)?.add(other);
+ map.get(other)?.add(node);
+ }
+ }
+ return map;
+ });
+ return { points, members, neighbours };
+}
+
+export function createVectorStation(kit: Kit): Station {
+ const group = new Group();
+ group.position.set(0, Y.vector, 0);
+ const fader = new Fader();
+ const { points, members, neighbours } = buildGraph();
+ const position = (hop: Hop, out = new Vector3()) =>
+ out.set(points[hop.node][0], LAYER_Y[hop.layer], points[hop.node][1]);
+
+ /* Layer planes. */
+ for (const [level, y] of LAYER_Y.entries()) {
+ const plane = new Mesh(
+ new PlaneGeometry(7.4, 5.2),
+ fader.add(holoMaterial({ color: hex.violetDeep, fill: 0.018, line: 0.5, glow: 0.1, opacity: 0.55 })),
+ );
+ plane.rotation.x = -Math.PI / 2;
+ plane.position.y = y - 0.02;
+ group.add(plane);
+ const tag = kit.tex.label(`layer ${level}`, 0.3, { color: "dim", align: "left" });
+ tag.position.set(-3.55, y + 0.05, 2.35);
+ fader.add(tag.material);
+ group.add(tag);
+ }
+
+ /* Edges within layers and the vertical links between copies of a node. */
+ {
+ const edges: number[] = [];
+ neighbours.forEach((map, level) => {
+ for (const [node, set] of map) {
+ for (const other of set) {
+ if (other < node) continue;
+ edges.push(points[node][0], LAYER_Y[level], points[node][1], points[other][0], LAYER_Y[level], points[other][1]);
+ }
+ }
+ });
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(edges), 3));
+ group.add(new LineSegments(geometry, fader.add(lineMaterial(hex.violetDeep, 0.42))));
+
+ const links: number[] = [];
+ for (let level = 1; level < members.length; level++) {
+ for (const node of members[level]) {
+ links.push(points[node][0], LAYER_Y[level], points[node][1], points[node][0], LAYER_Y[level - 1], points[node][1]);
+ }
+ }
+ const linkGeometry = new BufferGeometry();
+ linkGeometry.setAttribute("position", new BufferAttribute(new Float32Array(links), 3));
+ group.add(new LineSegments(linkGeometry, fader.add(lineMaterial(hex.violetDeep, 0.18))));
+ }
+
+ /* Nodes. One point per (layer, node) pair. */
+ const hops: Hop[] = [];
+ members.forEach((layer, level) => layer.forEach((node) => hops.push({ layer: level, node })));
+ const nodePositions = new Float32Array(hops.length * 3);
+ const nodeColors = new Float32Array(hops.length * 3);
+ const nodeSizes = new Float32Array(hops.length);
+ const nodeAlpha = new Float32Array(hops.length).fill(1);
+ const scratch = new Vector3();
+ hops.forEach((hop, i) => position(hop, scratch).toArray(nodePositions, i * 3));
+ const nodeGeometry = new BufferGeometry();
+ nodeGeometry.setAttribute("position", new BufferAttribute(nodePositions, 3));
+ nodeGeometry.setAttribute("aColor", new BufferAttribute(nodeColors, 3));
+ nodeGeometry.setAttribute("aSize", new BufferAttribute(nodeSizes, 1));
+ nodeGeometry.setAttribute("aAlpha", new BufferAttribute(nodeAlpha, 1));
+ const nodeCloud = new Points(nodeGeometry, fader.add(pointsMaterial()));
+ nodeCloud.frustumCulled = false;
+ group.add(nodeCloud);
+ const hopIndex = (hop: Hop) => hops.findIndex((h) => h.layer === hop.layer && h.node === hop.node);
+
+ /* Precompute the query's greedy path and its true nearest neighbours. */
+ const search = (() => {
+ const [qx, qz] = QUERY;
+ const toQuery = (node: number) => Math.hypot(points[node][0] - qx, points[node][1] - qz);
+ const path: Hop[] = [];
+ let current = 0;
+ for (let level = members.length - 1; level >= 0; level--) {
+ path.push({ layer: level, node: current });
+ for (;;) {
+ let best = current;
+ for (const other of neighbours[level].get(current) ?? []) {
+ if (toQuery(other) < toQuery(best)) best = other;
+ }
+ if (best === current) break;
+ current = best;
+ path.push({ layer: level, node: current });
+ }
+ }
+ const nearest = members[0]
+ .slice()
+ .sort((a, b) => toQuery(a) - toQuery(b))
+ .slice(0, TOP_K);
+ return { qx, qz, path, pathIndices: path.map(hopIndex), nearest, nearestIndices: nearest.map((node) => hopIndex({ layer: 0, node })) };
+ })();
+
+ /* Query marker: a ring on every layer joined by a vertical line. */
+ const queryMaterial = new MeshBasicMaterial({
+ color: 0xffffff,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ side: DoubleSide,
+ blending: AdditiveBlending,
+ });
+ const ringGeometry = new RingGeometry(0.17, 0.23, 32);
+ ringGeometry.rotateX(-Math.PI / 2);
+ const queryRings = LAYER_Y.map((y) => {
+ const ring = new Mesh(ringGeometry, queryMaterial);
+ ring.position.y = y;
+ group.add(ring);
+ return ring;
+ });
+ const queryLineMaterial = lineMaterial(0xffffff, 0);
+ const queryLine = new Line(
+ new BufferGeometry().setFromPoints([new Vector3(0, LAYER_Y[0], 0), new Vector3(0, LAYER_Y[2] + 1.7, 0)]),
+ queryLineMaterial,
+ );
+ group.add(queryLine);
+ const queryLabel = kit.tex.label(`similar to ${PRODUCT.name}`, 0.3, { color: "ink", pill: true, align: "center" });
+ group.add(queryLabel);
+
+ /* Search path so far, and the result fan. */
+ const maxPath = search.path.length;
+ const trailPositions = new Float32Array(maxPath * 3);
+ const trailGeometry = new BufferGeometry();
+ trailGeometry.setAttribute("position", new BufferAttribute(trailPositions, 3));
+ const trailMaterial = lineMaterial(0xffffff, 0);
+ const trail = new Line(trailGeometry, trailMaterial);
+ trail.frustumCulled = false;
+ group.add(trail);
+
+ const resultPositions = new Float32Array(TOP_K * 6);
+ const resultGeometry = new BufferGeometry();
+ resultGeometry.setAttribute("position", new BufferAttribute(resultPositions, 3));
+ const resultMaterial = lineMaterial(hex.emerald, 0);
+ const resultLines = new LineSegments(resultGeometry, resultMaterial);
+ resultLines.frustumCulled = false;
+ group.add(resultLines);
+
+ const pulseSprite = new Sprite(glowSpriteMaterial(kit.tex.glow(), 0xffffff, 0));
+ pulseSprite.scale.setScalar(0.9);
+ pulseSprite.renderOrder = 25;
+ group.add(pulseSprite);
+
+ /* Globe. */
+ const globe = new Group();
+ globe.position.set(5.4, 0.25, -0.2);
+ const globeRadius = 1.2;
+ const areaMaterial = lineMaterial(hex.emerald, 0.95);
+ const ping = new Sprite(glowSpriteMaterial(kit.tex.glow(), hex.emerald, 0));
+ {
+ const lines: number[] = [];
+ const onSphere = (lat: number, lon: number, out: number[]) => {
+ out.push(
+ Math.cos(lat) * Math.sin(lon) * globeRadius,
+ Math.sin(lat) * globeRadius,
+ Math.cos(lat) * Math.cos(lon) * globeRadius,
+ );
+ };
+ const steps = 48;
+ for (let m = 0; m < 12; m++) {
+ const lon = (m / 12) * Math.PI * 2;
+ for (let i = 0; i < steps; i++) {
+ onSphere(-Math.PI / 2 + (i / steps) * Math.PI, lon, lines);
+ onSphere(-Math.PI / 2 + ((i + 1) / steps) * Math.PI, lon, lines);
+ }
+ }
+ for (let p = 1; p < 6; p++) {
+ const lat = -Math.PI / 2 + (p / 6) * Math.PI;
+ for (let i = 0; i < steps; i++) {
+ onSphere(lat, (i / steps) * Math.PI * 2, lines);
+ onSphere(lat, ((i + 1) / steps) * Math.PI * 2, lines);
+ }
+ }
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(lines), 3));
+ globe.add(new LineSegments(geometry, fader.add(lineMaterial(0x2f8f86, 0.42))));
+
+ // Stores, and a $near search area around one of them.
+ const rng = mulberry32(5);
+ const centerLat = 0.55;
+ const centerLon = 0.5;
+ const places: number[] = [];
+ onSphere(centerLat, centerLon, places);
+ for (let i = 0; i < 11; i++) onSphere(centerLat + (rng() - 0.5) * 1.5, centerLon + (rng() - 0.5) * 2.2, places);
+ const placeGeometry = new BufferGeometry();
+ const count = places.length / 3;
+ const colors = new Float32Array(count * 3);
+ const emerald = new Color(hex.emerald);
+ for (let i = 0; i < count; i++) emerald.toArray(colors, i * 3);
+ placeGeometry.setAttribute("position", new BufferAttribute(new Float32Array(places), 3));
+ placeGeometry.setAttribute("aColor", new BufferAttribute(colors, 3));
+ placeGeometry.setAttribute("aSize", new BufferAttribute(new Float32Array(count).fill(0.2), 1));
+ placeGeometry.setAttribute("aAlpha", new BufferAttribute(new Float32Array(count).fill(1), 1));
+ globe.add(new Points(placeGeometry, fader.add(pointsMaterial())));
+
+ const area: number[] = [];
+ const reach = 0.42;
+ for (let i = 0; i < 40; i++) {
+ for (const step of [i, i + 1]) {
+ const bearing = (step / 40) * Math.PI * 2;
+ onSphere(centerLat + Math.sin(bearing) * reach, centerLon + (Math.cos(bearing) * reach) / Math.cos(centerLat), area);
+ }
+ }
+ const areaGeometry = new BufferGeometry();
+ areaGeometry.setAttribute("position", new BufferAttribute(new Float32Array(area), 3));
+ globe.add(new LineSegments(areaGeometry, areaMaterial));
+
+ const centre: number[] = [];
+ onSphere(centerLat, centerLon, centre);
+ ping.position.set(centre[0], centre[1], centre[2]).multiplyScalar(1.02);
+ globe.add(ping);
+ }
+ group.add(globe);
+ const nearLabel = kit.tex.label("$near: [-122.33, 47.61]", 0.28, { color: "ink", pill: true, align: "center" });
+ nearLabel.position.set(globe.position.x, globe.position.y - globeRadius - 0.6, globe.position.z);
+ group.add(nearLabel);
+
+ /* Captions. */
+ const labels: Sprite[] = [];
+ const caption = (text: string, sub: string, x: number, y: number, z: number, color: "violet" | "emerald") => {
+ const sprite = kit.tex.label(text, 0.4, { color, sub, align: "center" });
+ sprite.position.set(x, y, z);
+ labels.push(sprite);
+ group.add(sprite);
+ };
+ caption("vector-hnsw", "pgvector · cosine similarity", -0.4, LAYER_Y[2] + 2.75, 0, "violet");
+ caption("2dsphere", "PostGIS · $near", globe.position.x, globe.position.y + globeRadius + 0.85, globe.position.z, "emerald");
+
+ const violet = new Color(hex.violet);
+ const white = new Color(0xffffff);
+ const emerald = new Color(hex.emerald);
+ const tint = new Color();
+ const from = new Vector3();
+ const to = new Vector3();
+
+ return {
+ group,
+ update(frame: Frame) {
+ const { t } = frame;
+ // Glimpsed in the dark on the way down, visited on the way back up.
+ const visit = envelope(t, 25.3, 26.2, 28.9, 29.9);
+ const glimpse = 0.32 * envelope(t, 12.3, 13.0, 14.0, 14.8);
+ const w = Math.max(visit, glimpse, frame.finale);
+ group.visible = w > 0.002;
+ if (!group.visible) return;
+ fader.set(w);
+ const detail = visit * (1 - frame.finale);
+ for (const label of labels) label.material.opacity = detail;
+ globe.rotation.y = Math.sin(frame.time * 0.16) * 0.2 - 0.3;
+
+ const start = CUE.vectorQuery + 0.25;
+ const travelled = Math.max(0, (t - start) / HOP);
+ const lastHop = search.path.length - 1;
+ const done = start + lastHop * HOP;
+ const found = smoothstep(done, done + 0.4, t);
+ const present = envelope(t, CUE.vectorQuery - 0.3, CUE.vectorQuery + 0.15, 28.9, 29.6);
+
+ // Query marker.
+ queryRings.forEach((ring) => {
+ ring.position.x = search.qx;
+ ring.position.z = search.qz;
+ });
+ queryLine.position.set(search.qx, 0, search.qz);
+ queryMaterial.opacity = w * present * 0.95;
+ queryLineMaterial.opacity = w * present * 0.4;
+ queryLabel.position.set(search.qx, LAYER_Y[2] + 1.95, search.qz);
+ queryLabel.material.opacity = detail * present;
+
+ // Node colours: resting violet, white when visited, emerald when returned.
+ for (let i = 0; i < hops.length; i++) {
+ tint.copy(violet).multiplyScalar(hops[i].layer === 0 ? 0.62 : 0.9);
+ nodeSizes[i] = hops[i].layer === 0 ? 0.17 : 0.21;
+ tint.toArray(nodeColors, i * 3);
+ }
+ search.pathIndices.forEach((index, step) => {
+ const since = travelled - step;
+ if (since < 0) return;
+ const glow = Math.exp(-since * 0.22) * present;
+ tint.fromArray(nodeColors, index * 3).lerp(white, glow).multiplyScalar(1 + glow * 1.4);
+ tint.toArray(nodeColors, index * 3);
+ nodeSizes[index] += glow * 0.16;
+ });
+ search.nearestIndices.forEach((index) => {
+ const glow = found * present;
+ tint.fromArray(nodeColors, index * 3).lerp(emerald, glow).multiplyScalar(1 + glow * 1.6);
+ tint.toArray(nodeColors, index * 3);
+ nodeSizes[index] += glow * 0.2;
+ });
+ nodeGeometry.attributes.aColor.needsUpdate = true;
+ nodeGeometry.attributes.aSize.needsUpdate = true;
+
+ // The path walked so far.
+ const whole = Math.min(Math.floor(travelled), lastHop);
+ const part = Math.min(travelled - whole, 1);
+ for (let i = 0; i < maxPath; i++) {
+ const step = Math.min(i, whole);
+ position(search.path[step], from);
+ if (i > whole) {
+ // The segment being walked right now, and padding after it.
+ position(search.path[Math.min(whole + 1, lastHop)], to);
+ from.lerp(to, part);
+ }
+ from.toArray(trailPositions, i * 3);
+ }
+ trailGeometry.attributes.position.needsUpdate = true;
+ trailMaterial.opacity = w * (t > start ? 0.9 : 0) * present;
+ position(search.path[whole], from);
+ position(search.path[Math.min(whole + 1, lastHop)], to);
+ pulseSprite.position.copy(from.lerp(to, whole < lastHop ? part : 1));
+ pulseSprite.position.y += 0.05;
+ pulseSprite.material.opacity = w * (t > start && t < done + 0.3 ? 1 : 0);
+
+ // Results: the K nearest rows, tied back to the query.
+ search.nearest.forEach((node, i) => {
+ resultPositions.set([search.qx, LAYER_Y[0], search.qz, points[node][0], LAYER_Y[0], points[node][1]], i * 6);
+ });
+ resultGeometry.attributes.position.needsUpdate = true;
+ resultMaterial.opacity = w * found * present * 0.9;
+
+ // $near on the globe: the search area flashes as the nearest store is found.
+ const near = pulse(t, CUE.nearQuery, 1.3) * (t < CUE.nearQuery + 3 ? 1 : 0);
+ areaMaterial.opacity = w * (0.55 + 0.45 * Math.min(near * 1.6, 1));
+ ping.scale.setScalar(0.5 + near * 1.1);
+ ping.material.opacity = w * Math.min(near * 1.4, 1) * 0.9;
+ nearLabel.material.opacity = detail * envelope(t, CUE.nearQuery - 0.35, CUE.nearQuery, 28.9, 29.5);
+ },
+ };
+}
diff --git a/app/components/campaign/scene/textures.ts b/app/components/campaign/scene/textures.ts
new file mode 100644
index 0000000..6b647d4
--- /dev/null
+++ b/app/components/campaign/scene/textures.ts
@@ -0,0 +1,240 @@
+import {
+ CanvasTexture,
+ LinearFilter,
+ LinearMipmapLinearFilter,
+ SRGBColorSpace,
+ Sprite,
+ SpriteMaterial,
+ type Texture,
+} from "three";
+import { css, type CssColor } from "./palette";
+
+export const MONO =
+ 'ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';
+
+export type Ctx = CanvasRenderingContext2D;
+export type Tok = [text: string, color: CssColor];
+
+export function roundRect(ctx: Ctx, x: number, y: number, w: number, h: number, r: number) {
+ const radius = Math.min(r, w / 2, h / 2);
+ ctx.beginPath();
+ ctx.moveTo(x + radius, y);
+ ctx.arcTo(x + w, y, x + w, y + h, radius);
+ ctx.arcTo(x + w, y + h, x, y + h, radius);
+ ctx.arcTo(x, y + h, x, y, radius);
+ ctx.arcTo(x, y, x + w, y, radius);
+ ctx.closePath();
+}
+
+export interface LabelStyle {
+ color?: CssColor;
+ /** Second, smaller line. */
+ sub?: string;
+ subColor?: CssColor;
+ /** Dark rounded backing with a hairline border. */
+ pill?: boolean;
+ mono?: boolean;
+ align?: "left" | "center" | "right";
+}
+
+export interface CodePanel {
+ texture: CanvasTexture;
+ /** Width divided by height. */
+ aspect: number;
+ /** Vertical centre of a line, 0 at the top of the panel and 1 at the bottom. */
+ lineV(index: number): number;
+ /** Right end of a line's text, 0 at the left edge and 1 at the right. */
+ lineEndU(index: number): number;
+ /** Left edge of every line's text, as a fraction of the width. */
+ startU: number;
+ /** Height of one line, as a fraction of the panel's height. */
+ lineHeightV: number;
+ /** Width of one character, as a fraction of the panel's width. */
+ charU: number;
+}
+
+/**
+ * Creates and tracks every canvas-backed texture so they can be uploaded ahead
+ * of first use and released together.
+ */
+export class TextureKit {
+ readonly all: Texture[] = [];
+ private glowTexture?: CanvasTexture;
+
+ constructor(
+ private readonly anisotropy: number,
+ /** Sans-serif stack copied from the page so canvas text matches it. */
+ readonly sans: string,
+ /** Resolution multiplier; below 1 on constrained devices. */
+ readonly res: number,
+ ) {}
+
+ canvas(width: number, height: number): [HTMLCanvasElement, Ctx] {
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.max(2, Math.round(width * this.res));
+ canvas.height = Math.max(2, Math.round(height * this.res));
+ const ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("2D canvas is unavailable");
+ ctx.scale(this.res, this.res);
+ return [canvas, ctx];
+ }
+
+ texture(canvas: HTMLCanvasElement) {
+ const texture = new CanvasTexture(canvas);
+ texture.colorSpace = SRGBColorSpace;
+ texture.anisotropy = this.anisotropy;
+ texture.generateMipmaps = true;
+ texture.minFilter = LinearMipmapLinearFilter;
+ texture.magFilter = LinearFilter;
+ this.all.push(texture);
+ return texture;
+ }
+
+ /** Draw at a logical size and get the texture back. */
+ draw(width: number, height: number, paint: (ctx: Ctx) => void) {
+ const [canvas, ctx] = this.canvas(width, height);
+ paint(ctx);
+ return this.texture(canvas);
+ }
+
+ /** Soft radial falloff used for halos and light pools. */
+ glow() {
+ if (!this.glowTexture) {
+ this.glowTexture = this.draw(128, 128, (ctx) => {
+ const gradient = ctx.createRadialGradient(64, 64, 0, 64, 64, 64);
+ gradient.addColorStop(0, "rgba(255,255,255,1)");
+ gradient.addColorStop(0.25, "rgba(255,255,255,0.55)");
+ gradient.addColorStop(0.6, "rgba(255,255,255,0.12)");
+ gradient.addColorStop(1, "rgba(255,255,255,0)");
+ ctx.fillStyle = gradient;
+ ctx.fillRect(0, 0, 128, 128);
+ });
+ }
+ return this.glowTexture;
+ }
+
+ /**
+ * A camera-facing text tag. `height` is the world-space height of a
+ * single-line label; a label with a sub line is proportionally taller.
+ */
+ label(text: string, height: number, style: LabelStyle = {}) {
+ const mono = style.mono ?? true;
+ const family = mono ? MONO : this.sans;
+ const mainFont = `600 44px ${family}`;
+ const subFont = `500 30px ${family}`;
+ const padX = style.pill ? 28 : 6;
+ const padY = style.pill ? 18 : 8;
+ const mainH = 54;
+ const subH = style.sub ? 44 : 0;
+
+ const [probe, probeCtx] = this.canvas(8, 8);
+ probeCtx.font = mainFont;
+ let textW = probeCtx.measureText(text).width;
+ if (style.sub) {
+ probeCtx.font = subFont;
+ textW = Math.max(textW, probeCtx.measureText(style.sub).width);
+ }
+ probe.width = probe.height = 0;
+
+ const width = Math.ceil(textW + padX * 2);
+ const totalH = mainH + subH + padY * 2;
+ const align = style.align ?? "left";
+ const texture = this.draw(width, totalH, (ctx) => {
+ if (style.pill) {
+ roundRect(ctx, 1.5, 1.5, width - 3, totalH - 3, 16);
+ ctx.fillStyle = "rgba(4,8,12,0.82)";
+ ctx.fill();
+ ctx.globalAlpha = 0.5;
+ ctx.strokeStyle = css[style.color ?? "sky"];
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ ctx.globalAlpha = 1;
+ }
+ const x = align === "left" ? padX : align === "right" ? width - padX : width / 2;
+ ctx.textAlign = align;
+ ctx.textBaseline = "middle";
+ ctx.font = mainFont;
+ ctx.fillStyle = css[style.color ?? "sky"];
+ ctx.fillText(text, x, padY + mainH / 2 + 1);
+ if (style.sub) {
+ ctx.font = subFont;
+ ctx.fillStyle = css[style.subColor ?? "dim"];
+ ctx.fillText(style.sub, x, padY + mainH + subH / 2);
+ }
+ });
+
+ const material = new SpriteMaterial({
+ map: texture,
+ transparent: true,
+ depthWrite: false,
+ depthTest: false,
+ });
+ const sprite = new Sprite(material);
+ const worldH = height * (totalH / (mainH + padY * 2));
+ sprite.scale.set(worldH * (width / totalH), worldH, 1);
+ sprite.center.set(align === "left" ? 0 : align === "right" ? 1 : 0.5, 0.5);
+ sprite.renderOrder = 20;
+ return sprite;
+ }
+
+ /** Syntax-coloured monospace text on a dark card. */
+ code(
+ lines: Tok[][],
+ options: { fontPx?: number; title?: string; titleColor?: CssColor; minCols?: number } = {},
+ ): CodePanel {
+ const fontPx = options.fontPx ?? 30;
+ const lineH = Math.round(fontPx * 1.5);
+ const padX = Math.round(fontPx * 1.1);
+ const padY = Math.round(fontPx * 0.95);
+ const titleH = options.title ? Math.round(fontPx * 1.7) : 0;
+ const font = `500 ${fontPx}px ${MONO}`;
+
+ const [probe, probeCtx] = this.canvas(8, 8);
+ probeCtx.font = font;
+ const charW = probeCtx.measureText("M").width;
+ probe.width = probe.height = 0;
+
+ const lengths = lines.map((line) => line.reduce((n, [text]) => n + text.length, 0));
+ const cols = Math.max(options.minCols ?? 0, ...lengths);
+ const width = Math.ceil(cols * charW + padX * 2);
+ const height = titleH + lines.length * lineH + padY * 2;
+
+ const texture = this.draw(width, height, (ctx) => {
+ ctx.fillStyle = "rgba(6,11,17,0.9)";
+ ctx.fillRect(0, 0, width, height);
+ ctx.textBaseline = "middle";
+ if (options.title) {
+ ctx.font = `600 ${Math.round(fontPx * 0.72)}px ${MONO}`;
+ ctx.fillStyle = css[options.titleColor ?? "dim"];
+ ctx.fillText(options.title.toUpperCase(), padX, padY + titleH * 0.36);
+ ctx.fillStyle = "rgba(125,211,252,0.16)";
+ ctx.fillRect(padX, padY + titleH * 0.78, width - padX * 2, 1.5);
+ }
+ ctx.font = font;
+ lines.forEach((line, row) => {
+ let x = padX;
+ const y = padY + titleH + row * lineH + lineH / 2;
+ for (const [text, color] of line) {
+ ctx.fillStyle = css[color];
+ ctx.fillText(text, x, y);
+ x += text.length * charW;
+ }
+ });
+ });
+
+ return {
+ texture,
+ aspect: width / height,
+ lineV: (index) => (padY + titleH + index * lineH + lineH / 2) / height,
+ lineEndU: (index) => (padX + lengths[index] * charW) / width,
+ startU: padX / width,
+ lineHeightV: lineH / height,
+ charU: charW / width,
+ };
+ }
+
+ dispose() {
+ for (const texture of this.all) texture.dispose();
+ this.all.length = 0;
+ }
+}
diff --git a/app/components/campaign/scene/util.ts b/app/components/campaign/scene/util.ts
new file mode 100644
index 0000000..601e0cd
--- /dev/null
+++ b/app/components/campaign/scene/util.ts
@@ -0,0 +1,38 @@
+export const clamp = (x: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, x));
+export const saturate = (x: number) => clamp(x, 0, 1);
+export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+
+export function smoothstep(edge0: number, edge1: number, x: number) {
+ const t = saturate((x - edge0) / (edge1 - edge0));
+ return t * t * (3 - 2 * t);
+}
+
+export const smoother = (t: number) => t * t * t * (t * (t * 6 - 15) + 10);
+
+/** 1 inside `inner` of `center`, falling to 0 at `outer`. */
+export function bump(x: number, center: number, inner: number, outer: number) {
+ return 1 - smoothstep(inner, outer, Math.abs(x - center));
+}
+
+/** Rises from 0 to 1 between `a` and `b`, falls back to 0 between `c` and `d`. */
+export function envelope(x: number, a: number, b: number, c: number, d: number) {
+ return smoothstep(a, b, x) * (1 - smoothstep(c, d, x));
+}
+
+/** 1 at `at`, decaying afterwards; 0 before. */
+export function pulse(x: number, at: number, decay: number) {
+ return x >= at ? Math.exp(-(x - at) * decay) : 0;
+}
+
+export const fract = (x: number) => x - Math.floor(x);
+
+/** Small deterministic PRNG so every visitor sees the same layout. */
+export function mulberry32(seed: number) {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
diff --git a/app/components/campaign/scene/world.ts b/app/components/campaign/scene/world.ts
new file mode 100644
index 0000000..1cbcae7
--- /dev/null
+++ b/app/components/campaign/scene/world.ts
@@ -0,0 +1,144 @@
+import { CatmullRomCurve3, Vector3, type Group } from "three";
+import type { Signal } from "./signal";
+import type { TextureKit } from "./textures";
+
+// The world is a tower. A phone floats above a hall of server racks; inside
+// one of those machines, drawn large, the gateway sits over PostgreSQL, whose
+// indexes sit over the heap they point into. Y is the height of each level.
+export const Y = {
+ gateway: -14,
+ vector: -26,
+ index: -38,
+ heap: -50,
+} as const;
+
+/** The phone whose tap the film follows: centre of its screen, facing +z. */
+export const PHONE = { x: 0, y: 1.45, z: 6.5, w: 1.2, h: 2.6 } as const;
+
+/** Where the document and its bytes float, relative to the phone's centre. */
+export const DOC = {
+ json: new Vector3(2.05, 0.42, 0.55),
+ bson: new Vector3(2.05, -0.72, 0.55),
+};
+
+/** The hall of racks between the phone and the machine the film goes into. */
+export const HALL = {
+ floor: -8.4,
+ /** Height at which the light runs along the aisle and enters the last rack. */
+ port: -6.6,
+ rack: { w: 1.5, h: 3.4, d: 1.9 },
+ /** The two rows facing the aisle stand this far either side of the axis. */
+ aisle: 2.35,
+ /** Where the aisle opens towards the camera. */
+ mouth: 11.4,
+ perRow: 5,
+} as const;
+
+/** Vertical extent of the machine that holds everything below the hall. */
+export const SERVER = { top: -9.2, bottom: -57.4, half: 10.5 };
+
+/** Where the spine of that machine starts: the heart of the rack at the aisle's end. */
+export const TRUNK_TOP = HALL.port;
+
+/** One heap page, shared by the station that draws it and the light that lands on it. */
+export const HEAP = {
+ w: 6.6,
+ h: 7.6,
+ /** The page stands slightly behind the tower's axis. */
+ z: -0.4,
+ tupleH: 0.72,
+ /** Row version the update supersedes, and the one it writes above it. */
+ oldY: -1.6,
+ newY: -0.78,
+ /** Line pointers of those two versions (their offsets in the page, minus one). */
+ oldPointer: 2,
+ newPointer: 3,
+ pointerY: 2.72,
+ /** The write-ahead log runs under the page. */
+ walY: -4.6,
+} as const;
+
+/** Width of the page's contents, inside its outline. */
+export const HEAP_INNER = HEAP.w - 0.36;
+
+export const pointerX = (index: number) => -HEAP_INNER / 2 + 0.25 + index * 0.62;
+
+/** Both index trees: three levels over a strip of the heap rows they point to. */
+export const TREE = {
+ levelY: [2.5, 0.95, -0.6],
+ rowY: -2.75,
+ btreeX: -3.1,
+ rumX: 3.5,
+ btreeInner: [-1.45, 1.45],
+ btreeLeaves: [-2.4, -1.45, -0.5, 0.5, 1.45, 2.4],
+ /** The path an _id lookup takes: second internal page, fifth leaf. */
+ pkInner: 1,
+ pkLeaf: 4,
+ rows: 12,
+} as const;
+
+export const rowX = (index: number) => -5.5 + (index * 11) / (TREE.rows - 1);
+
+/** World-space stops of the primary-key lookup: root, internal page, leaf, heap row. */
+export function pkLookupPath() {
+ const x = TREE.btreeX;
+ return [
+ new Vector3(x, Y.index + TREE.levelY[0], 0),
+ new Vector3(x + TREE.btreeInner[TREE.pkInner], Y.index + TREE.levelY[1], 0),
+ new Vector3(x + TREE.btreeLeaves[TREE.pkLeaf], Y.index + TREE.levelY[2], 0),
+ new Vector3(rowX(TREE.pkLeaf), Y.index + TREE.rowY, 0),
+ ];
+}
+
+/**
+ * The way from the phone into the machine: down from the phone's bottom edge
+ * to the mouth of the aisle, along the aisle into the front of the last rack,
+ * and on to its heart, where the spine begins.
+ */
+export function entryRoute() {
+ const bottom = PHONE.y - PHONE.h / 2 - 0.06;
+ const mouth = new Vector3(0, HALL.port, HALL.mouth);
+ return {
+ link: new CatmullRomCurve3([
+ new Vector3(PHONE.x, bottom, PHONE.z - 0.04),
+ new Vector3(0, bottom - 1.25, 7.3),
+ new Vector3(0, -3.7, 10.6),
+ new Vector3(0, -5.8, 13.1),
+ new Vector3(0, HALL.port + 0.06, 12.75),
+ mouth,
+ ]),
+ mouth,
+ front: new Vector3(0, HALL.port, HALL.rack.d / 2),
+ heart: new Vector3(0, HALL.port, 0),
+ };
+}
+
+export interface Frame {
+ /** Film time in seconds, 0..DURATION. Everything choreographed keys on it. */
+ t: number;
+ /** Free-running clock for ambient motion that never has to line up. */
+ time: number;
+ dt: number;
+ /** Completed loops; the phone only resets its screen after the first. */
+ loop: number;
+ /** 0..1 while the camera stands back to show the whole stack. */
+ finale: number;
+}
+
+export interface Station {
+ group: Group;
+ update(frame: Frame): void;
+}
+
+export interface Kit {
+ tex: TextureKit;
+ /** The light the camera follows; stations attach things to it. */
+ signal: Signal;
+ /** Constrained device: fewer particles, smaller textures, no bloom. */
+ low: boolean;
+ /**
+ * Narrow screen: the film plays in a third of the width, so a few labels are
+ * drawn larger and anything that would stick out of the frame moves inside.
+ */
+ compact: boolean;
+}
diff --git a/app/why-document-databases/page.tsx b/app/why-document-databases/page.tsx
new file mode 100644
index 0000000..501489b
--- /dev/null
+++ b/app/why-document-databases/page.tsx
@@ -0,0 +1,77 @@
+import fs from "node:fs";
+import path from "node:path";
+import Link from "next/link";
+import Markdown from "../components/Markdown";
+import StructuredData, { articleStructuredData } from "../components/StructuredData";
+import { headingAnchor } from "../lib/docsAnchors";
+import { getMetadata } from "../services/metadataService";
+
+const pagePath = "/why-document-databases/";
+const description =
+ "Understand when document databases fit, how open-source DocumentDB builds on PostgreSQL, and how APIs, licensing, and hosting shape your choices.";
+
+export const metadata = getMetadata({
+ title: "Why Document Databases? - DocumentDB",
+ description,
+ path: pagePath,
+ type: "article",
+});
+
+export default function WhyDocumentDatabasesPage() {
+ const sourcePath = "content/why-document-databases.md";
+ const content = fs.readFileSync(path.join(process.cwd(), sourcePath), "utf8");
+ const title = content.match(/^# (.+)$/m)![1];
+ const sections = [...content.matchAll(/^## (.+)$/gm)].map((match) => match[1]);
+
+ return (
+
+
+
+
+ Document database fundamentals
+
+
+
+
+
+
+ Get started with DocumentDB
+
+
+ Install & download
+
+
+
+
+
+
+
+ );
+}
diff --git a/blogs/_data/nav.json b/blogs/_data/nav.json
index 72c2d19..8cfe72b 100644
--- a/blogs/_data/nav.json
+++ b/blogs/_data/nav.json
@@ -1,5 +1,6 @@
{
"links": [
+ { "label": "Why documents?", "href": "/why-document-databases" },
{ "label": "Docs", "href": "/docs" },
{ "label": "Install & Download", "href": "/packages" },
{ "label": "AI", "href": "/ai" },
diff --git a/content/why-document-databases.md b/content/why-document-databases.md
new file mode 100644
index 0000000..73789be
--- /dev/null
+++ b/content/why-document-databases.md
@@ -0,0 +1,248 @@
+# Why are there so many document databases?
+
+Modern applications often start with documents: a JSON customer profile, a product with nested attributes, an article with tags and permissions, or an AI record with an embedding. Document databases store and query these objects in a form close to the application model.
+
+Their appeal is not simply avoiding tables. For suitable workloads, they reduce the distance between how an application represents information and how its database stores and retrieves it.
+
+**MongoDB helped bring this approach into mainstream development.** It did not invent document databases, but popularized a compelling combination of flexible documents, collections, document-oriented operations, and accessible drivers. Its [document model and query capabilities](https://www.mongodb.com/docs/manual/) remain an important reference for compatible implementations.
+
+That ecosystem represents years of investment in code, tools, and expertise. MongoDB API compatibility can preserve some of that investment while offering a different engine, operating model, or license. It is a bridge to more choices, not the only reason to build another document database.
+
+The document model does not require one engine or hosting provider. The open-source [DocumentDB project](https://github.com/documentdb/documentdb) illustrates another approach: selected MongoDB wire-protocol commands and compatible drivers, backed by PostgreSQL and distributed under the MIT License. It builds on a familiar development experience while giving organizations an implementation they can inspect, operate, and extend.
+
+*Open-source DocumentDB, Amazon DocumentDB, and Azure DocumentDB are distinct products. Amazon DocumentDB is an AWS managed service; Azure DocumentDB describes itself as a managed service built on the open-source DocumentDB foundation. Shared names and API compatibility do not imply identical implementations or features.*
+
+## Why choose a document database?
+
+A document contains fields, nested objects, and arrays. Records in one collection can have different attributes:
+
+```json
+{
+ "_id": "camera-104",
+ "category": "camera",
+ "name": "Compact travel camera",
+ "specifications": {
+ "resolutionMegapixels": 24,
+ "weatherSealed": true
+ },
+ "tags": ["travel", "photography"]
+}
+```
+
+A book in the same catalog might have an author and ISBN instead of camera specifications. Documents accommodate that variation without a column for every possible attribute or a table for every category.
+
+The practical benefits are:
+
+- **Evolving attributes:** optional fields can be added without a database-wide table-schema change.
+- **Nested objects:** related information commonly read together can be stored together.
+- **Heterogeneous records:** each record retains its relevant attributes.
+- **Document-oriented queries:** applications can filter, project, and aggregate through an API suited to the model.
+
+Flexible storage does not mean "no schema." Applications still need consistent field names, types, required values, and versioning.
+
+Nor is document storage exclusive to dedicated document databases. PostgreSQL already provides [JSON, JSONB, document operators, and indexing](https://www.postgresql.org/docs/current/datatype-json.html). Applications that prefer SQL can combine relational and document-shaped data directly.
+
+But JSONB is not BSON, and PostgreSQL does not natively expose the MongoDB wire protocol. DocumentDB adds BSON support, collection management, document operations, indexing behavior, and a gateway for selected MongoDB commands. Its value is a document-database interface and implementation, not merely storing JSON.
+
+## One data model, different interfaces and deployment choices
+
+[Document-oriented databases](https://en.wikipedia.org/wiki/Document-oriented_database) form a broad category, not a shared application interface. Similar documents do not make clients, queries, or deployments interchangeable.
+
+| Database or API | Interface | Moving a MongoDB application |
+|---|---|---|
+| **Amazon DynamoDB** | Flexible items and nested attributes through DynamoDB operations and AWS SDKs. | Adapt database calls and access patterns. |
+| **Azure Cosmos DB for NoSQL** | Cosmos DB APIs with their own partitioning, consistency, and throughput model. | Replace or translate MongoDB calls and reassess behavior. |
+| **Azure Cosmos DB for MongoDB** | MongoDB wire protocol and existing MongoDB drivers. | Retain some client code; test supported operations and semantics. |
+| **Apache CouchDB** | RESTful HTTP operations, document revisions, and conflict handling. | Adapt operations and revision handling. |
+| **Couchbase** | JSON documents queried with SQL++ and other interfaces. | Adapt queries and database calls; SQL++ is not a MongoDB aggregation pipeline. |
+
+These differences affect application design. [DynamoDB's data model](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html) supports nested data, but its [`Query` operation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) requires a partition-key value, optionally refined by a sort-key condition. Secondary indexes provide other access paths.
+
+[Cosmos DB](https://learn.microsoft.com/en-us/azure/cosmos-db/overview) supports several APIs, so the name alone is insufficient for a compatibility comparison. [Cosmos DB for MongoDB](https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/overview) supports the MongoDB wire protocol and remains distinct from Azure DocumentDB. Microsoft directs readers considering MongoDB migrations or MongoDB Query Language features toward Azure DocumentDB.
+
+[CouchDB's HTTP API](https://docs.couchdb.org/en/stable/intro/overview.html) and [Couchbase's SQL++](https://docs.couchbase.com/server/current/n1ql/n1ql-intro/queriesandresults.html) are alternatives in the broader selection discussion, not drop-in MongoDB interfaces.
+
+### What does portability mean?
+
+Portability has four independent dimensions:
+
+- **Data:** can exports preserve identifiers, numeric types, dates, and other values? Plain JSON may lose distinctions represented in BSON.
+- **Application:** can drivers, commands, queries, and transaction behavior be retained? A shared wire protocol does not guarantee matching features or results.
+- **Deployment:** can a production-capable implementation run on-premises or with another provider?
+- **Operations:** can backup, recovery, authentication, monitoring, and provisioning workflows move too?
+
+Amazon DocumentDB supports application portability for selected MongoDB workloads, but remains an AWS service, not a self-hostable distribution of open-source DocumentDB. Its [supported-API matrix](https://docs.aws.amazon.com/documentdb/latest/devguide/mongo-apis.html) and functional differences matter more than its name.
+
+Open-source DocumentDB adds control over the implementation and infrastructure. It does not make PostgreSQL data files interchangeable with MongoDB's or remove migration testing.
+
+Local development is also different from production portability. The [Cosmos DB emulator](https://learn.microsoft.com/en-us/azure/cosmos-db/emulator) and [DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html) are development tools. AWS also documents [ExtendDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExtendDB.html), an independent open-source DynamoDB-compatible adapter with SQLite or PostgreSQL backends. That challenges blanket claims that DynamoDB APIs cannot run outside AWS, but the documented development image is local/CI-only, not for production or shared networks.
+
+### Preserving MongoDB APIs narrows the comparison
+
+Teams retaining MongoDB drivers should compare MongoDB itself with open-source DocumentDB, Amazon DocumentDB, Azure DocumentDB, and Cosmos DB for MongoDB.
+
+[MongoDB Atlas runs on AWS, Azure, and Google Cloud](https://www.mongodb.com/docs/atlas/reference/cloud-providers/), so multicloud hosting is not unique to DocumentDB. Choosing a provider within one service, switching implementations, and obtaining permissive rights to operate or redistribute an engine are different freedoms.
+
+**Choose the document model for the data, the API for the application, and the deployment and license for the organization's requirements.** DynamoDB or Cosmos DB can be a strong fit when their access models and managed capabilities match the workload.
+
+## More than a JSON storage wrapper
+
+Open-source DocumentDB combines a document-aware interface with PostgreSQL's database machinery:
+
+```text
+Application using a MongoDB driver
+ |
+ MongoDB wire protocol
+ |
+ DocumentDB Rust gateway
+ |
+ PostgreSQL queries and DocumentDB functions
+ |
+ BSON types, document operations, and indexes
+ |
+ PostgreSQL
+```
+
+### BSON participates in PostgreSQL's type system
+
+BSON represents nested documents and typed values beyond plain JSON, including binary data and additional numeric and identifier types.
+
+DocumentDB's core extension [registers a PostgreSQL BSON type](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/pg_documentdb_core/sql/types/bson--0.10-0.sql) with text and binary input/output functions. [Collection creation](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/pg_documentdb/src/commands/create_collection_core.c#L319-L369) creates PostgreSQL tables with BSON `document` and `object_id` columns. The table has a defined structure; documents within its rows can vary.
+
+### Familiar drivers, a different backend
+
+The Rust gateway translates MongoDB wire-protocol operations into PostgreSQL calls. Its [query catalog](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/pg_documentdb_gw/documentdb_gateway_core/src/postgres/query_catalog.rs#L674-L683) covers inserts, finds, updates, deletes, and aggregation; the quickstart connects with PyMongo.
+
+Driver compatibility does not promise every MongoDB feature or identical behavior. Test the application's commands, query semantics, transactions, and drivers before migrating. The gateway is not a REST API: a browser application still needs a service for HTTP, authentication, and business logic.
+
+### Queries and indexes execute in the database
+
+The [aggregation implementation](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/pg_documentdb/src/aggregation/bson_aggregation_pipeline.c) generates backend queries for stages such as `$match`, `$project`, and `$group`. [Index-handler selection](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/pg_documentdb/src/commands/create_indexes.c#L699-L734) integrates document indexes with PostgreSQL access methods, selecting a RUM-based handler by default.
+
+Applications need not fetch every document to inspect its fields. Performance still depends on selectivity, indexes, document size, updates, and supported optimizations; indexes consume storage and add write overhead.
+
+### Flexibility can include validation
+
+The [validation implementation](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/pg_documentdb/src/schema_validation/schema_validation.c#L28-L103) checks updated documents against configured validators and distinguishes validation modes. Optional attributes can coexist with enforced invariants, but availability depends on the release and configuration; the code includes a feature gate.
+
+### Vector search builds on extensions
+
+The source defines [IVFFlat and HNSW vector indexes](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/pg_documentdb/src/vector/vector_index_kind_impl.c#L108-L130) and [index expressions](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/pg_documentdb/src/vector/vector_utilities.c#L145-L220) that extract document vectors and use PostgreSQL vector types and distance operators.
+
+Content, metadata, and similarity search can share one database system. Embedding generation, access control, and retrieval quality remain application responsibilities.
+
+These source references describe the inspected revision, not a guarantee that every packaged release or managed service enables every capability.
+
+## Which applications benefit most?
+
+[Common document-database use cases](https://docs.aws.amazon.com/documentdb/latest/devguide/document-database-use-cases.html) follow from data shape and access patterns:
+
+| Application | Why documents fit | Design boundary |
+|---|---|---|
+| **Profiles and preferences** | Optional attributes and nested settings read together. | Keep unbounded activity histories separate. |
+| **Product catalogs** | Category-specific specifications with common search fields. | Standardize filter, sort, and validation fields. |
+| **Content management** | Shared metadata with type-specific fields. | Store large media in object storage and keep references. |
+| **Events and telemetry** | Evolving payloads filtered and aggregated near ingestion. | Plan retention, throughput, and analytical costs. |
+| **AI knowledge applications** | Content, provenance, metadata, and embeddings associated with records. | Own retrieval quality, authorization, and model integration. |
+
+The strongest fit is often an **application aggregate**: a bounded object whose information belongs together and is commonly retrieved together.
+
+Extensive joins, shared entities requiring consistent updates, and database-enforced relationships may favor relational tables. Embedding can simplify reads, but excessive embedding creates oversized documents, duplication, and expensive updates.
+
+The question is not whether documents beat tables, but which representation fits the application's consistency and access requirements.
+
+## Why PostgreSQL underneath matters
+
+DocumentDB separates the application's document interface from its storage engine. It reuses PostgreSQL's storage, transactions, query execution, and extension infrastructure while adding document-specific behavior.
+
+Teams familiar with PostgreSQL gain a recognizable operational foundation, not automatic compatibility with every existing tool. Validate extensions, metadata, and gateway behavior; a successful PostgreSQL restore must also recover a working DocumentDB system.
+
+PostgreSQL underneath does not guarantee full MongoDB transaction semantics, effortless horizontal scaling, or managed-service availability. Those depend on the implementation and deployment.
+
+**The advantage is a mature foundation, not exemption from database engineering.**
+
+## MIT licensing, and where SSPL changes the calculation
+
+The project's [MIT License](https://github.com/documentdb/documentdb/blob/a5f1636269e5062fa22a24bfa4d58d3cc92a0bc7/LICENSE) permits use, modification, distribution, sublicensing, and sale, provided the required notices are preserved.
+
+Organizations can operate DocumentDB themselves, package it with commercial products, adapt it, or build hosting and support services. MIT does not require publishing the surrounding application or hosting stack merely because the database is offered as a service. Dependencies have separate licenses to review.
+
+The **Server Side Public License (SSPL)** differs. [Section 13](https://www.mongodb.com/legal/licensing/server-side-public-license) requires the defined "Service Source Code" to be made available under SSPL when the program's functionality is offered to third parties as a service. That definition includes management, monitoring, backup, and hosting software.
+
+This is especially relevant to database-hosting businesses. It does **not** mean every application using an SSPL database must publish all its code. Obligations depend on the offering; obtain legal review for a specific business model.
+
+The [Open Source Initiative does not recognize SSPL as an open-source license](https://opensource.org/blog/the-sspl-is-not-an-open-source-license). Readable source and permissively licensed open source are different propositions. MIT reduces this licensing friction, but supplies neither a warranty nor database operations.
+
+## The opportunity: owning database-backed applications
+
+The goal is not for every organization to invent a database engine. It is to let teams adopt, inspect, operate, and, when necessary, adapt the database their applications depend on.
+
+A permissively licensed implementation of a familiar interface broadens participation: application teams gain deployment choices, vendors can support customer-hosted environments, and contributors can build on a shared foundation. It combines the developer experience MongoDB helped establish with PostgreSQL infrastructure.
+
+Teams can start locally, test real queries, and understand the implementation before committing to production hosting. This suits on-premises software, private environments, and established PostgreSQL operations.
+
+Ownership does not require avoiding the cloud. An application can use cloud compute, storage, identity, and monitoring with a self-operated database, or choose managed database operations when they offer better value. The starting point is an application requirement, not a hosting commitment.
+
+## When managed hosting is the better choice
+
+Self-hosting is not automatically cheaper or safer. Production databases need patching, capacity planning, access management, monitoring, verified backups, incident response, and recovery exercises.
+
+Managed services can help small teams protect development time, meet demanding availability and recovery objectives, handle capacity changes, and integrate enterprise controls. Their value depends on service limits, pricing, and the surrounding application.
+
+[Amazon DocumentDB](https://docs.aws.amazon.com/documentdb/latest/devguide/what-is.html) supports selected MongoDB APIs and drivers, with automated backups, point-in-time recovery, replica failover, VPC isolation, and AWS KMS encryption. [Azure DocumentDB](https://azure.microsoft.com/en-us/products/documentdb) offers an open-source-based managed service with availability options, backups, scaling, and Azure integrations.
+
+Evaluate operations, regional availability, recovery objectives, performance, migration effort, and total cost. A managed service's features do not automatically belong to a standalone open-source deployment.
+
+### Cloud providers and specialist database vendors
+
+Cloud-provider services are not the only managed choices:
+
+| Service | Distinctive consideration | Evaluate |
+|---|---|---|
+| **Azure DocumentDB** | Azure-managed, built on open-source DocumentDB. | Application behavior, tiers, and differences from self-hosting. |
+| **Amazon DocumentDB** | AWS-managed, supporting selected MongoDB APIs. | Commands, semantics, cluster capabilities, and AWS operational fit. |
+| **MongoDB Atlas** | MongoDB's vendor-operated service on AWS, Azure, and Google Cloud. | Required features, deployment options, integrations, and cost. |
+| **Couchbase Capella** | SQL++, search, eventing, and mobile/edge synchronization options. | Workload fit and the cost of changing application interfaces. |
+
+[Atlas documents its cloud choices](https://www.mongodb.com/docs/atlas/reference/cloud-providers/); [Capella describes its capabilities](https://docs.couchbase.com/cloud/get-started/intro.html) and [provider and networking options](https://docs.couchbase.com/cloud/clusters/create-database.html).
+
+Backups, scaling, and private networking are not exclusive to a cloud provider's own database. Compare database capabilities and the integration work that remains.
+
+### What does the cloud ecosystem buy?
+
+Usually, less integration and operational work across the application, not automatically faster document queries:
+
+- **Identity and governance:** Azure DocumentDB supports [Entra ID and managed identities](https://learn.microsoft.com/en-us/azure/documentdb/how-to-connect-role-based-access-control). Amazon DocumentDB exposes [resource-management permissions through IAM](https://docs.aws.amazon.com/documentdb/latest/devguide/security-iam.html). Resource administration and record access are different permission layers.
+- **Private connectivity:** Azure documents [Private Link](https://learn.microsoft.com/en-us/azure/documentdb/how-to-private-link); Amazon DocumentDB runs in a VPC. [Atlas also supports private endpoints](https://www.mongodb.com/docs/atlas/security-private-endpoint/) on supported deployments. Latency and transfer costs depend on region, routing, and pricing.
+- **Monitoring:** Azure DocumentDB can send [diagnostics to Azure Monitor and Log Analytics](https://learn.microsoft.com/en-us/azure/documentdb/how-to-monitor-diagnostics-logs). Configuration and tier restrictions apply; integration is not automatic end-to-end tracing.
+- **Event processing:** [Lambda can process Amazon DocumentDB change streams](https://docs.aws.amazon.com/lambda/latest/dg/with-documentdb.html). Engine and cluster restrictions apply, and at-least-once delivery requires handlers that tolerate duplicates.
+- **Procurement and support:** a database may fit existing purchasing, inventories, cost allocation, and support workflows. Check contracts and charges; specialist vendors may fit those workflows too.
+
+Specialists offer many of the same connections. [Atlas supports AWS IAM database authentication](https://www.mongodb.com/docs/atlas/security/aws-iam-authentication/), including application roles on AWS compute. This is not "cloud integration versus no integration."
+
+The tradeoff is **database strengths, integration effort, and platform dependence**. Cloud identities and event mappings can simplify work now and complicate a later move. A specialist service can preserve an interface across clouds while creating dependencies on its own management platform. Neither eliminates lock-in or guarantees lower cost.
+
+An integrated service may be simplest for a team already operating in Azure or AWS. A specialist may better fit particular features or multicloud management. Customer-hosted deployments and direct engine control are reasons to consider open-source DocumentDB.
+
+The complete system remains larger than its database:
+
+```text
+Web, mobile, or AI client
+ |
+Application service / HTTP API
+ |
+ Document database
+ |
+Identity, monitoring, backups, object storage,
+event processing, and cloud AI or analytics
+```
+
+## Start with the application, keep deployment choices open
+
+There are many document databases because the document model solves a recurring application problem, while organizations need different implementations, licenses, and operating models.
+
+Open-source DocumentDB combines a document-oriented interface, BSON and document operations integrated with PostgreSQL, and MIT licensing. It does not promise every workload will be faster or every deployment simpler. It offers meaningful control over software and infrastructure.
+
+Start with the [quickstart](/docs/getting-started/): build a representative application, test compatibility, measure real queries, and verify recovery. Then choose self-hosting or a managed service according to production requirements.
+
+**Choose documents because they fit the application. Choose hosting because it fits the organization.**
diff --git a/package-lock.json b/package-lock.json
index e7d32a8..bbdd555 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,7 +20,8 @@
"react-syntax-highlighter": "^16.1.0",
"remark": "^15.0.1",
"remark-gfm": "^4.0.1",
- "strip-markdown": "^6.0.0"
+ "strip-markdown": "^6.0.0",
+ "three": "^0.187.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.3.3",
@@ -32,6 +33,7 @@
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@types/react-syntax-highlighter": "^15.5.13",
+ "@types/three": "^0.187.0",
"autoprefixer": "^10.4.23",
"eslint": "^10.8.0",
"eslint-config-next": "^16.2.12",
@@ -398,6 +400,13 @@
"keyv": "^5.6.0"
}
},
+ "node_modules/@dimforge/rapier3d-compat": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
+ "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
@@ -2708,6 +2717,13 @@
"node": "^10 || ^12 || >=14"
}
},
+ "node_modules/@tweenjs/tween.js": {
+ "version": "23.1.3",
+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@tybys/wasm-util": {
"version": "0.10.3",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
@@ -2869,12 +2885,41 @@
"@types/react": "*"
}
},
+ "node_modules/@types/stats.js": {
+ "version": "0.17.4",
+ "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/three": {
+ "version": "0.187.0",
+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.187.0.tgz",
+ "integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@dimforge/rapier3d-compat": "~0.12.0",
+ "@tweenjs/tween.js": "~23.1.3",
+ "@types/stats.js": "*",
+ "@types/webxr": ">=0.5.17",
+ "fflate": "~0.8.3",
+ "meshoptimizer": "~1.1.1"
+ }
+ },
"node_modules/@types/unist": {
"version": "2.0.11",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
"integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
"license": "MIT"
},
+ "node_modules/@types/webxr": {
+ "version": "0.5.24",
+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.65.0.tgz",
@@ -5753,6 +5798,13 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/fflate": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/file-entry-cache": {
"version": "11.1.5",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz",
@@ -7889,6 +7941,13 @@
"node": ">= 8"
}
},
+ "node_modules/meshoptimizer": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
+ "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/micromark": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",
@@ -10464,6 +10523,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/three": {
+ "version": "0.187.0",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz",
+ "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==",
+ "license": "MIT"
+ },
"node_modules/tinybench": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz",
diff --git a/package.json b/package.json
index 2f1f9b5..21575f3 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,8 @@
"react-syntax-highlighter": "^16.1.0",
"remark": "^15.0.1",
"remark-gfm": "^4.0.1",
- "strip-markdown": "^6.0.0"
+ "strip-markdown": "^6.0.0",
+ "three": "^0.187.0"
},
"overrides": {
"string-width": "^5.1.2"
@@ -45,6 +46,7 @@
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@types/react-syntax-highlighter": "^15.5.13",
+ "@types/three": "^0.187.0",
"autoprefixer": "^10.4.23",
"eslint": "^10.8.0",
"eslint-config-next": "^16.2.12",
diff --git a/public/images/campaign-film-poster.webp b/public/images/campaign-film-poster.webp
new file mode 100644
index 0000000..d7371a7
Binary files /dev/null and b/public/images/campaign-film-poster.webp differ
diff --git a/readme.md b/readme.md
index 63b2586..7f69fd4 100644
--- a/readme.md
+++ b/readme.md
@@ -26,6 +26,25 @@ Use the following fixed prompt set for manual evaluations. Record platform/model
Save evaluation results outside the published site, compare a small changed-page cohort with unchanged pages, and repeat before expanding content. Private search-console data, referral analytics and verified crawler logs can supplement these observations; the static site does not collect model citation or task-success measurements automatically.
+## Agent landing page
+
+The standalone agent landing page is at `/campaigns/landing/`. It includes the
+Starter article summary, retail storefront and AI-memory prompt carousel,
+folded resource links, and the local article at `/why-document-databases/`.
+The polished article is maintained in `content/why-document-databases.md`.
+
+The 20 KB film poster loads first; Three.js and WebGL initialize only after
+Play. Carousel rotation and film playback remain independent. This page has
+no Waline or campaign-collector dependency and requires no hosting changes.
+Its existing noindex/nofollow metadata is preserved.
+
+Both prompts use the published Agent-Kit repository pinned to
+`d10f02a9fcd1694b390658d9098a6945948eff97` and the tested gallery revision.
+The retail and text/tag/regex memory flows passed independent end-to-end
+checks with Claude Sonnet 5.5 and GPT-5.6 Sol. Those runs used the authorized
+local Agent-Kit mirror at the identical commit after remote clones were blocked;
+public cold-clone access and optional Ollama semantic mode were not verified.
+
## Prerequisites for Development
- **[Node.js](https://nodejs.org/)** (*20 or higher*)
diff --git a/tests/campaignFilm.test.tsx b/tests/campaignFilm.test.tsx
new file mode 100644
index 0000000..4d07c23
--- /dev/null
+++ b/tests/campaignFilm.test.tsx
@@ -0,0 +1,308 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { createElement } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { Vector3 } from 'three';
+import { describe, expect, it } from 'vitest';
+import CampaignFilm from '../app/components/campaign/CampaignFilm';
+import { narration } from '../app/components/campaign/filmContent';
+import { CUE, DURATION, SHOTS, STILL_AT, finaleAt, shotIndexAt } from '../app/components/campaign/scene/film';
+import { Rig } from '../app/components/campaign/scene/rig';
+import { Signal } from '../app/components/campaign/scene/signal';
+
+const campaignDir = path.join(import.meta.dirname, '../app/components/campaign');
+const read = (file: string) => fs.readFileSync(path.join(campaignDir, file), 'utf8');
+// The way React's server renderer escapes text.
+const escapeHtml = (text: string) => text
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''');
+
+// A page chooses only the copy and the links beside the film.
+function render(copy = { tagline: 'Tagline', heading: 'Heading', description: 'Description', primary: 'Primary', secondary: 'Secondary' }) {
+ return renderToStaticMarkup(createElement(CampaignFilm, {
+ tagline: copy.tagline,
+ heading: copy.heading,
+ description: copy.description,
+ primary: { label: copy.primary, href: '/docs/getting-started/' },
+ secondary: { label: copy.secondary, href: '/packages/' },
+ }));
+}
+
+/** The film's own markup: its control, its narration and its written fallback. */
+const filmPart = (html: string) => html.slice(html.indexOf('