Files
hyperframes/docs/catalog/blocks/spiral-galaxy.mdx
Miguel ÁngelandMiguel Angel Simon Sierra 1ae2067b8d feat(catalog): put the variables panel back, on payloads (#3199)
* feat(catalog): put the variables panel back, on payloads

The panel drove its preview by loading an .html from docs/public, a type the
host does not publish, so it showed an empty frame in production and was
parked when the catalog was re-landed.

It now mounts the same JSON payload the plain player uses and re-mounts it as
values change, injecting them as window.__hfVariables into the composition head
before any of its scripts run, which is where the runtime reads overrides from.
Doing it in the markup rather than after load is what stops the composition
initialising with the wrong values first.

172 items with variables get the panel back; the playhead carries across a
change so a tweak mid-shot does not jump back to frame zero.

* fix(docs): drop the unused url form and the needless escapes

* fix(docs): the panel cannot reference a binding beside the export

* feat(catalog): make importing an SVG the obvious move

A reader arrives at this control with a shape, not with path data, and the
panel asked for the coordinates first. Import is now the primary action in a
drop target you can see is a drop target, and the raw path sits behind a
disclosure for anyone who wants it.

* feat(cli): let a fruitless catalog search report the gap

An agent that searches by meaning and finds nothing worth installing knows
something we do not: the name of a move the catalog is missing. There was no
way to tell us, so that knowledge was lost at the end of every run.

hyperframes feedback --search-miss "<query>" --wanted "<the move>" records it.
It carries no rating, so it never lands in the rating metric, and it is a
separate deliberate command rather than something catalog --query does on its
own: plain search still sends nothing, which is what the CLI promises.

--rating stops being required at the arg level, since a miss has no rating to
give. The check moved into the run body, where an absent one is now handled
rather than crashing on undefined.

* feat(cli): carry tuned variable values into the install snippet

Someone who tunes a block on its catalog page had no way to keep those values:
the install command was the same one everybody gets, and the tuning stayed on
the page.

hyperframes add <item> --vars '<json>' now prints a mount element carrying
data-variable-values, so the values land where the block is used.

They ride on the host rather than being written into the installed file. That
keeps the composition on disk byte-identical to the registry's, so a later
reinstall can still tell an edit from an update, and it lets two mounts of the
same block carry different values.

* fix(catalog): serve the item's own directory so runtime paths resolve

Some compositions assemble their asset URLs at run time —
"compositions/components/" + texture + ".png" for the texture masks, a font the
compiler pulled into _remote_media — and no scan of the markup can see a string
that does not exist until a script concatenates it. Those items either rendered
black or were dropped to a video that had never been uploaded.

Each item that needs it now has its prepared directory published, and its
payload carries a <base> pointing at it, so any relative path the composition
invents resolves. caption-texture renders its masks again, and
variable-font-flex has a preview at all for the first time: its MP4 and poster
are both 403.

Both layouts are published, because which one a composition asks for differs
per item, and a directory only earns that if it is under 2 MB. The 12 MB
texture sheet keeps the recorded video it already had.

* fix(catalog): let the variables panel actually drive the composition

Every control on the panel was inert. The values reached the composition and
nothing repainted, because the payload had already been compiled: compiling
inlines a mounted component and resolves its variables into the markup and CSS,
so by the time a reader turns a knob there is nothing left to change.

An item that declares variables now ships uncompiled, keeping the mount the
runtime loads at run time, which is the only state where data-variable-values
still means anything. The component travels inline as a data URI rather than a
sibling file, because .html is the one type the docs host will not publish. The
demo's own pinned values come off, so the reader's choices reach the mount
instead of losing to the values the demo picked to show itself off.

Measured on the rendered frame rather than the DOM: green rgb(98,207,144),
blue rgb(6,6,199), violet rgb(177,147,230), and back to green.

docs/public/catalog drops from 48 MB to 35 MB along the way, since an
uncompiled payload carries far less than an inlined one.

* feat(catalog): keep variable changes in the url

A reader who tuned a piece lost it on reload, and had nothing to send anyone.
The values now live in the query string, scoped by composition id so two links
never read each other,and only the ones that differ from the defaults are
written, so changing one knob gives a short URL rather than every variable
spelled out.

replaceState rather than pushState: dragging a slider should not leave a trail
of history entries. An unreadable value is ignored rather than thrown, so a
truncated or hand-edited link opens the piece at its defaults.

* fix(catalog): only rewrite the url when a value actually changed

* refactor(catalog): memoise the declared defaults on their content

* feat(catalog): offer an install command carrying the tuned values

The Install block is generated before anyone touches a knob, so it can only
ever print the plain command. Someone who spent a minute tuning a piece copied
it and got the defaults back.

The panel now carries its own command in the Snippet tab, with --vars holding
exactly the values that differ. An untouched piece still offers the same short
command, so nothing gets noisier for the common case.

* fix(catalog): a piece with nothing to render is a skip, not a failure

caption-blend-difference is a stylesheet and a paragraph of prose — a class you
add to your own captions, with no standalone scene to show. The generator
treated that as a build failure, so every run ended by reporting something
broken when nothing was.

It now reports the shape it is and keeps its recorded video, which is the only
honest preview such an item has. A genuine render failure still throws.

* fix(catalog): restore variables from the url on a cold load

A shared link opened at the defaults. The first render happens on the server,
where there is no window to read the query string from, and React then hydrates
against that markup and never revisits it — so the values only appeared once you
touched a control.

The URL is read again after mount, which is the first moment it exists. The
value is also escaped once now rather than twice: URLSearchParams already
decodes on the way out, and decoding a second time turned an SVG path full of
percent-escapes into something that no longer parsed, besides doubling the
length of every link.

* fix(catalog): mount the preview with the values a link carried

The frame was built from the declared defaults and the shared values were
posted to it afterwards, which is too late for anything the composition reads
once at init: a path arrived after the mark had already been drawn from the
default one, so a link looked right in the panel and wrong on screen.

* feat(catalog): the install command follows the values you tuned

Copying the Install line gave the plain command back, because that block is
generated before anyone touches a knob and had no way to know what changed. The
tuned command only existed in the panel Snippet tab, which is not where anyone
looks for it.

The line now reads the same query string the panel writes, so the two agree
without either component knowing the other exists, and a shared link carries the
right command too. replaceState fires no event, so the panel announces its own
writes.

* fix(catalog): send a text variable to the preview once it is finished

Every other control in the explorer reports a whole value on every event: a
slider at any position is a position, a swatch is a colour. A text field is
not. Typing v3 into a badge posted v first, so the preview remounted and
rendered a composition built from half a word.

The post now waits while a text field has focus and goes out when the edit is
committed, with Enter or by clicking away. The field itself is unchanged and
still tracks every keystroke.

---------

Co-authored-by: Miguel Angel Simon Sierra <miguelangelsi07@gmail.com>
2026-08-10 22:40:01 -04:00

726 lines
30 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Spiral Galaxy"
description: "A spiral galaxy seen from outside, turning with real differential rotation: inner stars orbit faster than outer ones, so the arms wind up over the shot instead of spinning rigidly. 20,000 additive GPU sprites, seeded once and solved directly from time, so any frame can be rendered on its own."
---
import { InstallCommand } from "/snippets/install-command.jsx";
import { VariablesExplorer } from "/snippets/variables-explorer.jsx";
<VariablesExplorer
previewSrc="/public/catalog/blocks/spiral-galaxy.json"
compositionId="spiral-galaxy"
compositionSrc="compositions/spiral-galaxy.html"
variables={[{"id":"stars","type":"number","label":"Star count","default":20000,"min":2000,"max":40000,"step":1000},{"id":"arms","type":"number","label":"Arm count","default":3,"min":2,"max":8,"step":1},{"id":"rate","type":"number","label":"Rotation rate","default":0.25,"min":0,"max":1.5,"step":0.05,"unit":"rad/s"},{"id":"glow","type":"number","label":"Core brightness","default":1.9,"min":0.2,"max":4,"step":0.1},{"id":"size","type":"number","label":"Star size","default":10,"min":2,"max":40,"step":1,"unit":"px"},{"id":"core","type":"color","label":"Core colour","default":"#ffa575"},{"id":"rim","type":"color","label":"Rim colour","default":"#311599"}]}
>
```html spiral-galaxy.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=1920, height=1080" />
<title>Spiral Galaxy</title>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.147.0/build/three.min.js"></script>
<style>
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 1920px;
height: 1080px;
overflow: hidden;
background: #03040a;
}
#sg-root {
position: relative;
width: 1920px;
height: 1080px;
overflow: hidden;
}
/* Full-bleed child carries the scene fill; never the composition root. */
#sg-fill {
position: absolute;
inset: 0;
background: #03040a;
}
#sg-gl {
position: absolute;
inset: 0;
display: block;
width: 1920px;
height: 1080px;
}
/* Ambient halo in the rim colour, screen-blended over the point cloud.
Reads the declared `rim` variable. Variable ids are single lowercase
words on purpose: the runtime injects `--<id>` while the compiler
injects `--<slugify(id)>`, and those two only agree when the id has
no capitals or separators. */
#sg-halo {
position: absolute;
inset: 0;
mix-blend-mode: screen;
opacity: 0.12;
background: radial-gradient(72% 46% at 50% 50%, var(--rim, #311599) 0%, #000000 70%);
}
</style>
</head>
<body>
<div
id="sg-root"
data-composition-id="spiral-galaxy"
data-composition-variables='[
{"id":"stars","type":"number","label":"Star count","default":20000,"min":2000,"max":40000,"step":1000},
{"id":"arms","type":"number","label":"Arm count","default":3,"min":2,"max":8,"step":1},
{"id":"rate","type":"number","label":"Rotation rate","default":0.25,"min":0,"max":1.5,"step":0.05,"unit":"rad/s"},
{"id":"glow","type":"number","label":"Core brightness","default":1.9,"min":0.2,"max":4,"step":0.1},
{"id":"size","type":"number","label":"Star size","default":10,"min":2,"max":40,"step":1,"unit":"px"},
{"id":"core","type":"color","label":"Core colour","default":"#ffa575"},
{"id":"rim","type":"color","label":"Rim colour","default":"#311599"}
]'
data-start="0"
data-duration="10"
data-width="1920"
data-height="1080"
>
<div id="sg-fill"></div>
<canvas id="sg-gl" width="1920" height="1080"></canvas>
<div id="sg-halo"></div>
<!-- Driver clip: gives the block a timed element for the host timeline. -->
<div
id="sg-drv"
class="clip"
data-start="0"
data-duration="10"
data-track-index="0"
style="position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none"
></div>
</div>
<script>
(function () {
var COMP_ID = "spiral-galaxy";
var DURATION = 10;
var W = 1920,
H = 1080;
// ── Measured constants ────────────────────────────────────────────
// Read from the three.js galaxy examples (MIT) during reference
// research; reimplemented here, nothing copied.
// count 20000 · branches 3 · radius = ratio^1.5 * 5 · spin 1
// angle = branchAngle + spin * radius + t * (1 - radiusRatio)
// randomnessPower 3 · inside #ffa575 · outside #311599
var DISC_RADIUS = 5.0; // world units, from `radius = ratio^1.5 * 5`
var RADIUS_POWER = 1.5; // ratio -> radius exponent
// Static Archimedean twist, radians per world unit. This is what draws
// the arm across the WHOLE disc; the time term below then winds it.
// Slightly under the example's 1.0 so the outer arms stay open.
var SPIN = 0.78;
var RANDOMNESS = 0.2; // arm thickness, as a fraction of DISC_RADIUS
var RANDOM_POWER = 3.0; // pow(u, 3): most stars hug the arm, a few stray
var TANGENT_SQUEEZE = 0.62; // arms are thin across, long along
var DISC_FLATNESS = 0.3; // vertical jitter relative to in-plane jitter
var SEED = 20240817; // fixes every per-star attribute
// ── Variables ─────────────────────────────────────────────────────
// Read ONCE at init. Variables never change mid-render.
var vars =
window.__hyperframes && window.__hyperframes.getVariables
? window.__hyperframes.getVariables()
: {};
function clampNum(value, lo, hi, fallback) {
var n = Number(value);
if (!isFinite(n)) n = fallback;
return Math.min(hi, Math.max(lo, n));
}
var STARS = Math.round(clampNum(vars.stars, 2000, 40000, 20000));
var ARMS = Math.round(clampNum(vars.arms, 2, 8, 3));
var RATE = clampNum(vars.rate, 0, 1.5, 0.25);
var GLOW = clampNum(vars.glow, 0.2, 4, 1.9);
var SIZE = clampNum(vars.size, 2, 40, 10);
var CORE_COLOR = typeof vars.core === "string" ? vars.core : "#ffa575";
var RIM_COLOR = typeof vars.rim === "string" ? vars.rim : "#311599";
// ── Seeded PRNG (mulberry32) ──────────────────────────────────────
function mulberry32(seed) {
return function () {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// ── Per-star attributes, seeded once ──────────────────────────────
// Nothing here depends on time. Every frame is computed from these
// plus `uTime` alone, so frame N never reads frame N-1.
var rng = mulberry32(SEED);
var aRatio = new Float32Array(STARS); // 0 = core, 1 = rim
var aBranch = new Float32Array(STARS); // base arm angle
var aJitterR = new Float32Array(STARS); // offset along the arm's radial axis
var aJitterT = new Float32Array(STARS); // offset along the arm's tangent
var aJitterY = new Float32Array(STARS); // disc thickness
var aSpark = new Float32Array(STARS); // per-star size variation
function jitter() {
var magnitude = Math.pow(rng(), RANDOM_POWER) * RANDOMNESS * DISC_RADIUS;
return rng() < 0.5 ? -magnitude : magnitude;
}
for (var i = 0; i < STARS; i++) {
aRatio[i] = rng();
aBranch[i] = ((i % ARMS) / ARMS) * Math.PI * 2;
aJitterR[i] = jitter();
aJitterT[i] = jitter() * TANGENT_SQUEEZE;
aJitterY[i] = jitter() * DISC_FLATNESS;
aSpark[i] = rng();
}
// ── Scene ─────────────────────────────────────────────────────────
var renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("sg-gl"),
antialias: false,
alpha: false,
preserveDrawingBuffer: true, // survives seek-capture screenshots
});
renderer.setPixelRatio(1);
renderer.setSize(W, H, false);
renderer.setClearColor(0x03040a, 1);
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(45, W / H, 0.1, 200);
camera.position.set(0, 2.9, 7.6);
camera.lookAt(0, 0, 0);
var uniforms = {
uTime: { value: 0 },
uRate: { value: RATE },
uSpin: { value: SPIN },
uRadius: { value: DISC_RADIUS },
uPower: { value: RADIUS_POWER },
uSize: { value: SIZE },
uRefDist: { value: camera.position.length() },
uGlow: { value: GLOW },
uCore: { value: new THREE.Color(CORE_COLOR) },
uRim: { value: new THREE.Color(RIM_COLOR) },
};
var VERT = [
"attribute float aRatio;",
"attribute float aBranch;",
"attribute float aJitterR;",
"attribute float aJitterT;",
"attribute float aJitterY;",
"attribute float aSpark;",
"uniform float uTime;",
"uniform float uRate;",
"uniform float uSpin;",
"uniform float uRadius;",
"uniform float uPower;",
"uniform float uSize;",
"uniform float uRefDist;",
"uniform float uGlow;",
"uniform vec3 uCore;",
"uniform vec3 uRim;",
"varying vec3 vColor;",
"varying float vBright;",
"void main() {",
" float ratio = clamp(aRatio, 0.0, 1.0);",
// Differential rotation. omega falls to zero at the rim, so the
// core laps the outer disc and the arms wind up over time.
// Solved directly from uTime — never integrated frame to frame.
" float omega = 1.0 - ratio;",
" float r = pow(ratio, uPower) * uRadius;",
// uSpin * r is the static arm shape (time-independent, so it drops
// out of any inner-vs-outer rotation measurement); uRate * uTime *
// omega is the winding.
" float theta = aBranch + uSpin * r + uRate * uTime * omega;",
" vec2 radial = vec2(cos(theta), sin(theta));",
" vec2 tangent = vec2(-radial.y, radial.x);",
// Jitter rides in the star's own rotating frame, so arm thickness
// holds its shape instead of smearing as the disc turns.
" vec2 xz = radial * (r + aJitterR) + tangent * aJitterT;",
" vec4 mv = modelViewMatrix * vec4(xz.x, aJitterY, xz.y, 1.0);",
" gl_Position = projectionMatrix * mv;",
" gl_PointSize = uSize * (uRefDist / max(-mv.z, 0.001)) * (0.55 + 0.75 * aSpark);",
// Lerp by r/R (i.e. ratio^1.5), matching the example's colour ramp:
// the disc stays warm well past mid-radius and only the rim goes cold.
" vColor = mix(uCore, uRim, pow(ratio, uPower));",
" vBright = uGlow * (0.22 + 0.78 * exp(-ratio * 3.0));",
"}",
].join("\n");
var FRAG = [
"varying vec3 vColor;",
"varying float vBright;",
"void main() {",
" float d = length(gl_PointCoord - vec2(0.5));",
" float a = smoothstep(0.5, 0.0, d);",
" a = a * a;",
" gl_FragColor = vec4(vColor * vBright, a);",
"}",
].join("\n");
var geometry = new THREE.BufferGeometry();
// The vertex shader builds every position from the attributes below;
// `position` exists only because three.js counts vertices from it.
geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(STARS * 3), 3),
);
geometry.setAttribute("aRatio", new THREE.BufferAttribute(aRatio, 1));
geometry.setAttribute("aBranch", new THREE.BufferAttribute(aBranch, 1));
geometry.setAttribute("aJitterR", new THREE.BufferAttribute(aJitterR, 1));
geometry.setAttribute("aJitterT", new THREE.BufferAttribute(aJitterT, 1));
geometry.setAttribute("aJitterY", new THREE.BufferAttribute(aJitterY, 1));
geometry.setAttribute("aSpark", new THREE.BufferAttribute(aSpark, 1));
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: VERT,
fragmentShader: FRAG,
blending: THREE.AdditiveBlending,
transparent: true,
depthTest: false,
depthWrite: false,
});
var points = new THREE.Points(geometry, material);
points.frustumCulled = false; // positions live in the shader, not in `position`
scene.add(points);
function draw(t) {
uniforms.uTime.value = t;
renderer.render(scene, camera);
}
// ── Timeline ──────────────────────────────────────────────────────
// `tl.eventCallback("onUpdate", ...)` does NOT fire on tl.seek(), so
// the repaint hangs off a property setter on the tweened driver —
// that setter runs on every render, seek included.
var driver = { _t: 0 };
Object.defineProperty(driver, "t", {
get: function () {
return this._t;
},
set: function (value) {
this._t = value;
draw(value);
},
});
window.__timelines = window.__timelines || {};
var tl = gsap.timeline({ paused: true });
// ease "none" over the full duration makes driver.t === tl.time().
tl.to(driver, { t: DURATION, duration: DURATION, ease: "none", lazy: false }, 0);
window.__timelines[COMP_ID] = tl;
draw(0); // paint frame 0; GSAP skips the setter when the value is unchanged
})();
</script>
</body>
</html>
```
</VariablesExplorer>
## Install
<InstallCommand command="npx hyperframes add spiral-galaxy" item="spiral-galaxy" />
That writes one file: `compositions/spiral-galaxy.html`.
## Add it to your video
It runs for 10 seconds at 1920×1080. Paste this into your composition:
```html index.html
<div
data-composition-id="spiral-galaxy"
data-composition-src="compositions/spiral-galaxy.html"
data-start="0"
data-duration="10"
data-track-index="1"
data-width="1920"
data-height="1080"
></div>
```
Move it in time with `data-start`. Put it on a different timeline row with
`data-track-index`. See [data attributes](/concepts/data-attributes) for the rest.
## Change how it looks
Set these CSS variables on the block:
- `stars` — Star count. Defaults to `20000`.
- `arms` — Arm count. Defaults to `3`.
- `rate` — Rotation rate. Defaults to `0.25`.
- `glow` — Core brightness. Defaults to `1.9`.
- `size` — Star size. Defaults to `10`.
- `core` — Core colour. Defaults to `#ffa575`.
- `rim` — Rim colour. Defaults to `#311599`.
## Variables
Every one of these has a default, so the piece works untouched. Set the ones you
want to change on the element:
| Variable | Default | Accepts | What it does |
| --- | --- | --- | --- |
| `stars` | `20000` | 2000 to 40000, step 1000 | |
| `arms` | `3` | 2 to 8, step 1 | |
| `rate` | `0.25` | 0rad/s to 1.5rad/s, step 0.05rad/s | |
| `glow` | `1.9` | 0.2 to 4, step 0.1 | |
| `size` | `10` | 2px to 40px, step 1px | |
| `core` | `#ffa575` | color | |
| `rim` | `#311599` | color | |
Set them with `data-variable-values` on the element that mounts it. These are the
defaults, so this behaves exactly like the preview above until you change one:
```html wrap
<div
data-composition-id="spiral-galaxy"
data-composition-src="compositions/spiral-galaxy.html"
data-variable-values='{"stars":20000,"arms":3,"rate":0.25,"glow":1.9,"size":10,"core":"#ffa575","rim":"#311599"}'
></div>
```
## Source
<Accordion title={`spiral-galaxy.html`}>
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=1920, height=1080" />
<title>Spiral Galaxy</title>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.147.0/build/three.min.js"></script>
<style>
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 1920px;
height: 1080px;
overflow: hidden;
background: #03040a;
}
#sg-root {
position: relative;
width: 1920px;
height: 1080px;
overflow: hidden;
}
/* Full-bleed child carries the scene fill; never the composition root. */
#sg-fill {
position: absolute;
inset: 0;
background: #03040a;
}
#sg-gl {
position: absolute;
inset: 0;
display: block;
width: 1920px;
height: 1080px;
}
/* Ambient halo in the rim colour, screen-blended over the point cloud.
Reads the declared `rim` variable. Variable ids are single lowercase
words on purpose: the runtime injects `--<id>` while the compiler
injects `--<slugify(id)>`, and those two only agree when the id has
no capitals or separators. */
#sg-halo {
position: absolute;
inset: 0;
mix-blend-mode: screen;
opacity: 0.12;
background: radial-gradient(72% 46% at 50% 50%, var(--rim, #311599) 0%, #000000 70%);
}
</style>
</head>
<body>
<div
id="sg-root"
data-composition-id="spiral-galaxy"
data-composition-variables='[
{"id":"stars","type":"number","label":"Star count","default":20000,"min":2000,"max":40000,"step":1000},
{"id":"arms","type":"number","label":"Arm count","default":3,"min":2,"max":8,"step":1},
{"id":"rate","type":"number","label":"Rotation rate","default":0.25,"min":0,"max":1.5,"step":0.05,"unit":"rad/s"},
{"id":"glow","type":"number","label":"Core brightness","default":1.9,"min":0.2,"max":4,"step":0.1},
{"id":"size","type":"number","label":"Star size","default":10,"min":2,"max":40,"step":1,"unit":"px"},
{"id":"core","type":"color","label":"Core colour","default":"#ffa575"},
{"id":"rim","type":"color","label":"Rim colour","default":"#311599"}
]'
data-start="0"
data-duration="10"
data-width="1920"
data-height="1080"
>
<div id="sg-fill"></div>
<canvas id="sg-gl" width="1920" height="1080"></canvas>
<div id="sg-halo"></div>
<!-- Driver clip: gives the block a timed element for the host timeline. -->
<div
id="sg-drv"
class="clip"
data-start="0"
data-duration="10"
data-track-index="0"
style="position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none"
></div>
</div>
<script>
(function () {
var COMP_ID = "spiral-galaxy";
var DURATION = 10;
var W = 1920,
H = 1080;
// ── Measured constants ────────────────────────────────────────────
// Read from the three.js galaxy examples (MIT) during reference
// research; reimplemented here, nothing copied.
// count 20000 · branches 3 · radius = ratio^1.5 * 5 · spin 1
// angle = branchAngle + spin * radius + t * (1 - radiusRatio)
// randomnessPower 3 · inside #ffa575 · outside #311599
var DISC_RADIUS = 5.0; // world units, from `radius = ratio^1.5 * 5`
var RADIUS_POWER = 1.5; // ratio -> radius exponent
// Static Archimedean twist, radians per world unit. This is what draws
// the arm across the WHOLE disc; the time term below then winds it.
// Slightly under the example's 1.0 so the outer arms stay open.
var SPIN = 0.78;
var RANDOMNESS = 0.2; // arm thickness, as a fraction of DISC_RADIUS
var RANDOM_POWER = 3.0; // pow(u, 3): most stars hug the arm, a few stray
var TANGENT_SQUEEZE = 0.62; // arms are thin across, long along
var DISC_FLATNESS = 0.3; // vertical jitter relative to in-plane jitter
var SEED = 20240817; // fixes every per-star attribute
// ── Variables ─────────────────────────────────────────────────────
// Read ONCE at init. Variables never change mid-render.
var vars =
window.__hyperframes && window.__hyperframes.getVariables
? window.__hyperframes.getVariables()
: {};
function clampNum(value, lo, hi, fallback) {
var n = Number(value);
if (!isFinite(n)) n = fallback;
return Math.min(hi, Math.max(lo, n));
}
var STARS = Math.round(clampNum(vars.stars, 2000, 40000, 20000));
var ARMS = Math.round(clampNum(vars.arms, 2, 8, 3));
var RATE = clampNum(vars.rate, 0, 1.5, 0.25);
var GLOW = clampNum(vars.glow, 0.2, 4, 1.9);
var SIZE = clampNum(vars.size, 2, 40, 10);
var CORE_COLOR = typeof vars.core === "string" ? vars.core : "#ffa575";
var RIM_COLOR = typeof vars.rim === "string" ? vars.rim : "#311599";
// ── Seeded PRNG (mulberry32) ──────────────────────────────────────
function mulberry32(seed) {
return function () {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// ── Per-star attributes, seeded once ──────────────────────────────
// Nothing here depends on time. Every frame is computed from these
// plus `uTime` alone, so frame N never reads frame N-1.
var rng = mulberry32(SEED);
var aRatio = new Float32Array(STARS); // 0 = core, 1 = rim
var aBranch = new Float32Array(STARS); // base arm angle
var aJitterR = new Float32Array(STARS); // offset along the arm's radial axis
var aJitterT = new Float32Array(STARS); // offset along the arm's tangent
var aJitterY = new Float32Array(STARS); // disc thickness
var aSpark = new Float32Array(STARS); // per-star size variation
function jitter() {
var magnitude = Math.pow(rng(), RANDOM_POWER) * RANDOMNESS * DISC_RADIUS;
return rng() < 0.5 ? -magnitude : magnitude;
}
for (var i = 0; i < STARS; i++) {
aRatio[i] = rng();
aBranch[i] = ((i % ARMS) / ARMS) * Math.PI * 2;
aJitterR[i] = jitter();
aJitterT[i] = jitter() * TANGENT_SQUEEZE;
aJitterY[i] = jitter() * DISC_FLATNESS;
aSpark[i] = rng();
}
// ── Scene ─────────────────────────────────────────────────────────
var renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("sg-gl"),
antialias: false,
alpha: false,
preserveDrawingBuffer: true, // survives seek-capture screenshots
});
renderer.setPixelRatio(1);
renderer.setSize(W, H, false);
renderer.setClearColor(0x03040a, 1);
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(45, W / H, 0.1, 200);
camera.position.set(0, 2.9, 7.6);
camera.lookAt(0, 0, 0);
var uniforms = {
uTime: { value: 0 },
uRate: { value: RATE },
uSpin: { value: SPIN },
uRadius: { value: DISC_RADIUS },
uPower: { value: RADIUS_POWER },
uSize: { value: SIZE },
uRefDist: { value: camera.position.length() },
uGlow: { value: GLOW },
uCore: { value: new THREE.Color(CORE_COLOR) },
uRim: { value: new THREE.Color(RIM_COLOR) },
};
var VERT = [
"attribute float aRatio;",
"attribute float aBranch;",
"attribute float aJitterR;",
"attribute float aJitterT;",
"attribute float aJitterY;",
"attribute float aSpark;",
"uniform float uTime;",
"uniform float uRate;",
"uniform float uSpin;",
"uniform float uRadius;",
"uniform float uPower;",
"uniform float uSize;",
"uniform float uRefDist;",
"uniform float uGlow;",
"uniform vec3 uCore;",
"uniform vec3 uRim;",
"varying vec3 vColor;",
"varying float vBright;",
"void main() {",
" float ratio = clamp(aRatio, 0.0, 1.0);",
// Differential rotation. omega falls to zero at the rim, so the
// core laps the outer disc and the arms wind up over time.
// Solved directly from uTime — never integrated frame to frame.
" float omega = 1.0 - ratio;",
" float r = pow(ratio, uPower) * uRadius;",
// uSpin * r is the static arm shape (time-independent, so it drops
// out of any inner-vs-outer rotation measurement); uRate * uTime *
// omega is the winding.
" float theta = aBranch + uSpin * r + uRate * uTime * omega;",
" vec2 radial = vec2(cos(theta), sin(theta));",
" vec2 tangent = vec2(-radial.y, radial.x);",
// Jitter rides in the star's own rotating frame, so arm thickness
// holds its shape instead of smearing as the disc turns.
" vec2 xz = radial * (r + aJitterR) + tangent * aJitterT;",
" vec4 mv = modelViewMatrix * vec4(xz.x, aJitterY, xz.y, 1.0);",
" gl_Position = projectionMatrix * mv;",
" gl_PointSize = uSize * (uRefDist / max(-mv.z, 0.001)) * (0.55 + 0.75 * aSpark);",
// Lerp by r/R (i.e. ratio^1.5), matching the example's colour ramp:
// the disc stays warm well past mid-radius and only the rim goes cold.
" vColor = mix(uCore, uRim, pow(ratio, uPower));",
" vBright = uGlow * (0.22 + 0.78 * exp(-ratio * 3.0));",
"}",
].join("\n");
var FRAG = [
"varying vec3 vColor;",
"varying float vBright;",
"void main() {",
" float d = length(gl_PointCoord - vec2(0.5));",
" float a = smoothstep(0.5, 0.0, d);",
" a = a * a;",
" gl_FragColor = vec4(vColor * vBright, a);",
"}",
].join("\n");
var geometry = new THREE.BufferGeometry();
// The vertex shader builds every position from the attributes below;
// `position` exists only because three.js counts vertices from it.
geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(STARS * 3), 3),
);
geometry.setAttribute("aRatio", new THREE.BufferAttribute(aRatio, 1));
geometry.setAttribute("aBranch", new THREE.BufferAttribute(aBranch, 1));
geometry.setAttribute("aJitterR", new THREE.BufferAttribute(aJitterR, 1));
geometry.setAttribute("aJitterT", new THREE.BufferAttribute(aJitterT, 1));
geometry.setAttribute("aJitterY", new THREE.BufferAttribute(aJitterY, 1));
geometry.setAttribute("aSpark", new THREE.BufferAttribute(aSpark, 1));
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: VERT,
fragmentShader: FRAG,
blending: THREE.AdditiveBlending,
transparent: true,
depthTest: false,
depthWrite: false,
});
var points = new THREE.Points(geometry, material);
points.frustumCulled = false; // positions live in the shader, not in `position`
scene.add(points);
function draw(t) {
uniforms.uTime.value = t;
renderer.render(scene, camera);
}
// ── Timeline ──────────────────────────────────────────────────────
// `tl.eventCallback("onUpdate", ...)` does NOT fire on tl.seek(), so
// the repaint hangs off a property setter on the tweened driver —
// that setter runs on every render, seek included.
var driver = { _t: 0 };
Object.defineProperty(driver, "t", {
get: function () {
return this._t;
},
set: function (value) {
this._t = value;
draw(value);
},
});
window.__timelines = window.__timelines || {};
var tl = gsap.timeline({ paused: true });
// ease "none" over the full duration makes driver.t === tl.time().
tl.to(driver, { t: DURATION, duration: DURATION, ease: "none", lazy: false }, 0);
window.__timelines[COMP_ID] = tl;
draw(0); // paint frame 0; GSAP skips the setter when the value is unchanged
})();
</script>
</body>
</html>
```
</Accordion>
{/* hf:generated-footer */}
Tagged `hero` `space` `particles` `webgl` `background`.
## Related topics
- [Browse the complete Catalog](/catalog)
- [Add assets and Catalog items in Studio](/studio/assets-and-blocks)
- [Build a richer composition](/go-further)