diff --git a/examples/index.html b/examples/index.html
index 50547e9..ad9045f 100644
--- a/examples/index.html
+++ b/examples/index.html
@@ -59,6 +59,8 @@
Tech demos
Find the Code
Fog of History
Lights Out
+ Light Shafts
+ Still Water
The Moon
America, folded
diff --git a/examples/public/demos/find-code/index.mjs b/examples/public/demos/find-code/index.mjs
index 288eb21..d880890 100644
--- a/examples/public/demos/find-code/index.mjs
+++ b/examples/public/demos/find-code/index.mjs
@@ -24,12 +24,6 @@ const TARGET = [0, 130, -40];
const CODE = "1847";
// How far scrolling moves the camera towards its target
const DOLLY = 350;
-const ZOOMED_EYE = vec3.scaleAndAdd(
- [],
- EYE,
- vec3.normalize([], vec3.sub([], TARGET, EYE)),
- DOLLY,
-);
const container = new Container();
container.camera.transform = Transform.targetTo(EYE, TARGET);
@@ -74,16 +68,16 @@ const MON_FRONT = MON_BACK + 8;
const BEZEL_Y = DESK_TOP + 30;
const SCREEN_Y = BEZEL_Y + BEZEL + SCREEN_H / 2;
-// The views this page can reach, so a face turned away from all of them skips the DOM
+// The views this page can reach
const POSES = {
home: [EYE, TARGET],
- zoomed: [ZOOMED_EYE, TARGET],
drawer: [
[110, 470, 330],
[130, 30, -230],
],
+ // Far enough back that the full dolly still stops short of the screen
screen: [
- [MON_X, SCREEN_Y + 15, MON_FRONT + 287],
+ [MON_X, SCREEN_Y + 15, MON_FRONT + 440],
[MON_X, SCREEN_Y, MON_FRONT - 33],
],
door: [
@@ -91,7 +85,17 @@ const POSES = {
[190, 110, 0],
],
};
-const POSE_EYES = Object.values(POSES).map(([eye]) => eye);
+// Scrolling moves each eye DOLLY closer. A face turned away from every eye, near and far,
+// skips the DOM
+const POSE_EYES = Object.values(POSES).flatMap(([eye, target]) => [
+ eye,
+ vec3.scaleAndAdd(
+ [],
+ eye,
+ vec3.normalize([], vec3.sub([], target, eye)),
+ DOLLY,
+ ),
+]);
// A box that never moves can drop the faces no pose sees
const solid = (lo, hi, color) => {
for (const pts of Object.values(boxFaces(lo, hi)))
@@ -133,7 +137,7 @@ solid(
[W, DOOR_H + CASE, DOOR_Z1 + CASE],
RIM,
);
-// The reveal runs through the wall's thickness, faces only: a box would show through in Firefox
+// The reveal runs through the wall's thickness
const REVEAL = "#d9cfba";
quad(root, "+z", [W, 0, DOOR_Z0], [W + T, DOOR_H, DOOR_Z0], REVEAL);
quad(root, "-z", [W, 0, DOOR_Z1], [W + T, DOOR_H, DOOR_Z1], REVEAL);
@@ -374,12 +378,13 @@ const addDrawer = (id, label, content, furnish) => {
const drawer = new Group();
drawer.domElement.classList.add("slide", `s-${id}`);
at.addChild(drawer);
- // In two, split where the note stands: Firefox paints a floor crossing its plane over it
- for (const [z0, z1] of [
- [CAB_FRONT - NOTE_Z, CAB_FRONT],
- [back, CAB_FRONT - NOTE_Z],
- ])
- quad(drawer, "+y", [DRAWER_X0, y0, z0], [DRAWER_X1, y0, z1], "#5d3f28");
+ quad(
+ drawer,
+ "+y",
+ [DRAWER_X0, y0, back],
+ [DRAWER_X1, y0, CAB_FRONT],
+ "#5d3f28",
+ );
const SIDE = "#7c5635";
quad(
drawer,
@@ -454,10 +459,13 @@ sticky.setAttribute("aria-label", "A sticky note asks where the code went");
place(root, sticky, Transform.translate([-10, 310, -D + 1]), 0.9);
const camera = (sel, [eye, target]) =>
- `${sel} .c3r-container>.c3r-view{${cameraView(eye, target)};animation:none}`;
+ `${sel} .c3r-container>.c3r-view{${cameraView(eye, target)}}`;
const scene = await container.toHTML();
-// Values from the scene, the rest is in style.css
-const css = `:root{--dolly:${DOLLY * container.unitScale}px;--note-z:${NOTE_Z}px}
+// Values from the scene, the rest is in style.css. The dolly is outside transform, so it moves
+// along the view axis of every pose and the pose transitions leave it alone. Its length is
+// written out because Firefox steps a var() keyframe, in pixels as the scene inside is unit-scaled
+const css = `@keyframes dolly{to{translate:0 0 ${DOLLY * container.unitScale}px}}
+:root{--note-z:${NOTE_Z}px}
${camera("html:has(details[open])", POSES.drawer)}
${camera("html:has(#code:focus)", POSES.screen)}
${camera("html:has(#code:valid)", POSES.door)}
diff --git a/examples/public/demos/find-code/style.css b/examples/public/demos/find-code/style.css
index 9d0ddde..75ce9c0 100644
--- a/examples/public/demos/find-code/style.css
+++ b/examples/public/demos/find-code/style.css
@@ -20,12 +20,6 @@ body {
.c3r-view {
transition: transform 1.2s cubic-bezier(0.4, 0, 0.2, 1);
}
-/* Outside transform, so it dollies along the view axis. The close-up poses turn it off. Lengths out here are in pixels, the scene inside is unit-scaled */
-@keyframes dolly {
- to {
- translate: 0 0 var(--dolly);
- }
-}
/* Without the guard an unsupporting browser fills to the last keyframe and stays zoomed */
@supports (animation-timeline: scroll()) {
.c3r-view {
diff --git a/examples/public/demos/fog-of-history/index.mjs b/examples/public/demos/fog-of-history/index.mjs
index 87854f0..8b0bb65 100644
--- a/examples/public/demos/fog-of-history/index.mjs
+++ b/examples/public/demos/fog-of-history/index.mjs
@@ -17,7 +17,7 @@ import {
} from "../../../demos.mjs";
const HERE = import.meta.dirname;
-const { Container, Group, Transform } = await happyC3R();
+const { Container, Group, Timeline, Transform, Tween } = await happyC3R();
const items = load(path.join(HERE, "hextris.json"));
const tiles = load(path.join(HERE, "hexmeta.json"));
const LIGHT = { ambient: 0.62, intensity: 0.62, direction: [-0.5, -1, -0.45] };
@@ -120,6 +120,10 @@ const unhidden = (tris) => {
const container = new Container();
container.camera.transform = Transform.targetTo(EYE, FOCUS);
+container.camera.tween = new Tween({
+ keyframes: [Transform.translate([0, 0, -DOLLY])],
+ timeline: new Timeline({ scroll: true }),
+});
const pan = new Group();
pan.domElement.classList.add("pan");
@@ -172,7 +176,6 @@ const pans = tiles.map((tile) => {
return `html:has(#t${tile.tag}:target) .pan{transform:translate3d(${(-x).toFixed(1)}px,0,${(-z).toFixed(1)}px)}`;
});
const scene = await container.toHTML();
-const css = `:root{--dolly:${DOLLY * container.unitScale}px}
-@media (orientation:portrait){.c3r-container.c3r-container>.c3r-view{${cameraView(PORTRAIT_EYE, FOCUS)}}}
+const css = `@media (orientation:portrait){.c3r-container.c3r-container>.c3r-view{${cameraView(PORTRAIT_EYE, FOCUS)}}}
${pans.join("\n")}`;
writePage(HERE, { css, targets, scene });
diff --git a/examples/public/demos/fog-of-history/style.css b/examples/public/demos/fog-of-history/style.css
index 4d9efbd..d5be61b 100644
--- a/examples/public/demos/fog-of-history/style.css
+++ b/examples/public/demos/fog-of-history/style.css
@@ -6,19 +6,6 @@ body {
margin: 0;
height: 300vh;
}
-/* Outside transform, so it dollies along the view axis. Lengths out here are in pixels, the scene inside is unit-scaled */
-@keyframes dolly {
- to {
- translate: 0 0 var(--dolly);
- }
-}
-/* Without the guard an unsupporting browser fills to the last keyframe and stays zoomed */
-@supports (animation-timeline: scroll()) {
- .c3r-view {
- animation: dolly linear both;
- animation-timeline: scroll(root);
- }
-}
.c3r-container.c3r-container {
position: fixed;
inset: 0;
diff --git a/examples/public/demos/globe-gores/index.mjs b/examples/public/demos/globe-gores/index.mjs
index c73ba90..ab5bd8e 100644
--- a/examples/public/demos/globe-gores/index.mjs
+++ b/examples/public/demos/globe-gores/index.mjs
@@ -2,8 +2,15 @@ import { join } from "node:path";
import { happyC3R, load, writePage } from "../../../demos.mjs";
const HERE = import.meta.dirname;
-const { Container, Group, Material, Transform, Tween, ElementObject } =
- await happyC3R();
+const {
+ Container,
+ Group,
+ Material,
+ Timeline,
+ Transform,
+ Tween,
+ ElementObject,
+} = await happyC3R();
const { rotateX, rotateY, rotateZ, translate } = Transform;
const { gores, tex, scale, full, crop } = load(join(HERE, "gores.json"));
const [TW, TH] = tex;
@@ -93,6 +100,7 @@ const HOLD = 7;
const FOLD = 43;
const TURN = 42;
const REST = 8;
+const page = new Timeline({ scroll: true });
const phase = (rest, moved, before, during, after) =>
new Tween({
from: rest,
@@ -102,6 +110,7 @@ const phase = (rest, moved, before, during, after) =>
{ steps: moved, duration: after },
],
easing: "ease-in-out",
+ timeline: page,
});
const fold = (flat, folded) => phase(flat, folded, HOLD, FOLD, TURN + REST);
diff --git a/examples/public/demos/globe-gores/style.css b/examples/public/demos/globe-gores/style.css
index ddb7379..3b1196d 100644
--- a/examples/public/demos/globe-gores/style.css
+++ b/examples/public/demos/globe-gores/style.css
@@ -22,10 +22,6 @@ html .c3r-container {
html .label {
backface-visibility: hidden;
}
-.c3r-group[style*="animation"],
-.c3r-view {
- animation-timeline: scroll(root) !important;
-}
.label {
display: block;
background: none;
diff --git a/examples/public/demos/light-shafts/index.eta b/examples/public/demos/light-shafts/index.eta
new file mode 100644
index 0000000..38402d4
--- /dev/null
+++ b/examples/public/demos/light-shafts/index.eta
@@ -0,0 +1,4 @@
+<% layout("@layout", { title: "Light Shafts" }) %>
+<%~ it.scene %>
+
+
diff --git a/examples/public/demos/light-shafts/index.mjs b/examples/public/demos/light-shafts/index.mjs
new file mode 100644
index 0000000..c6ef36b
--- /dev/null
+++ b/examples/public/demos/light-shafts/index.mjs
@@ -0,0 +1,374 @@
+import {
+ boxFaces,
+ facesAny,
+ hex,
+ happyC3R,
+ normalOf,
+ rect,
+ rgb,
+ writePage,
+} from "../../../demos.mjs";
+
+const HERE = import.meta.dirname;
+const { Container, Material, Timeline, Transform, Tween } = await happyC3R();
+
+// The nave spans x from -HALF_WIDTH to HALF_WIDTH, y from 0 to HEIGHT, z from BACK to FRONT
+const HALF_WIDTH = 300;
+const HEIGHT = 560;
+const FRONT = 420;
+const BAY = 300;
+const BAYS = 8;
+const BACK = -BAY * BAYS;
+const EYE = [30, 180, 300];
+// How far scrolling walks the camera down the nave
+const DOLLY = 1300;
+const END_EYE = [EYE[0], EYE[1], EYE[2] - DOLLY];
+
+const PILLAR_X = 185;
+const PILLAR_HALF = 32;
+const RIB = 40;
+// A pointed window on the left of every bay but the last, z measured from the bay's pillars
+const WINDOW = { z: -150, half: 80, sill: 260, spring: 400 };
+// Sunlight moves this far across the nave for each unit it falls. It never runs along the nave,
+// so every slice of a beam is a plane facing the camera
+const RUN = 0.93;
+// Across the window, where the beam is sliced and where the dust hangs
+const BEAM_SLICES = [-72, -48, -20, 20, 48, 72];
+const DUST_PLANES = [-34, 34];
+const MOTES_PER_PLANE = 46;
+
+const STONE = "#433b33";
+const FLOOR = "#312b25";
+const FOG = "#1c2130";
+const FOG_LENGTH = 1100;
+const AMBIENT = 0.7;
+const SUN_FILL = 0.35;
+// The glass shines through the fog, so it takes on only this much of it
+const GLASS_FOG = 0.3;
+// Each light's alpha before the fog dims it
+const ALPHA = {
+ beam: 0.11,
+ pool: 0.34,
+ bounce: 0.2,
+ haloWindow: 0.3,
+ haloPool: 0.2,
+};
+// A plane fades out over this distance before the camera reaches it, else it would pop
+const FADE = [260, 70];
+// Soft planes need few pixels, opaque faces keep the library's size so their edges stay crisp
+const SOFT_PX = () => 256;
+
+const BAY_ZS = Array.from({ length: BAYS }, (_, k) => -k * BAY);
+const SHEET_ZS = BAY_ZS.map((z) => z + WINDOW.z);
+const WINDOW_ZS = SHEET_ZS.slice(0, -1);
+
+const fogAmount = (z) => 1 - Math.exp(-Math.max(0, EYE[2] - z) / FOG_LENGTH);
+const mix = (a, b, t) => hex(rgb(a).map((v, i) => v + (rgb(b)[i] - v) * t));
+const dimmed = (alpha, z) => alpha * (1 - 0.75 * fogAmount(z));
+const sunlight = (alpha) => `rgb(255 214 166/${alpha.toFixed(3)})`;
+const random = (lo, hi) => lo + Math.random() * (hi - lo);
+const percent = (t) => `${(t * 100).toFixed(1)}%`;
+
+// A pointed arch, s across it and y up, made of two arcs of radius twice the half width. Each
+// point carries its uv in the arch's bounding box
+const arch = (half, bottom, spring) => {
+ const height = spring + Math.sqrt(3) * half - bottom;
+ const right = Array.from({ length: 7 }, (_, i) => {
+ const angle = (i / 6) * (Math.PI / 3);
+ return [
+ -half + 2 * half * Math.cos(angle),
+ spring + 2 * half * Math.sin(angle),
+ ];
+ });
+ const left = right
+ .slice(0, -1)
+ .map(([s, y]) => [-s, y])
+ .reverse();
+ return [[-half, bottom], [half, bottom], ...right, ...left].map(([s, y]) => ({
+ s,
+ y,
+ uv: [(s + half) / (2 * half), (y - bottom) / height],
+ }));
+};
+
+const container = new Container();
+document.body.append(container.domElement);
+container.camera.fov = 60;
+container.camera.transform = [
+ Transform.translate(EYE),
+ Transform.rotateX(-0.06),
+];
+container.camera.tween = new Tween({
+ keyframes: [Transform.translate([0, 0, -DOLLY])],
+ timeline: new Timeline({ scroll: true }),
+});
+container.fog = { color: rgb(FOG).map((v) => v / 255), length: FOG_LENGTH };
+// Weak since the sun only gets in through the windows, and along the beams so the window wall
+// falls dark
+container.lights = {
+ ambient: { intensity: AMBIENT },
+ directional: { direction: [RUN, -1, 0], intensity: SUN_FILL },
+};
+const surface = new Material();
+surface.fog = true;
+surface.shading = "flat";
+
+const RECT_UV = [
+ [0, 0],
+ [1, 0],
+ [1, 1],
+ [0, 1],
+];
+const addFace = (
+ points,
+ uvs,
+ className,
+ { style = {}, html = "", domSize } = {},
+) => {
+ const content = document.createElement("div");
+ content.className = className;
+ for (const [name, value] of Object.entries(style))
+ content.style.setProperty(name, value);
+ content.innerHTML = html;
+ const vertices = points.map((position, i) => ({ position, uv: uvs[i] }));
+ return container.root.addPolygon(vertices, {
+ contentElement: content,
+ getDomSize: domSize,
+ });
+};
+// Opaque faces, which the library lights and fades into the fog as the camera walks
+const addSurface = (points, color, layers = "") => {
+ const style = { "--bg": `${layers}linear-gradient(${color} 0 0)` };
+ addFace(points, RECT_UV, "solid", { style }).material = surface;
+};
+// A plane facing the camera, faded out by scrolling before the camera passes it
+const addVeil = (
+ points,
+ uvs,
+ className,
+ { style, html, domSize = SOFT_PX },
+) => {
+ const scrolled = (distance) =>
+ percent((EYE[2] - points[0][2] - distance) / DOLLY);
+ addFace(points, uvs, `${className} veil`, {
+ style: {
+ ...style,
+ "--fade-start": scrolled(FADE[0]),
+ "--fade-end": scrolled(FADE[1]),
+ },
+ html,
+ domSize,
+ });
+};
+const sheet = (z) => rect("+z", [-HALF_WIDTH, 0, z], [HALF_WIDTH, HEIGHT, z]);
+
+// The hall, one segment per bay so the fog's few gradient stops stay close
+const JOINTS =
+ "repeating-linear-gradient(to right,#0000 0 23px,#0003 23px 25px),";
+for (const [k, z0] of [...BAY_ZS, BACK].entries()) {
+ const z1 = k ? z0 + BAY : FRONT;
+ addSurface(
+ rect("+y", [-HALF_WIDTH, 0, z0], [HALF_WIDTH, 0, z1]),
+ FLOOR,
+ JOINTS,
+ );
+ addSurface(
+ rect("-y", [-HALF_WIDTH, HEIGHT, z0], [HALF_WIDTH, HEIGHT, z1]),
+ STONE,
+ );
+ addSurface(
+ rect("+x", [-HALF_WIDTH, 0, z0], [-HALF_WIDTH, HEIGHT, z1]),
+ STONE,
+ );
+ addSurface(rect("-x", [HALF_WIDTH, 0, z0], [HALF_WIDTH, HEIGHT, z1]), STONE);
+}
+addSurface(
+ rect("+z", [-HALF_WIDTH, 0, BACK], [HALF_WIDTH, HEIGHT, BACK]),
+ STONE,
+);
+
+// Pillars, only the faces the camera sees on its walk
+const pillarFaces = BAY_ZS.flatMap((z) =>
+ [-PILLAR_X, PILLAR_X].flatMap((x) =>
+ Object.entries(
+ boxFaces(
+ [x - PILLAR_HALF, 0, z - PILLAR_HALF],
+ [x + PILLAR_HALF, HEIGHT - RIB, z + PILLAR_HALF],
+ ),
+ ),
+ ),
+);
+for (const [side, points] of pillarFaces) {
+ if (side.endsWith("y") || !facesAny(points, [EYE, END_EYE])) continue;
+ // Light from the pools bounces up the sides facing the aisle
+ const bounce = `linear-gradient(to top,${sunlight(ALPHA.bounce)},#0000 40%),`;
+ addSurface(points, STONE, side === "+z" ? "" : bounce);
+}
+
+// A rib across the ceiling over each pair of pillars
+for (const z of BAY_ZS) {
+ const lo = [-HALF_WIDTH, HEIGHT - RIB, z - 20];
+ const hi = [HALF_WIDTH, HEIGHT, z + 20];
+ addSurface(rect("-y", lo, hi), STONE);
+ addSurface(rect("+z", lo, hi), STONE);
+}
+
+// The door at the end, glowing through the last of the fog
+const door = arch(110, 0, 300);
+addFace(
+ door.map(({ s, y }) => [s, y, BACK + 1]),
+ door.map(({ uv }) => uv),
+ "light",
+ { style: { "--bg": "linear-gradient(to top,#ffd9a8,#fff4e0 60%)" } },
+);
+const DOOR_GLOWS = [
+ [80, "radial-gradient(ellipse 36% 51% at 50% 72%,rgb(255 226 180/.4),#0000)"],
+ [
+ 200,
+ "radial-gradient(ellipse 63% 74% at 50% 67%,rgb(255 220 170/.18),#0000)",
+ ],
+];
+for (const [distance, glow] of DOOR_GLOWS)
+ addVeil(sheet(BACK + distance), RECT_UV, "glow", { style: { "--bg": glow } });
+
+// Fog sheets, one in the middle of each bay. The puffs sit on a strip twice the sheet's width,
+// each repeated every half so the drift loops. Plain gradients, an SVG noise image filters
+// differently in each browser
+const puff = () => {
+ const [x, y] = [random(0, 50), random(45, 100)];
+ const size = `${random(8, 18).toFixed(1)}% ${random(14, 30).toFixed(1)}%`;
+ const color = `rgb(150 160 186/${random(0.1, 0.22).toFixed(2)})`;
+ return [x - 50, x, x + 50, x + 100].map(
+ (at) =>
+ `radial-gradient(ellipse ${size} at ${at.toFixed(1)}% ${y.toFixed(1)}%,${color},#0000)`,
+ );
+};
+const HAZE = "linear-gradient(rgb(150 160 186/.07),rgb(150 160 186/.07))";
+// Lit by the window and by the pool below it
+const windowHalo = (z) =>
+ `radial-gradient(ellipse 27% 24% at 5% 45%,${sunlight(dimmed(ALPHA.haloWindow, z))},#0000),` +
+ `radial-gradient(ellipse 31% 18% at 54.5% 100%,${sunlight(dimmed(ALPHA.haloPool, z))},#0000)`;
+for (const z of SHEET_ZS) {
+ addVeil(sheet(z), RECT_UV, "fog", {
+ style: {
+ "--puffs": [...Array.from({ length: 9 }, puff).flat(), HAZE].join(","),
+ "--halo": WINDOW_ZS.includes(z) ? windowHalo(z) : "none",
+ "--alpha": (1 - 0.4 * fogAmount(z)).toFixed(3),
+ "--period": `${random(70, 110).toFixed(1)}s`,
+ "--delay": `${random(-100, 0).toFixed(1)}s`,
+ },
+ html: '',
+ });
+}
+
+// The windows, with a mullion and a transom
+const windowArch = arch(WINDOW.half, WINDOW.sill, WINDOW.spring);
+const MUNTINS =
+ "linear-gradient(to right,#0000 48%,#2a2420 48% 52%,#0000 52%)," +
+ "linear-gradient(to top,#0000 60%,#2a2420 60% 63%,#0000 63%),";
+for (const z of WINDOW_ZS) {
+ const [warm, pale] = ["#ffd7a0", "#fff5e2"].map((c) =>
+ mix(c, FOG, GLASS_FOG * fogAmount(z)),
+ );
+ addFace(
+ windowArch.map(({ s, y }) => [-HALF_WIDTH + 1, y, z - s]),
+ windowArch.map(({ uv }) => uv),
+ "light",
+ { style: { "--bg": `${MUNTINS}linear-gradient(to top,${warm},${pale})` } },
+ );
+}
+
+const apex = WINDOW.spring + Math.sqrt(3) * WINDOW.half;
+// Height of the window's top at s across it
+const windowTop = (s) =>
+ WINDOW.spring +
+ Math.sqrt((2 * WINDOW.half) ** 2 - (Math.abs(s) + WINDOW.half) ** 2);
+const BEAM_X = -HALF_WIDTH;
+// Where the ray leaving the window at height y lands on the floor
+const landing = (y) => BEAM_X + y * RUN;
+// Where the ray from the window's top lands, the far edge of the dust planes
+const BEAM_RIGHT = landing(apex);
+
+// Pools of light, the window's outline cast along the sunlight onto the floor
+for (const z of WINDOW_ZS) {
+ const points = windowArch.map(({ s, y }) => [landing(y), 1, z - s]);
+ // The window's height runs along the sunlight on the floor
+ const uvs = windowArch.map(({ uv: [u, v] }) => [v, u]);
+ const facesUp = normalOf(points)[1] > 0;
+ addFace(
+ facesUp ? points : points.toReversed(),
+ facesUp ? uvs : uvs.toReversed(),
+ "pool",
+ { style: { "--sun": sunlight(dimmed(ALPHA.pool, z)) } },
+ );
+}
+
+// Beams. u is the height on the window a ray left from, v the height above the floor, so every
+// ray fades towards the floor
+const beamUv = ([x, y]) => [
+ (apex - y - (x - BEAM_X) / RUN) / (apex - WINDOW.sill),
+ y / apex,
+];
+const beams = WINDOW_ZS.flatMap((z) =>
+ BEAM_SLICES.map((s, i) => ({
+ z: z + s,
+ top: windowTop(s),
+ period: 5 + i * 1.3,
+ })),
+);
+for (const { z, top, period } of beams) {
+ const beam = [
+ [BEAM_X, WINDOW.sill, z],
+ [landing(WINDOW.sill), 0, z],
+ [landing(top), 0, z],
+ [BEAM_X, top, z],
+ ];
+ addVeil(beam, beam.map(beamUv), "shaft", {
+ style: {
+ "--alpha": dimmed(ALPHA.beam, z).toFixed(3),
+ "--period": `${period.toFixed(1)}s`,
+ "--delay": `${random(-14, 0).toFixed(1)}s`,
+ },
+ html: '',
+ });
+}
+
+// Dust, on upright rectangles: the beams' own mapping is stretched along them and would smear
+// each mote. A mote is a point of the window carried some way down its ray
+const randomMote = (top, z) => {
+ const height = random(WINDOW.sill + 10, top - 10);
+ const drop = random(0.03, 0.92) * height;
+ return {
+ x: BEAM_X + drop * RUN,
+ y: height - drop,
+ size: `${random(3, 8).toFixed(1)}px`,
+ alpha: (random(0.4, 1) * dimmed(1, z)).toFixed(2),
+ };
+};
+const dustPlanes = WINDOW_ZS.flatMap((z) =>
+ DUST_PLANES.map((s) => ({ z: z + s, top: windowTop(s) })),
+);
+for (const { z, top } of dustPlanes) {
+ const motes = Array.from({ length: MOTES_PER_PLANE }, () =>
+ randomMote(top, z),
+ );
+ const layers = motes.map(({ x, y, size, alpha }) => {
+ const position = `${percent((x - BEAM_X) / (BEAM_RIGHT - BEAM_X))} ${percent(1 - y / apex)}`;
+ return `radial-gradient(rgb(255 238 205/${alpha}),#0000 70%) ${position}/${size} ${size} no-repeat`;
+ });
+ addVeil(rect("+z", [BEAM_X, 0, z], [BEAM_RIGHT, apex, z]), RECT_UV, "dust", {
+ style: {
+ "--motes": layers.join(","),
+ "--delay": `${random(-12, 0).toFixed(1)}s`,
+ },
+ // Motes are sized in pixels, so the planes keep one pixel density whatever their width
+ domSize: (size) => size * 1.4,
+ html: '',
+ });
+}
+
+const scene = await container.toHTML();
+writePage(HERE, {
+ css: `:root{background:${FOG}}`,
+ scene,
+});
diff --git a/examples/public/demos/light-shafts/style.css b/examples/public/demos/light-shafts/style.css
new file mode 100644
index 0000000..93e7bbc
--- /dev/null
+++ b/examples/public/demos/light-shafts/style.css
@@ -0,0 +1,165 @@
+html {
+ scrollbar-width: none;
+}
+/* Scrolling the page only walks the camera, the scene stays put */
+body {
+ margin: 0;
+ height: 400vh;
+}
+.c3r-container.c3r-container {
+ position: fixed;
+ inset: 0;
+}
+/* Two classes, the library's own rules come later in the page */
+.c3r-polygon-content.c3r-polygon-content {
+ background-color: #0000;
+ background-image: var(--bg, none);
+ background-blend-mode: normal;
+}
+.c3r-polygon-content > * {
+ position: absolute;
+ inset: 0;
+}
+
+/* The window's transom shades a band across the beam */
+.rays {
+ background: linear-gradient(
+ to right,
+ #0000,
+ rgb(255 214 166 / var(--alpha)) 18% 34%,
+ rgb(255 214 166 / calc(var(--alpha) * 0.35)) 38% 44%,
+ rgb(255 214 166 / var(--alpha)) 48% 80%,
+ #0000
+ );
+ mask-image: linear-gradient(to top, #0003, #000 35%);
+ /* The library maps the uv onto the content's own background, the rays follow it */
+ background-size: inherit;
+ background-position: inherit;
+ mask-size: inherit;
+ mask-position: inherit;
+ animation: shimmer var(--period) ease-in-out var(--delay) infinite alternate;
+}
+@keyframes shimmer {
+ to {
+ opacity: 0.5;
+ }
+}
+
+/* The window's transom and mullion cast as darker bands */
+.c3r-polygon-content.pool {
+ background-image: linear-gradient(
+ to right,
+ #0000,
+ var(--sun) 12% 55%,
+ #0000 58% 64%,
+ var(--sun) 67% 94%,
+ #0000
+ );
+ mask-image: linear-gradient(
+ to top,
+ #0000,
+ #000 15% 46%,
+ #0004 50%,
+ #000 54% 85%,
+ #0000
+ );
+}
+
+/* Twice as wide as the plane, the same puffs in each half, so the drift loops without a seam */
+.puffs {
+ right: -100%;
+ background: var(--puffs);
+ /* Clear at the floor, else each sheet draws a line where it meets it */
+ mask-image: linear-gradient(to top, #0000, #000 16%, #0007 45%, #0000 90%);
+ opacity: var(--alpha);
+ animation: drift var(--period) linear var(--delay) infinite;
+}
+.fog > .halo {
+ background: var(--halo);
+}
+@keyframes drift {
+ to {
+ translate: -50%;
+ }
+}
+
+.motes {
+ background: var(--motes);
+ animation:
+ float 11s ease-in-out var(--delay) infinite alternate,
+ twinkle 3.7s ease-in-out var(--delay) infinite alternate;
+}
+@keyframes float {
+ to {
+ translate: 2% -6%;
+ }
+}
+@keyframes twinkle {
+ to {
+ opacity: 0.3;
+ }
+}
+
+@keyframes fade {
+ to {
+ opacity: 0;
+ visibility: hidden;
+ }
+}
+/* Without the guard an unsupporting browser fills to the last keyframe and hides them */
+@supports (animation-timeline: scroll()) {
+ .c3r-polygon-content.veil {
+ animation: fade linear both;
+ animation-timeline: scroll(root);
+ animation-range: var(--fade-start) var(--fade-end);
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .c3r-polygon-content > * {
+ animation: none !important;
+ }
+}
+
+/* Outside the 3D scene, where blending is safe: the eye's own glare and vignette */
+.lens {
+ position: fixed;
+ inset: 0;
+ pointer-events: none;
+ background: radial-gradient(ellipse at 50% 45%, #0000 50%, #0009);
+}
+.lens::before {
+ content: "";
+ position: absolute;
+ inset: 0;
+ background: radial-gradient(
+ ellipse 45% 55% at 12% 30%,
+ rgb(255 200 140 / 0.12),
+ #0000
+ );
+ mix-blend-mode: plus-lighter;
+}
+
+header {
+ position: fixed;
+ left: 16px;
+ top: 10px;
+ color: #e3d6bf;
+ font:
+ 13px/1.35 Georgia,
+ serif;
+ text-shadow: 0 0 4px #000;
+}
+h1 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: normal;
+ color: #fff;
+}
+p {
+ margin: 0;
+}
+@media (max-aspect-ratio: 1/1) {
+ .c3r-perspective {
+ --c3r-camera-fov: 100deg !important;
+ }
+}
diff --git a/examples/public/demos/lights-out/index.mjs b/examples/public/demos/lights-out/index.mjs
index 9d6b652..1b5af75 100644
--- a/examples/public/demos/lights-out/index.mjs
+++ b/examples/public/demos/lights-out/index.mjs
@@ -98,6 +98,10 @@ container.lights = {
};
container.camera.fov = 60;
container.camera.transform = Transform.translate(EYE);
+container.camera.tween = new Tween({
+ keyframes: [Transform.translate([0, 0, -DOLLY])],
+ timeline: new Timeline({ scroll: true }),
+});
const room = new Group();
container.root.addChild(room);
@@ -339,13 +343,9 @@ const addPillar = () => {
["+z", "+x", "-x"].map((side) => rect(side, lo, hi));
const collar = (y0, y1) =>
visibleSides([collarX[0], y0, collarZ[0]], [collarX[1], y1, collarZ[1]]);
- // Front, left and right strips around the shaft. A whole cap would cut through the shaft, and
- // Firefox sorts it on top
- const ring = (y, side) => [
- rect(side, [collarX[0], y, shaftHi[2]], [collarX[1], y, collarZ[1]]),
- rect(side, [collarX[0], y, shaftLo[2]], [shaftLo[0], y, shaftHi[2]]),
- rect(side, [shaftHi[0], y, shaftLo[2]], [collarX[1], y, shaftHi[2]]),
- ];
+ // A whole cap, the shaft hides the part inside it
+ const cap = (y, side) =>
+ rect(side, [collarX[0], y, collarZ[0]], [collarX[1], y, collarZ[1]]);
// Flat, smooth on these small faces cost about a third of the frame rate
const collars = new Group();
pillar.addChild(collars);
@@ -353,9 +353,9 @@ const addPillar = () => {
addTiled(pillar, visibleSides(shaftLo, shaftHi));
addTiled(collars, [
...collar(0, COLLAR_H),
- ...ring(COLLAR_H, "+y"),
+ cap(COLLAR_H, "+y"),
...collar(HEIGHT - COLLAR_H, HEIGHT),
- ...ring(HEIGHT - COLLAR_H, "-y"),
+ cap(HEIGHT - COLLAR_H, "-y"),
]);
};
addPillar();
@@ -370,7 +370,4 @@ sprite.addPolygon(withUv(rect("+z", [-30, -30, 0], [30, 30, 0])));
sprite.material = material("assets/lamp.png");
const scene = await container.toHTML({ shadows: true });
-writePage(HERE, {
- css: `:root{--dolly:${DOLLY * container.unitScale}px}`,
- scene,
-});
+writePage(HERE, { scene });
diff --git a/examples/public/demos/lights-out/style.css b/examples/public/demos/lights-out/style.css
index 97b3a2c..6058926 100644
--- a/examples/public/demos/lights-out/style.css
+++ b/examples/public/demos/lights-out/style.css
@@ -11,20 +11,6 @@ body {
position: fixed;
inset: 0;
}
-/* Outside transform, so it dollies along the view axis. Lengths out here are in pixels, the scene
- inside is unit-scaled */
-@keyframes dolly {
- to {
- translate: 0 0 var(--dolly);
- }
-}
-/* Without the guard an unsupporting browser fills to the last keyframe and stays zoomed */
-@supports (animation-timeline: scroll()) {
- .c3r-view {
- animation: dolly linear both;
- animation-timeline: scroll(root);
- }
-}
/* A page parsed in chunks starts its animations up to half a second apart, which would throw the
shadows off the pillar for good. This holds them all until the last element arrives */
body:not(:has(> header)) * {
diff --git a/examples/public/demos/still-water/CREDITS.md b/examples/public/demos/still-water/CREDITS.md
new file mode 100644
index 0000000..4bf6dfc
--- /dev/null
+++ b/examples/public/demos/still-water/CREDITS.md
@@ -0,0 +1,10 @@
+# Still Water credits
+
+| Asset | Source | License |
+| --- | --- | --- |
+| `assets/sky.jpg` | [Bell Park Dawn](https://polyhaven.com/a/bell_park_dawn), Greg Zaal, Poly Haven, [download](https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/bell_park_dawn.jpg), 170 degrees of it above the horizon, laid out for a cylinder | [CC0](https://polyhaven.com/license) |
+| `assets/sky-water.jpg` | The same sky as a lake reflects it: smeared downwards, darkened | [CC0](https://polyhaven.com/license) |
+| `assets/planks.jpg` | [Brown Planks 03](https://polyhaven.com/a/brown_planks_03), Rob Tuytel, Poly Haven, [download](https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/brown_planks_03/brown_planks_03_diff_1k.jpg) | [CC0](https://polyhaven.com/license) |
+| `assets/pile.jpg` | [Bark Brown 01](https://polyhaven.com/a/bark_brown_01), Rob Tuytel, Poly Haven, [download](https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/bark_brown_01/bark_brown_01_diff_1k.jpg), scaled to 512 px, greyed and darkened | [CC0](https://polyhaven.com/license) |
+| `assets/pile-end.jpg` | `textures/log_end.png` of these examples, greyed | Part of this repository |
+| `assets/waves.png` | Generated | Part of this repository |
diff --git a/examples/public/demos/still-water/assets/pile-end.jpg b/examples/public/demos/still-water/assets/pile-end.jpg
new file mode 100644
index 0000000..0910c00
Binary files /dev/null and b/examples/public/demos/still-water/assets/pile-end.jpg differ
diff --git a/examples/public/demos/still-water/assets/pile.jpg b/examples/public/demos/still-water/assets/pile.jpg
new file mode 100644
index 0000000..22d020f
Binary files /dev/null and b/examples/public/demos/still-water/assets/pile.jpg differ
diff --git a/examples/public/demos/still-water/assets/planks.jpg b/examples/public/demos/still-water/assets/planks.jpg
new file mode 100644
index 0000000..002f1e9
Binary files /dev/null and b/examples/public/demos/still-water/assets/planks.jpg differ
diff --git a/examples/public/demos/still-water/assets/sky-water.jpg b/examples/public/demos/still-water/assets/sky-water.jpg
new file mode 100644
index 0000000..6c1736c
Binary files /dev/null and b/examples/public/demos/still-water/assets/sky-water.jpg differ
diff --git a/examples/public/demos/still-water/assets/sky.jpg b/examples/public/demos/still-water/assets/sky.jpg
new file mode 100644
index 0000000..333dfb3
Binary files /dev/null and b/examples/public/demos/still-water/assets/sky.jpg differ
diff --git a/examples/public/demos/still-water/assets/waves.png b/examples/public/demos/still-water/assets/waves.png
new file mode 100644
index 0000000..b63d9b5
Binary files /dev/null and b/examples/public/demos/still-water/assets/waves.png differ
diff --git a/examples/public/demos/still-water/index.eta b/examples/public/demos/still-water/index.eta
new file mode 100644
index 0000000..35883f1
--- /dev/null
+++ b/examples/public/demos/still-water/index.eta
@@ -0,0 +1,3 @@
+<% layout("@layout", { title: "Still Water" }) %>
+<%~ it.scene %>
+
diff --git a/examples/public/demos/still-water/index.mjs b/examples/public/demos/still-water/index.mjs
new file mode 100644
index 0000000..2d296d9
--- /dev/null
+++ b/examples/public/demos/still-water/index.mjs
@@ -0,0 +1,244 @@
+import { happyC3R, rect, writePage } from "../../../demos.mjs";
+
+const HERE = import.meta.dirname;
+const { Container, Group, Material, Timeline, Transform, Tween } =
+ await happyC3R(HERE);
+
+const radians = (degrees) => (degrees * Math.PI) / 180;
+
+// The sky is a photograph on the inside of a cylinder around the lake. assets/sky.jpg covers
+// SKY_SPAN degrees of it, from the horizon up to SKY_TOP degrees
+const SKY_RADIUS = 5000;
+const SKY_SPAN = 170;
+const SKY_TOP = 46;
+const SKY_PANELS = 16;
+const SKY_ZENITH = "#c4cfe9";
+
+// The jetty runs away from the shore along -z, its deck DECK_TOP above the water
+const JETTY = { halfWidth: 80, near: 420, far: -900 };
+const DECK_TOP = 46;
+// The deck is laid in lengths, each an element of its own to keep its boards sharp
+const DECK_LENGTHS = 3;
+// One repeat of the planks is nine boards wide
+const PLANKS_TILE = 160;
+const PILE_SIDES = 8;
+const PILE = { radius: 8, height: 72, spacing: 190 };
+// How far from its centre the end grain reaches in assets/pile-end.jpg
+const PILE_END_RADIUS = 0.36;
+const PILE_END_INSET = 0.5;
+
+const EYE = [24, DECK_TOP + 150, 330];
+// How far scrolling walks the camera along the jetty
+const WALK = 700;
+// The camera drifts to each side and turns a little, once over in `period` seconds
+const SWAY = { drift: 14, turn: 0.01, period: 8 };
+
+// The water near the jetty, in two strips, far to near, each an element WATER_PIXELS wide.
+// The waves thin out over the far one, further out they would squeeze into stripes
+const WATER_STRIPS = [
+ { near: -300, far: -1000, halfWidth: 2500, fades: true },
+ { near: 250, far: -300, halfWidth: 1500 },
+];
+const WATER_PIXELS = 1500;
+// World size of one repeat of the waves, and the seconds its two layers take to drift across
+const WAVE_TILE = [1100, 520];
+const WAVE_PERIODS = [44, 29];
+// The second layer starts this many percent down the texture, so the two never line up
+const WAVE_LAYER_OFFSET = 37;
+
+const container = new Container();
+document.body.append(container.domElement);
+container.camera.fov = 60;
+container.camera.transform = [
+ Transform.translate(EYE),
+ Transform.rotateX(-0.1),
+];
+container.camera.tween = [
+ new Tween({
+ keyframes: [Transform.translate([0, 0, -WALK])],
+ timeline: new Timeline({ scroll: true }),
+ }),
+ // A slow sway, so the reflections shift even when the page is not scrolled
+ new Tween({
+ from: [
+ Transform.translate([-SWAY.drift, 0, 0]),
+ Transform.rotateY(-SWAY.turn),
+ ],
+ keyframes: [
+ [Transform.translate([SWAY.drift, 0, 0]), Transform.rotateY(SWAY.turn)],
+ ],
+ duration: SWAY.period,
+ easing: "ease-in-out",
+ loop: true,
+ alternate: true,
+ }),
+];
+// The sun is about to rise behind the hills ahead on the right, low enough for long shadows
+container.lights = {
+ ambient: { intensity: 0.5 },
+ directional: { direction: [-0.7, -0.4, 0.6], intensity: 0.75 },
+};
+
+const textured = (image, shading) => {
+ const material = new Material();
+ material.background = image;
+ if (shading) material.shading = shading;
+ return material;
+};
+const skyMaterial = textured("assets/sky.jpg");
+// The same sky as the lake gives it back, smeared downwards and darker towards the nearer water
+const waterSkyMaterial = textured("assets/sky-water.jpg");
+const deckMaterial = textured("assets/planks.jpg", "flat");
+deckMaterial.shadows = { opacity: 0.6, blur: 4 };
+const pileMaterial = textured("assets/pile.jpg", "smooth");
+const pileEndMaterial = textured("assets/pile-end.jpg", "flat");
+
+// The sky's panels meet edge to edge and a hairline of the page shows between them, so a
+// second ring a little further out, turned by half a panel, backs each joint
+const SKY_RINGS = [
+ { radius: SKY_RADIUS + 60, shift: 0.5, panels: SKY_PANELS - 1 },
+ { radius: SKY_RADIUS, shift: 0, panels: SKY_PANELS },
+];
+const addSky = (group, material) => {
+ for (const { radius, shift, panels } of SKY_RINGS)
+ for (let panel = 0; panel < panels; panel++) {
+ const [left, right] = [panel, panel + 1].map((edge) => {
+ const u = (edge + shift) / SKY_PANELS;
+ const angle = radians((u - 0.5) * SKY_SPAN);
+ return { u, x: radius * Math.sin(angle), z: -radius * Math.cos(angle) };
+ });
+ const height = radius * Math.tan(radians(SKY_TOP));
+ group.addPolygon([
+ { position: [left.x, 0, left.z], uv: [left.u, 0] },
+ { position: [right.x, 0, right.z], uv: [right.u, 0] },
+ { position: [right.x, height, right.z], uv: [right.u, 1] },
+ { position: [left.x, height, left.z], uv: [left.u, 1] },
+ ]).material = material;
+ }
+};
+
+// The deck's boards lie across the jetty. Only its top ever faces the eye, and from above it
+// its reflection hides under it
+const addDeck = (group) => {
+ const length = (JETTY.near - JETTY.far) / DECK_LENGTHS;
+ for (let piece = 0; piece < DECK_LENGTHS; piece++) {
+ const far = JETTY.far + piece * length;
+ const points = rect(
+ "+y",
+ [-JETTY.halfWidth, DECK_TOP, far],
+ [JETTY.halfWidth, DECK_TOP, far + length],
+ );
+ const vertices = points.map(([x, y, z]) => ({
+ position: [x, y, z],
+ uv: [z / PLANKS_TILE, x / PLANKS_TILE],
+ }));
+ group.addPolygon(vertices).material = deckMaterial;
+ }
+};
+
+// A round pile standing on its group's origin. The bark wraps once around it, so its grain
+// meets itself at every edge, and the faces go in as one mesh, so the library closes the
+// joints between them and shades across them by the normals
+const addPile = (group) => {
+ const { radius, height } = PILE;
+ const around = 2 * Math.PI * radius;
+ const corners = Array.from({ length: PILE_SIDES + 1 }, (_, corner) => {
+ const angle = (corner / PILE_SIDES) * 2 * Math.PI;
+ const normal = [Math.cos(angle), 0, Math.sin(angle)];
+ const at = (y) => ({
+ position: [radius * normal[0], y, radius * normal[2]],
+ uv: [corner / PILE_SIDES, y / around],
+ normal,
+ });
+ return { angle, bottom: at(0), top: at(height) };
+ });
+ const triangles = corners.slice(1).flatMap((left, side) => {
+ const right = corners[side];
+ return [
+ [left.bottom, right.bottom, right.top],
+ [left.bottom, right.top, left.top],
+ ];
+ });
+ for (const face of group.addTriangles(triangles))
+ face.material = pileMaterial;
+ // The sawn end, its rings centred in the image. It sits a little under the rim, level with
+ // it a hairline of the lake showed between the two
+ const cap = corners
+ .slice(1)
+ .map(({ angle, top: { position } }) => ({
+ position: [position[0], height - PILE_END_INSET, position[2]],
+ uv: [
+ 0.5 + PILE_END_RADIUS * Math.cos(angle),
+ 0.5 + PILE_END_RADIUS * Math.sin(angle),
+ ],
+ }))
+ .reverse();
+ group.addPolygon(cap).material = pileEndMaterial;
+};
+
+// The piles beside the deck throw their shadows across it
+const addPiles = (parent) => {
+ const side = JETTY.halfWidth + PILE.radius;
+ for (let z = JETTY.far + PILE.radius; z < JETTY.near; z += PILE.spacing)
+ for (const x of [-side, side]) {
+ const pile = new Group();
+ pile.transform = Transform.translate([x, 0, z]);
+ parent.addChild(pile);
+ addPile(pile);
+ pile.shadowCaster = {
+ shape: "cylinder",
+ radius: PILE.radius,
+ height: PILE.height,
+ center: [0, PILE.height / 2, 0],
+ };
+ }
+};
+
+const sky = new Group();
+container.root.addChild(sky);
+addSky(sky, skyMaterial);
+
+// The lake's reflection is the sky and its hills built again and turned upside down. The
+// jetty stays out of it, its deck all but hides where it would show
+const reflection = new Group();
+reflection.transform = Transform.scale([1, -1, 1]);
+container.root.addChild(reflection);
+addSky(reflection, waterSkyMaterial);
+
+// The water's surface adds what a breeze does to it, pale crests drifting two ways
+const [waveWidth, waveDepth] = WAVE_TILE;
+for (const { near, far, halfWidth, fades } of WATER_STRIPS) {
+ const content = document.createElement("div");
+ content.className = "water";
+ // Each layer is twice the strip's width and drifts by one repeat of the waves
+ const repeat = `${((waveWidth / (4 * halfWidth)) * 100).toFixed(2)}%`;
+ content.style.setProperty(
+ "--tile",
+ `${repeat} ${((waveDepth / (near - far)) * 100).toFixed(2)}%`,
+ );
+ content.style.setProperty("--drift", repeat);
+ if (fades) content.classList.add("fades");
+ content.innerHTML = WAVE_PERIODS.map(
+ (period, layer) =>
+ ``,
+ ).join("");
+ const points = rect("+y", [-halfWidth, 0, far], [halfWidth, 0, near]);
+ const uvs = [
+ [0, 0],
+ [1, 0],
+ [1, 1],
+ [0, 1],
+ ];
+ container.root.addPolygon(
+ points.map((position, i) => ({ position, uv: uvs[i] })),
+ { contentElement: content, getDomSize: () => WATER_PIXELS },
+ );
+}
+
+const jetty = new Group();
+container.root.addChild(jetty);
+addDeck(jetty);
+addPiles(jetty);
+
+const scene = await container.toHTML({ shadows: true });
+writePage(HERE, { css: `:root{background:${SKY_ZENITH}}`, scene });
diff --git a/examples/public/demos/still-water/style.css b/examples/public/demos/still-water/style.css
new file mode 100644
index 0000000..2d959df
--- /dev/null
+++ b/examples/public/demos/still-water/style.css
@@ -0,0 +1,70 @@
+html {
+ scrollbar-width: none;
+}
+/* Scrolling the page only walks the camera, the scene stays put */
+body {
+ margin: 0;
+ height: 300vh;
+}
+.c3r-container.c3r-container {
+ position: fixed;
+ inset: 0;
+}
+
+/* Two classes, the library's own rules come later in the page and would paint it white */
+.c3r-polygon-content.water {
+ background: none;
+}
+.waves {
+ position: absolute;
+ inset: 0 -100% 0 0;
+ background: url(assets/waves.png) 0 var(--offset) / var(--tile);
+ animation: drift var(--period) linear infinite;
+}
+/* The waves thin out towards the far edge of the far strip */
+.fades > .waves {
+ mask-image: linear-gradient(#0000, #000 70%);
+}
+.waves + .waves {
+ animation-direction: reverse;
+}
+@keyframes drift {
+ to {
+ translate: calc(-1 * var(--drift));
+ }
+}
+/* The second of the camera's tweens is its sway, the first follows the scroll */
+@media (prefers-reduced-motion: reduce) {
+ .waves {
+ animation: none;
+ }
+ .c3r-view {
+ --c3r-tween-1-animation: none !important;
+ }
+}
+
+header {
+ position: fixed;
+ left: 16px;
+ top: 10px;
+ color: #26303f;
+ font:
+ 13px/1.35 Georgia,
+ serif;
+}
+h1 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: normal;
+}
+p {
+ margin: 0;
+}
+header a {
+ color: inherit;
+}
+@media (max-aspect-ratio: 1/1) {
+ .c3r-perspective {
+ --c3r-camera-fov: 90deg !important;
+ }
+}
diff --git a/package-lock.json b/package-lock.json
index 5e91220..d43a4f9 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -2080,7 +2080,7 @@
}
},
"packages/c3r": {
- "version": "0.6.0",
+ "version": "0.7.0",
"license": "MIT",
"dependencies": {
"gl-matrix": "^3.4.4"
@@ -2091,10 +2091,10 @@
}
},
"packages/c3r-three": {
- "version": "0.6.0",
+ "version": "0.7.0",
"license": "MIT",
"dependencies": {
- "c3r": "^0.6.0"
+ "c3r": "^0.7.0"
},
"devDependencies": {
"@types/three": "^0.186.0",
diff --git a/packages/c3r-three/package.json b/packages/c3r-three/package.json
index 5ad1131..8a36894 100644
--- a/packages/c3r-three/package.json
+++ b/packages/c3r-three/package.json
@@ -1,6 +1,6 @@
{
"name": "c3r-three",
- "version": "0.6.0",
+ "version": "0.7.0",
"description": "three.js CSS3DRenderer built on C3R, with geometry and texture support",
"keywords": [
"three",
@@ -34,7 +34,7 @@
"prepublishOnly": "npm run build"
},
"dependencies": {
- "c3r": "^0.6.0"
+ "c3r": "^0.7.0"
},
"peerDependencies": {
"@types/three": ">=0.160.0",
diff --git a/packages/c3r/README.md b/packages/c3r/README.md
index dfd2906..5bfd35f 100644
--- a/packages/c3r/README.md
+++ b/packages/c3r/README.md
@@ -17,7 +17,7 @@ import { Container, Polygon } from "c3r";
Or with a script tag, using [GitHub Releases](https://github.com/K-Adam/CSS3D-Renderer/releases) or a CDN:
```html
-
+
```
It bundles gl-matrix and exposes a `C3R` global.
@@ -67,7 +67,7 @@ A `Material`, `Tween`, `Timeline` or camera is a class rule in one shared styles
A `transform` array applies in order, like CSS. A tween animates a group after its `transform`, from rest or from the `from` steps, and a group's tweens apply in array order. Its keyframes play in sequence, `duration` seconds each unless written as `{ steps, duration }`, and `easing` applies to each; a keyframe is one step or an array of steps, and what it doesn't list holds. Transforms apply in the order they first appear, `from` first. Angles are radians and may exceed a half turn. A `Transform.matrix` keyframe tweens its translation, rotation and scale separately, and can't have shear, perspective or a zero scale. `Filter` steps apply to the polygons and `ElementObject` elements, and a nested group's filters replace its parent's. With `hover`, a `loop` plays only while hovered; any other tween takes one keyframe and eases to it and back. Setting `paused` later pauses everything on the tween's timeline. A hover transition can't pause, so it stops responding to hover instead. It runs on the main thread and `bake()` ignores its scale. Use a negative `delay`, in seconds, to offset the phase.
-A `Timeline({ paused, hover })` passed as `timeline` makes tweens move as one, and they take `paused` and `hover` from it. `hover` plays them while one of their groups is hovered, or the container when it runs the light's, and `bake()` brings a tween that joins later in step. A tween without one gets its own, and a hover transition can't join one.
+A `Timeline({ paused, hover })` passed as `timeline` makes tweens move as one, and they take `paused` and `hover` from it. `hover` plays them while one of their groups is hovered, or the container when it runs the light's, and `bake()` brings a tween that joins later in step. A tween without one gets its own, and a hover transition can't join one. `Timeline({ scroll: true })` plays its tweens, the camera's too, along the page's scroll, with keyframe durations as shares of it. Its tweens can't loop or wait, and where scroll timelines are missing they hold their first keyframe.
A group's `clock` runs `Group.time`, in seconds, for its own and its descendants' materials. It wraps hourly and restyles the subtree every frame, so it is off by default. Filters other than `hueRotate` and `tint` also take a `CssValue`, such as `Filter.opacity(CssValue.fn("sin", Group.time))`, which a tween can't animate.
@@ -87,6 +87,8 @@ A shaded material's `specular = { intensity, shininess, map? }` adds a white Bli
`point.tween` moves the light after `position`, so a group with that tween stays on it, and each frame restyles the whole scene. A `Transform.matrix` or filter tween throws.
+`container.fog = { color, length }` fades polygons whose material has `fog = true` into `color` (0-1) with their depth from the eye, as 1 - exp(-depth / length), from the next `bake()`. It follows the camera's tween, which then restyles every fogged polygon each frame. The layer covers the whole content element, so a hand-built translucent `contentElement` would be fogged in its transparent parts too.
+
`specular` works under a point light with the same viewer as `directional`. A flat polygon takes it at its center and a curve from three vertices. On a plane it is an oval on a child added to the content element at each `bake()`, more symmetric than the true shape, too dim where a very bright highlight should saturate, and off towards the light at a grazing view.
`group.lightGain`, a number or a `CssValue` that can read `Group.time`, multiplies the point light below the group. Run the `clock` on that group, on the root each frame restyles the scene.
diff --git a/packages/c3r/package.json b/packages/c3r/package.json
index cd5ff7e..4734b62 100644
--- a/packages/c3r/package.json
+++ b/packages/c3r/package.json
@@ -1,6 +1,6 @@
{
"name": "c3r",
- "version": "0.6.0",
+ "version": "0.7.0",
"description": "CSS 3D Renderer",
"keywords": [
"typescript",
diff --git a/packages/c3r/src/C3R.ts b/packages/c3r/src/C3R.ts
index 32fa783..3d46cd8 100644
--- a/packages/c3r/src/C3R.ts
+++ b/packages/c3r/src/C3R.ts
@@ -15,7 +15,12 @@ export { cssText, styleHTML } from "./css/styles.js";
export { Object3D } from "./dom/Object3D.js";
export { Group, type IndexedMesh, type MeshOptions } from "./dom/Group.js";
-export { type BakeOptions, Container, type Lights } from "./dom/Container.js";
+export {
+ type BakeOptions,
+ Container,
+ type Fog,
+ type Lights,
+} from "./dom/Container.js";
export { Polygon, type PolygonOptions } from "./dom/Polygon.js";
export { ElementObject } from "./dom/ElementObject.js";
export { Billboard } from "./dom/Billboard.js";
diff --git a/packages/c3r/src/css/Camera.ts b/packages/c3r/src/css/Camera.ts
index a147c72..d965fdb 100644
--- a/packages/c3r/src/css/Camera.ts
+++ b/packages/c3r/src/css/Camera.ts
@@ -12,7 +12,8 @@ import {
ownTransform,
type Transform,
} from "./Transform.js";
-import { setTweens, type Tween } from "./Tween.js";
+import { joinTimeline } from "./Timeline.js";
+import { setTweens, timelineOf, type Tween } from "./Tween.js";
let nextId = 0;
@@ -34,6 +35,12 @@ export abstract class Camera {
`.${this.className} > .c3r-view`,
this,
);
+ // Replays the tweens on elements that read the camera, without the view's
+ // matrix and inputs
+ #followerRule: CSSStyleRule | null = insertRule(
+ `.${this.className} .c3r-camera-follower:not(.${this.className} .c3r-container *)`,
+ this,
+ );
constructor() {
viewMatrices.set(this, mat4.create());
@@ -62,6 +69,14 @@ export abstract class Camera {
set tween(tween: Tween | readonly Tween[] | null) {
const tweens = setTweens(this.#viewRule?.style, tween, true);
+ // Only the clock, a value read from the animated variables would restyle
+ // the slow way on every follower
+ setTweens(this.#followerRule?.style, tween, true, "", true);
+ // So a bake brings followers that start later in step with the view
+ for (const t of tweens) {
+ const timeline = timelineOf(t);
+ if (timeline && !timeline.scroll) joinTimeline(timeline, t.className);
+ }
this.#tween = Array.isArray(tween) ? tweens : tween;
this.#refresh();
}
@@ -76,8 +91,9 @@ export abstract class Camera {
// Not from the constructor, an input rule may read a subclass's fields,
// which exist once it sets its params
#refresh(): void {
- const style = this.#viewRule?.style;
- if (style) refreshCamera(this, style);
+ const view = this.#viewRule?.style;
+ const follower = this.#followerRule?.style;
+ if (view && follower) refreshCamera(this, view, follower);
}
// Rewriting an unchanged rule would still restyle the whole scene
@@ -92,6 +108,7 @@ export abstract class Camera {
forgetCamera(this);
deleteRule(this.#paramsRule);
deleteRule(this.#viewRule);
- this.#paramsRule = this.#viewRule = null;
+ deleteRule(this.#followerRule);
+ this.#paramsRule = this.#viewRule = this.#followerRule = null;
}
}
diff --git a/packages/c3r/src/css/Material.ts b/packages/c3r/src/css/Material.ts
index 862d7a2..a4d09e3 100644
--- a/packages/c3r/src/css/Material.ts
+++ b/packages/c3r/src/css/Material.ts
@@ -57,6 +57,9 @@ export class Material {
#rule: CSSStyleRule | null = insertRule(`.${this.className}`, this);
+ // From the next bake, null inherits
+ fog: boolean | null = null;
+
// An rgba color, 0-1, or an image url; either hides the other from a parent
get background(): ReadonlyVec4 | string | null {
return this.#background;
diff --git a/packages/c3r/src/css/Timeline.ts b/packages/c3r/src/css/Timeline.ts
index 39ced80..56b66b7 100644
--- a/packages/c3r/src/css/Timeline.ts
+++ b/packages/c3r/src/css/Timeline.ts
@@ -5,8 +5,15 @@ export interface TimelineOptions {
// Plays only while a group in the container runs one of its tweens and is
// hovered, or the container itself when it runs the light's
hover?: boolean;
+ // Follows the page's scroll instead of the clock
+ scroll?: boolean;
}
+// Can't take a tween's or timeline's class, so they share its variables: a
+// camera's view, and the elements that replay its tweens to read the camera
+// without restyling what is between
+export const CAMERA_ELEMENTS = ".c3r-view, .c3r-camera-follower";
+
const members = new WeakMap>();
const dirty = new Set();
@@ -15,16 +22,23 @@ let nextId = 0;
// Tweens that pause, hover and start as one
export class Timeline {
readonly className = `c3r-timeline-${nextId++}`;
+ readonly scroll: boolean;
#paused = false;
#rules: CSSRule[] = [];
- // A camera's view can't take the class, so it shares the state
#rule: CSSStyleRule | null = insertRule(
- `.${this.className}, .c3r-view`,
+ `.${this.className}, ${CAMERA_ELEMENTS}`,
this,
);
- constructor({ paused = false, hover = false }: TimelineOptions = {}) {
+ constructor({
+ paused = false,
+ hover = false,
+ scroll = false,
+ }: TimelineOptions = {}) {
+ if (scroll && (paused || hover))
+ throw new RangeError("A scroll timeline can't pause or play on hover");
+ this.scroll = scroll;
this.#rules.push(this.#rule!);
members.set(this, new Set());
if (hover) {
@@ -32,7 +46,7 @@ export class Timeline {
const idle = `.c3r-container:not(:has(.c3r-group${own}:hover), ${own}:hover)`;
this.#rules.push(
insertRule(
- `${idle}${own}, ${idle} ${own}, ${idle} .c3r-view`,
+ `${idle}${own}, ${idle} ${own}, ${idle} :is(${CAMERA_ELEMENTS})`,
this,
`{ ${this.state}: paused; }`,
),
@@ -42,7 +56,18 @@ export class Timeline {
insertRule(`.c3r-group${own}`, this, "{ pointer-events: auto; }"),
);
}
- this.paused = paused;
+ if (scroll) {
+ // Held at the first pose where scroll timelines are missing, the clock
+ // would play it to the end
+ this.#rule!.style.setProperty(this.state, "paused");
+ this.#rules.push(
+ insertRule(
+ "@supports (animation-timeline: scroll())",
+ this,
+ `{ .${this.className}, ${CAMERA_ELEMENTS} { ${this.state}: running; } }`,
+ ),
+ );
+ } else this.paused = paused;
}
get state(): string {
@@ -54,6 +79,7 @@ export class Timeline {
}
set paused(paused: boolean) {
+ if (this.scroll) throw new RangeError("A scroll timeline can't pause");
this.#paused = paused;
this.#rule?.style.setProperty(this.state, paused ? "paused" : "running");
}
diff --git a/packages/c3r/src/css/Tween.ts b/packages/c3r/src/css/Tween.ts
index d56741f..f5a25b5 100644
--- a/packages/c3r/src/css/Tween.ts
+++ b/packages/c3r/src/css/Tween.ts
@@ -6,6 +6,7 @@ import { type Filter, filterTexts, filterVariables } from "./Filter.js";
import { inverseStepValue, type Step, stepOf, stepText } from "./steps.js";
import { deleteRule, insertRule, plainValue } from "./styles.js";
import {
+ CAMERA_ELEMENTS,
joinTimeline,
leaveTimeline,
Timeline,
@@ -36,12 +37,15 @@ interface Style {
filter?: string;
layers?: string;
animation?: string;
+ timeline?: string;
transition?: string;
hover?: boolean;
}
const styles = new WeakMap();
+const SCROLL = "scroll(root)";
+
type AnimatedStep = { step: Step; args: string[] };
const animatedSteps = new WeakMap();
@@ -213,6 +217,8 @@ export function setTweens(
inverse = false,
// An inline animation replaces any other, so the group's clock joins the list
extra = "",
+ // Writes only the animations, for elements that replay them
+ clockOnly = false,
): readonly Tween[] {
const tweens = Object.freeze([...new Set([tween ?? []].flat())]);
const parts = tweens.map((tween) => {
@@ -225,11 +231,20 @@ export function setTweens(
});
const list = (key: keyof Style, separator: string, from = parts) =>
from.flatMap((part) => part[key] ?? []).join(separator);
+ // One per animation, in its order
+ const animationTimelines = [
+ ...parts.flatMap((part) => part.timeline ?? []),
+ ...(extra ? ["auto"] : []),
+ ];
const properties = {
"--c3r-tween-transform": inverse
? list("inverse", " ", parts.toReversed())
: list("transform", " "),
animation: [list("animation", ", "), extra].filter(Boolean).join(", "),
+ // After the shorthand, which resets it
+ "animation-timeline": animationTimelines.includes(SCROLL)
+ ? animationTimelines.join(", ")
+ : "",
transition: list("transition", ", "),
...filterVariables(
"--c3r-tween-",
@@ -238,6 +253,7 @@ export function setTweens(
),
};
for (const [name, value] of Object.entries(properties)) {
+ if (clockOnly && !name.startsWith("animation")) continue;
if (value) style?.setProperty(name, value);
else style?.removeProperty(name);
}
@@ -344,6 +360,8 @@ export class Tween {
throw new RangeError(
"A tween on a timeline takes its pause and hover from it, and can't move on hover",
);
+ if (timeline?.scroll && (loop || delay))
+ throw new RangeError("A tween on the scroll can't loop or wait");
// Its own properties, so tweens on one element don't clash
const track = `--${this.className}`;
@@ -367,9 +385,8 @@ export class Tween {
.join(" ");
const total = times[times.length - 1];
- // A camera's view can't take the class, so it shares the variables
this.#rule = insertRule(
- hover ? `.${this.className}` : `.${this.className}, .c3r-view`,
+ hover ? `.${this.className}` : `.${this.className}, ${CAMERA_ELEMENTS}`,
this,
);
this.#rules.push(this.#rule);
@@ -437,7 +454,9 @@ export class Tween {
timelines.set(this, own);
// Shared ones start together. A private loop does too, but a group
// hovered on its own keeps its own time and a one-shot plays from its start
- if (timeline || (loop && !hover)) joinTimeline(own, this.className);
+ // The scroll keeps its own in step
+ if ((timeline && !timeline.scroll) || (loop && !hover))
+ joinTimeline(own, this.className);
const count = loop ? "infinite" : 1;
const direction = alternate ? "alternate" : "normal";
style.setProperty(
@@ -445,6 +464,7 @@ export class Tween {
`${this.className} ${total}s ${timing} ${count} ${direction} both var(${own.state}, running)`,
);
part.animation = `var(${track}-animation, none)`;
+ part.timeline = own.scroll ? SCROLL : "auto";
if (hover) {
// Each group plays while it is hovered itself, over the timeline's rule
this.#hoverRule = insertRule(
diff --git a/packages/c3r/src/dom/Accumulator.ts b/packages/c3r/src/dom/Accumulator.ts
index 5f29c30..1e3eb9f 100644
--- a/packages/c3r/src/dom/Accumulator.ts
+++ b/packages/c3r/src/dom/Accumulator.ts
@@ -1,5 +1,5 @@
import type { Camera } from "../css/Camera.js";
-import type { Composite, CssVector } from "../css/CssMatrix.js";
+import { type Composite, CssVector } from "../css/CssMatrix.js";
import { cssVar, CssValue, textOf } from "../css/CssValue.js";
import { deleteRule, insertRule, plainValue } from "../css/styles.js";
@@ -23,6 +23,9 @@ export interface AccumulatorOptions<
polygonsRead?: boolean;
combine: (parent: T, input: I) => T;
input?: (node: Object3D | Camera) => I | null;
+ // Numbers from the camera alone, as --name-camera-k on its followers, so a
+ // camera move restyles only the readers inside them
+ camera?: { size: number; value: (camera: Camera) => CssVector };
}
type AnyAccumulator = Accumulator;
@@ -37,6 +40,21 @@ const textsOf = (count: number, value: CssValue | Composite): string[] => {
return components.map(textOf);
};
+// A failing rule is reported and leaves no texts
+const reported = (
+ count: number,
+ value: () => CssValue | Composite | null,
+): string[] => {
+ try {
+ const result = value();
+ return result === null ? [] : textsOf(count, result);
+ } catch (error) {
+ if (typeof reportError === "function") reportError(error);
+ else console.error(error);
+ return [];
+ }
+};
+
const propertiesOf = (
name: string,
value: CssValue | Composite,
@@ -55,13 +73,15 @@ const properties = new Set();
const released = new FinalizationRegistry((names: string[]) => {
for (const p of names) properties.delete(p);
for (const camera of live(cameras))
- for (const p of names) cameraStyles.get(camera)!.removeProperty(p);
+ for (const style of [cameraStyles, followerStyles])
+ for (const p of names) style.get(camera)!.removeProperty(p);
});
// Weak, so neither keeps the other alive
const inputs = new Set>();
const cameras = new Set>();
const cameraStyles = new WeakMap();
+const followerStyles = new WeakMap();
const live = (refs: Set>): T[] => {
const alive: T[] = [];
@@ -93,15 +113,18 @@ export const refreshInput = (node: Object3D): void => {
export const refreshCamera = (
camera: Camera,
style: CSSStyleDeclaration,
+ follower: CSSStyleDeclaration,
): void => {
if (!cameraStyles.has(camera)) cameras.add(new WeakRef(camera));
cameraStyles.set(camera, style);
+ followerStyles.set(camera, follower);
for (const acc of live(inputs)) write(acc, camera, style);
};
// Firefox throws on writing to a deleted rule's style
export const forgetCamera = (camera: Camera): void => {
cameraStyles.delete(camera);
+ followerStyles.delete(camera);
for (const ref of cameras) if (ref.deref() === camera) cameras.delete(ref);
};
@@ -126,6 +149,7 @@ function validate(
syntax: string,
identity: CssValue | CssVector,
inputIdentity: CssValue | Composite,
+ cameraProperties: readonly string[],
): void {
if (!/^[a-z_][\w-]*$/i.test(name))
throw new RangeError(
@@ -134,6 +158,7 @@ function validate(
const names = [
...propertiesOf(name, identity),
...propertiesOf(name, inputIdentity, "-input"),
+ ...cameraProperties,
];
if (names.some((p) => properties.has(p)))
throw new RangeError(`${name} is in use, dispose its Accumulator first`);
@@ -158,9 +183,13 @@ export class Accumulator<
readonly className = `c3r-accumulator-${nextId++}`;
readonly result: T;
+ // The camera option's numbers, as read on its view and followers
+ readonly camera: CssVector | undefined;
readonly #names: readonly string[];
readonly #inputProperties: readonly string[];
+ readonly #cameraProperties: readonly string[];
+ readonly #cameraValue: ((camera: Camera) => CssVector) | undefined;
readonly #input: AccumulatorOptions["input"];
readonly #start: string;
readonly #weakSelf: WeakRef = new WeakRef(this);
@@ -184,10 +213,18 @@ export class Accumulator<
const { combine, input } = options;
const inputIdentity: CssValue | Composite =
options.inputIdentity ?? identity;
- validate(name, syntax, identity, inputIdentity);
+ const cameraProperties = Array.from(
+ { length: options.camera?.size ?? 0 },
+ (_, k) => `--${name}-camera-${k}`,
+ );
+ validate(name, syntax, identity, inputIdentity, cameraProperties);
const resultProperties = propertiesOf(name, identity);
const inputProperties = propertiesOf(name, inputIdentity, "-input");
- const names = [...resultProperties, ...inputProperties];
+ const names = [
+ ...resultProperties,
+ ...inputProperties,
+ ...cameraProperties,
+ ];
const initials = componentsOf(identity).map(textOf);
const slot = (i: number, k: number) => `--${this.className}-${i}-${k}`;
const flag = `--${this.className}-odd`;
@@ -236,6 +273,10 @@ export class Accumulator<
componentsOf(inputIdentity).forEach((initial, k) =>
register(inputProperties[k], false, textOf(initial)),
);
+ // Inherited from the follower, a reader that animates itself restyles
+ // several times slower than one that inherits
+ for (const property of cameraProperties)
+ register(property, true, initials[0]);
// Emulates `--name: combine(inherit(--name), var(--name-input))` until
// Firefox ships inherit() and Chrome enables it, then the parent ref
// turns into it: a node reads its parent's slot and writes the other,
@@ -265,8 +306,13 @@ export class Accumulator<
}
for (const p of names) properties.add(p);
this.result = refs(identity, resultProperties);
+ this.camera = cameraProperties.length
+ ? new CssVector(cameraProperties.map((p) => cssVar(p, syntax)))
+ : undefined;
this.#names = names;
this.#inputProperties = inputProperties;
+ this.#cameraProperties = cameraProperties;
+ this.#cameraValue = options.camera?.value;
this.#input = input;
const starts = resultProperties
.map((p, k) => `${p}: var(${slot(0, k)});`)
@@ -309,18 +355,20 @@ export class Accumulator<
// A failing rule leaves the identity, so the tree stays consistent
#write(node: Object3D | Camera, style: CSSStyleDeclaration): void {
if (!this.#input || !this.#rules.length) return;
- let texts: string[] = [];
- try {
- const result = this.#input(node);
- if (result !== null)
- texts = textsOf(this.#inputProperties.length, result);
- } catch (error) {
- if (typeof reportError === "function") reportError(error);
- else console.error(error);
- }
+ const input = this.#input;
+ const texts = reported(this.#inputProperties.length, () => input(node));
this.#inputProperties.forEach((p, k) =>
style.setProperty(p, texts[k] ?? ""),
);
+ const follower = followerStyles.get(node as Camera);
+ const cameraValue = this.#cameraValue;
+ if (!cameraValue || !follower) return;
+ const values = reported(this.#cameraProperties.length, () =>
+ cameraValue(node as Camera),
+ );
+ this.#cameraProperties.forEach((p, k) =>
+ follower.setProperty(p, values[k] ?? ""),
+ );
}
#clearInput(style: CSSStyleDeclaration): void {
@@ -363,7 +411,10 @@ export class Accumulator<
for (const p of this.#names) properties.delete(p);
inputs.delete(this.#weakSelf);
if (this.#input)
- for (const camera of live(cameras))
+ for (const camera of live(cameras)) {
this.#clearInput(cameraStyles.get(camera)!);
+ for (const p of this.#cameraProperties)
+ followerStyles.get(camera)!.removeProperty(p);
+ }
}
}
diff --git a/packages/c3r/src/dom/Container.ts b/packages/c3r/src/dom/Container.ts
index 9694356..25483aa 100644
--- a/packages/c3r/src/dom/Container.ts
+++ b/packages/c3r/src/dom/Container.ts
@@ -15,6 +15,7 @@ import {
} from "../css/Tween.js";
import { ElementObject } from "./ElementObject.js";
+import { setFogged } from "./Fog.js";
import { Group, touchSubtree } from "./Group.js";
import { matrixOf, type Object3D, parents } from "./Object3D.js";
import { measurePolygon, Polygon } from "./Polygon.js";
@@ -37,6 +38,12 @@ export interface Lights {
};
}
+// Color 0-1
+export interface Fog {
+ readonly color: ReadonlyVec3;
+ readonly length: number;
+}
+
export interface BakeOptions {
// Costly, other bakes keep them as cast
shadows?: boolean;
@@ -63,6 +70,7 @@ export class Container {
#unitScale = 1;
#refit: Promise | null = null;
#lights: Readonly | null = null;
+ #fog: Fog | null = null;
#connected = false;
#castShadows = false;
@@ -172,6 +180,34 @@ export class Container {
style.setProperty(`--c3r-light-${name}`, String(value));
}
+ get fog(): Fog | null {
+ return this.#fog;
+ }
+
+ set fog(fog: Fog | null) {
+ const { style } = this.domElement;
+ if (!fog) {
+ this.#fog = null;
+ style.removeProperty("--c3r-fog-color");
+ style.removeProperty("--c3r-fog-density");
+ return;
+ }
+ const color = vector(fog.color);
+ if (!color.every((c) => c >= 0 && c <= 1))
+ throw new RangeError(`Invalid fog color ${color}`);
+ if (!(fog.length > 0 && Number.isFinite(fog.length)))
+ throw new RangeError(`Invalid fog length ${fog.length}`);
+ this.#fog = Object.freeze({
+ color: Object.freeze(color),
+ length: fog.length,
+ });
+ style.setProperty(
+ "--c3r-fog-color",
+ color.map((c) => Math.round(c * 255)).join(" "),
+ );
+ style.setProperty("--c3r-fog-density", String(1 / fog.length));
+ }
+
get width(): number {
return this.#width;
}
@@ -220,6 +256,7 @@ export class Container {
specular: Specular | null,
diffuseMap: string | null,
shadows: Shadows | null,
+ fogged: boolean,
) => {
if (node.domElement.style.display === "none") return;
// Like the CSS variables: an image or a color replaces, null inherits
@@ -235,9 +272,11 @@ export class Container {
specular = material?.specular ?? specular;
if (material?.diffuse) diffuseMap = material.diffuse.map || null;
shadows = material?.shadows ?? shadows;
+ fogged = material?.fog ?? fogged;
if (node instanceof Group && node.shadowCaster) casters.push(node);
if (node instanceof Polygon) {
polygons.push({ polygon: node, shadows });
+ setFogged(node, fogged);
setShaded(
node,
shading,
@@ -265,7 +304,17 @@ export class Container {
if (scale > 0) density = Math.max(density, 1 / scale);
} else if (node instanceof Group) {
for (const child of node.children)
- visit(child, m, image, cells, shading, specular, diffuseMap, shadows);
+ visit(
+ child,
+ m,
+ image,
+ cells,
+ shading,
+ specular,
+ diffuseMap,
+ shadows,
+ fogged,
+ );
}
};
visit(
@@ -277,6 +326,7 @@ export class Container {
null,
null,
null,
+ false,
);
// Sizes and matrices are final once every image is in
if (!loading.length) {
@@ -294,8 +344,9 @@ export class Container {
if (isConnected && !this.#connected) {
touchSubtree(this.#root);
touchTweens(this.#lights?.point?.tween ?? null);
- touchTweens(this.#camera.tween);
}
+ // Fog layers added since replay the camera from their own start
+ touchTweens(this.#camera.tween);
this.#connected = isConnected;
syncTimelines();
}
diff --git a/packages/c3r/src/dom/Fog.ts b/packages/c3r/src/dom/Fog.ts
new file mode 100644
index 0000000..bee7fb2
--- /dev/null
+++ b/packages/c3r/src/dom/Fog.ts
@@ -0,0 +1,192 @@
+import { mat4, type ReadonlyMat4 } from "gl-matrix";
+
+import { Camera, viewMatrixOf } from "../css/Camera.js";
+import { CssMatrix, CssVector } from "../css/CssMatrix.js";
+import { type Arg, CssValue, cssRaw, cssVar, textOf } from "../css/CssValue.js";
+import { insertRule } from "../css/styles.js";
+import type { transformSteps } from "../css/Tween.js";
+
+import { type Accumulator, libraryAccumulator } from "./Accumulator.js";
+import { Group } from "./Group.js";
+import { matrixOf, type Object3D } from "./Object3D.js";
+import { type Polygon, setFogLayer } from "./Polygon.js";
+import { CONTENT, stepsOf } from "./Shading.js";
+
+type AnimatedStep = ReturnType[number];
+
+// Shaped like an affine matrix's transpose: the translation is the bottom row
+const transposedAffine = (m: readonly Arg[], t: readonly Arg[] = [0, 0, 0]) =>
+ new CssMatrix([
+ ...m.slice(0, 3),
+ t[0],
+ ...m.slice(3, 6),
+ t[1],
+ ...m.slice(6),
+ t[2],
+ 0,
+ 0,
+ 0,
+ 1,
+ ]);
+
+// A plane goes through a step by the transpose of its matrix, and the other way
+// by the transpose of its inverse
+const planeStep = (
+ { step, args }: AnimatedStep,
+ inverse: boolean,
+): CssMatrix => {
+ if (step.moves)
+ return transposedAffine(
+ [1, 0, 0, 0, 1, 0, 0, 0, 1],
+ args.map((arg) =>
+ cssRaw(`calc(${inverse ? -1 : 1} * ${arg} / 1px)`, ""),
+ ),
+ );
+ if (!step.normal)
+ throw new RangeError("Fog can't follow a Transform.matrix tween");
+ // A rotation's normal matrix is the rotation itself
+ if (step.rotates) {
+ const r = step.normal(args);
+ return transposedAffine((inverse ? r : r.transpose()).components);
+ }
+ const [x, y, z] = args.map((arg) => {
+ const n = cssRaw(arg, "");
+ return inverse ? CssValue.div(1, n) : n;
+ });
+ return transposedAffine([x, 0, 0, 0, y, 0, 0, 0, z]);
+};
+
+const transposed = (m: ReadonlyMat4) =>
+ new CssMatrix(mat4.transpose(mat4.create(), m));
+
+// Camera space looks down -z
+const CAMERA_PLANE = new CssVector([0, 0, -1, 0]);
+
+// Into each group's space, exact under any affine transform so the depth stays
+// in world units. Only the camera's pose folds down the chain, its tweens move
+// the plane on the fog layers, so a camera move restyles those and nothing above
+const planeInput = (node: Object3D | Camera): CssMatrix | null => {
+ if (node instanceof Camera) return transposed(viewMatrixOf(node));
+ if (!(node instanceof Group)) return null;
+ return stepsOf(node.tween).reduce(
+ (out, step) => planeStep(step, false).mul(out),
+ transposed(matrixOf(node)),
+ );
+};
+
+const STOPS = 6;
+
+const position = (name: string) =>
+ new CssVector(
+ ["x", "y", "z"].map((k) =>
+ cssVar(`--c3r-position-${name}-${k}`, ""),
+ ),
+ );
+
+const tweenedPlane = (camera: Camera): CssVector =>
+ stepsOf(camera.tween)
+ .reduce(
+ (out, step) => out.mul(planeStep(step, true)),
+ CssMatrix.identity(4),
+ )
+ .transform(CAMERA_PLANE);
+
+const AXES = [0, 1, 2, 3];
+const columnsOf = (v: CssVector) =>
+ AXES.map((j) => new CssVector(v.components.slice(4 * j, 4 * j + 4)));
+
+function createFog(): Accumulator {
+ // The four basis planes fold, as the fold is linear any plane the camera's
+ // tweens make is then a sum of them
+ const acc = libraryAccumulator({
+ name: "c3r-fog-plane",
+ syntax: "",
+ identity: new CssVector(Array(16).fill(0)),
+ inputIdentity: CssMatrix.identity(4),
+ start: new CssVector(CssMatrix.identity(4).components),
+ polygonsRead: true,
+ combine: (parent, input) =>
+ new CssVector(
+ columnsOf(parent).flatMap(
+ (column) => input.transform(column).components,
+ ),
+ ),
+ input: planeInput,
+ camera: { size: 4, value: tweenedPlane },
+ });
+ // Each basis plane's depth fields hold still, so the polygon computes them
+ // once and a camera move only weighs them on the fog layer
+ const FIELDS = ["center", "x", "y"];
+ const basisField = (field: string, j: number) => `--c3r-fog-${field}-${j}`;
+ const basisFields = columnsOf(acc.result)
+ .flatMap((column, j) => {
+ const normal = new CssVector(column.components.slice(0, 3));
+ return FIELDS.map((field) => {
+ const along = normal.dot(position(field));
+ const value =
+ field === "center"
+ ? CssValue.add(along, column.components[3])
+ : along;
+ return `${basisField(field, j)}: ${textOf(value)};`;
+ });
+ })
+ .join(" ");
+ const weighed = FIELDS.map(
+ (field) =>
+ `--c3r-fog-${field}: ${textOf(
+ new CssVector(
+ AXES.map((j) => cssVar(basisField(field, j), "")),
+ ).dot(acc.camera!),
+ )};`,
+ ).join(" ");
+ for (const field of FIELDS)
+ for (const j of AXES)
+ insertRule(
+ `@property ${basisField(field, j)}`,
+ acc,
+ `{ syntax: ""; inherits: true; initial-value: 0; }`,
+ );
+ for (const name of [...FIELDS, "reach"])
+ insertRule(
+ `@property --c3r-fog-${name}`,
+ acc,
+ `{ syntax: ""; inherits: false; initial-value: 0; }`,
+ );
+ // So a nested container doesn't take the fog of the one around it
+ insertRule(
+ ".c3r-container",
+ acc,
+ "{ --c3r-fog-color: 0 0 0; --c3r-fog-density: 0; }",
+ );
+ const polygon = `.c3r-polygon.${acc.className}`;
+ insertRule(polygon, acc, `{ ${basisFields} }`);
+ // The content's mask then cuts the fog out where a texture is transparent
+ insertRule(`${polygon} ${CONTENT}`, acc, "{ --c3r-shaded: alpha; }");
+ // Depth is linear across the face and the gradient line spans it exactly, so
+ // even stops sample the falloff
+ const stops = Array.from({ length: STOPS }, (_, i) => {
+ const depth = `var(--c3r-fog-center) + var(--c3r-fog-reach) * ${(2 * i) / (STOPS - 1) - 1}`;
+ return `rgb(var(--c3r-fog-color) / calc(1 - exp(-1 * max(0, ${depth}) * var(--c3r-fog-density)))) ${(100 * i) / (STOPS - 1)}%`;
+ }).join();
+ const follower = `${polygon} ${CONTENT} > .c3r-camera-follower`;
+ // Above the highlight, and tinted by the content's filter like the rest of it
+ insertRule(
+ follower,
+ acc,
+ "{ position: absolute; inset: 0; z-index: 1; pointer-events: none; }",
+ );
+ insertRule(
+ `${follower} > .c3r-polygon-fog`,
+ acc,
+ `{ position: absolute; inset: 0; ${weighed} --c3r-fog-reach: calc((abs(var(--c3r-fog-x)) * var(--c3r-width) + abs(var(--c3r-fog-y)) * var(--c3r-height)) / 2px); background-image: linear-gradient(atan2(var(--c3r-fog-x), calc(-1 * var(--c3r-fog-y))), ${stops}); }`,
+ );
+ return acc;
+}
+
+let fog: Accumulator | undefined;
+
+export const setFogged = (polygon: Polygon, fogged: boolean): void => {
+ setFogLayer(polygon, fogged);
+ if (fogged) (fog ??= createFog()).addTarget(polygon);
+ else fog?.removeTarget(polygon);
+};
diff --git a/packages/c3r/src/dom/Polygon.ts b/packages/c3r/src/dom/Polygon.ts
index 0f4f91c..f0ee7aa 100644
--- a/packages/c3r/src/dom/Polygon.ts
+++ b/packages/c3r/src/dom/Polygon.ts
@@ -170,6 +170,7 @@ const PAST_CLIP = 2;
// Friend access for Shading
export let setGlint: (polygon: Polygon, glint: boolean) => void;
+export let setFogLayer: (polygon: Polygon, fogged: boolean) => void;
export let setSmooth: (
polygon: Polygon,
@@ -179,9 +180,12 @@ export let setSmooth: (
mapped: boolean,
) => void;
-const FIELD = ["center", "x", "y"].flatMap((name) =>
- ["x", "y", "z"].map((k) => `--c3r-normal-${name}-${k}`),
-);
+const fieldNames = (prefix: string) =>
+ ["center", "x", "y"].flatMap((name) =>
+ ["x", "y", "z"].map((k) => `--c3r-${prefix}-${name}-${k}`),
+ );
+const NORMAL_FIELD = fieldNames("normal");
+const POSITION_FIELD = fieldNames("position");
export class Polygon extends Object3D {
readonly vertices: readonly Vertex[]; // vertices in CCW
@@ -213,6 +217,7 @@ export class Polygon extends Object3D {
#planar: boolean;
#lit: "radial" | "vertex" | null = null;
#glint: HTMLElement | null = null;
+ #fog: HTMLElement | null = null;
#mapped = false;
constructor(
@@ -304,6 +309,7 @@ export class Polygon extends Object3D {
static {
measurePolygon = (polygon, size) => polygon.#measure(size);
setGlint = (polygon, glint) => polygon.#setGlint(glint);
+ setFogLayer = (polygon, fogged) => polygon.#setFog(fogged);
setSmooth = (polygon, smooth, hasImage, point, mapped) =>
polygon.#setSmooth(smooth, hasImage, point, mapped);
}
@@ -323,6 +329,23 @@ export class Polygon extends Object3D {
}
}
+ #setFog(fogged: boolean): void {
+ if (fogged === !!this.#fog) return;
+ if (fogged) {
+ // The follower replays the camera and hands it down, the layer inside
+ // computes from what it inherits, which is the cheap way to restyle
+ this.#fog = document.createElement("div");
+ this.#fog.classList.add("c3r-camera-follower");
+ this.#fog.appendChild(document.createElement("div")).className =
+ "c3r-polygon-fog";
+ this.contentElement.appendChild(this.#fog);
+ } else {
+ this.#fog!.remove();
+ this.#fog = null;
+ }
+ this.#updateContent();
+ }
+
#setSmooth(
smooth: boolean,
hasImage: boolean,
@@ -351,20 +374,36 @@ export class Polygon extends Object3D {
}
// Around the content box's center, which a gradient line runs through
- #writeNormalField(contentPoints: readonly ReadonlyVec2[]): void {
+ #writeFields(contentPoints: readonly ReadonlyVec2[]): void {
const points = contentPoints.map(([u, v]) =>
vec2.fromValues(
(u - 0.5) * this.#blockWidth,
(v - 0.5) * this.#blockHeight,
),
);
+ const { style } = this.domElement;
+ if (this.#fog) {
+ const field = normalField(
+ points,
+ this.vertices.map((v) => v.position),
+ );
+ POSITION_FIELD.forEach((name, i) =>
+ style.setProperty(name, String(field[i])),
+ );
+ }
+ if (this.#smooth) this.#writeNormalField(points);
+ }
+
+ #writeNormalField(points: readonly ReadonlyVec2[]): void {
const face = newellNormal(this.vertices);
const { style } = this.domElement;
style.setProperty("--c3r-normal-width", String(this.#blockWidth));
style.setProperty("--c3r-normal-height", String(this.#blockHeight));
const normals = vertexNormals(this.vertices, face);
const field = normalField(points, normals);
- FIELD.forEach((name, i) => style.setProperty(name, String(field[i])));
+ NORMAL_FIELD.forEach((name, i) =>
+ style.setProperty(name, String(field[i])),
+ );
if (this.#lit === "radial") this.#writePlane(points);
if (this.#lit === "vertex") this.#writeVertices(points, normals);
}
@@ -628,7 +667,7 @@ export class Polygon extends Object3D {
style.removeProperty("transform");
style.removeProperty("--c3r-uv-position");
style.removeProperty("--c3r-uv-size");
- if (this.#smooth) this.#writeNormalField(this.#vertexPoints);
+ this.#writeFields(this.#vertexPoints);
return;
}
@@ -735,9 +774,9 @@ export class Polygon extends Object3D {
`translate(${TX[6] * 100}%,${TX[7] * 100}%)` +
`matrix(${[TX[0], TX[1] * bh, TX[3] / bh, TX[4], 0, 0].join()})`;
- if (!this.#smooth) return;
+ if (!this.#smooth && !this.#fog) return;
const toContent = mat3.invert(mat3.create(), TX) ?? mat3.create();
- this.#writeNormalField(
+ this.#writeFields(
this.#vertexPoints.map((p) =>
vec2.transformMat3(vec2.create(), p, toContent),
),
diff --git a/packages/c3r/src/dom/Shading.ts b/packages/c3r/src/dom/Shading.ts
index f9df710..dc81468 100644
--- a/packages/c3r/src/dom/Shading.ts
+++ b/packages/c3r/src/dom/Shading.ts
@@ -22,7 +22,7 @@ function staticNormal(matrix: ReadonlyMat4): CssMatrix {
return new CssMatrix(mat3.multiplyScalar(m, m, 1 / size));
}
-const stepsOf = (tween: Tween | readonly Tween[] | null) =>
+export const stepsOf = (tween: Tween | readonly Tween[] | null) =>
[tween ?? []].flat().flatMap((t) => transformSteps(t));
const normalOf = (
@@ -176,7 +176,7 @@ const FOLD = {
polygonsRead: true,
};
-const CONTENT = "> .c3r-polygon-clip > .c3r-polygon-content";
+export const CONTENT = "> .c3r-polygon-clip > .c3r-polygon-content";
const SPECULAR_STOPS = 8;
diff --git a/packages/c3r/src/dom/Shadows.ts b/packages/c3r/src/dom/Shadows.ts
index 1aaacff..4851798 100644
--- a/packages/c3r/src/dom/Shadows.ts
+++ b/packages/c3r/src/dom/Shadows.ts
@@ -492,6 +492,8 @@ function driverOf(tweens: readonly Tween[]): Driver {
};
}
const timeline = [...timelines][0] as Timeline;
+ if (timeline.scroll)
+ throw new RangeError("A shadow can't follow a scroll timeline");
const period = periodOf(tweens);
const keys = tweens.flatMap((tween) => {
const cycle = tweenCycle(tween);
diff --git a/packages/c3r/test/c3r.test.ts b/packages/c3r/test/c3r.test.ts
index a8ccea3..58153fb 100644
--- a/packages/c3r/test/c3r.test.ts
+++ b/packages/c3r/test/c3r.test.ts
@@ -601,9 +601,9 @@ describe("ElementObject", () => {
// A class rule's declarations, or "" once it is gone
const ruleOf = (className: string) =>
- new RegExp(String.raw`\.${className}(, \.c3r-view)? \{[^}]*`).exec(
- cssText(),
- )?.[0] ?? "";
+ new RegExp(
+ String.raw`\.${className}(, \.c3r-view, \.c3r-camera-follower)? \{[^}]*`,
+ ).exec(cssText())?.[0] ?? "";
describe("Material", () => {
it("styles objects through a class rule, removed on dispose", () => {
@@ -943,6 +943,59 @@ describe("Tween", () => {
expect(style.cssText).toBe("");
});
+ it("follows the scroll on a scroll timeline, held at the start without it", () => {
+ using scroll = new Timeline({ scroll: true });
+ using walk = new Tween({
+ keyframes: [Transform.translate([0, 0, -100])],
+ timeline: scroll,
+ });
+ using spin = new Tween({
+ keyframes: [Transform.rotateY(turn)],
+ loop: true,
+ });
+ expect(cssText()).toContain(
+ `.${scroll.className}, .c3r-view, .c3r-camera-follower { ${scroll.state}: paused; }`,
+ );
+ expect(cssText()).toContain(
+ `@supports (animation-timeline: scroll()) { .${scroll.className}, .c3r-view, .c3r-camera-follower { ${scroll.state}: running; } }`,
+ );
+
+ const group = new Group();
+ group.clock = true;
+ group.tween = [spin, walk];
+ const { style } = group.domElement;
+ expect(style.animation).toBe(
+ `var(--${spin.className}-animation, none), var(--${walk.className}-animation, none), c3r-time 3600s linear infinite`,
+ );
+ expect(style.getPropertyValue("animation-timeline")).toBe(
+ "auto, scroll(root), auto",
+ );
+ group.tween = spin;
+ expect(style.getPropertyValue("animation-timeline")).toBe("");
+
+ const container = new Container();
+ container.camera.tween = walk;
+ expect(cssText()).toContain("animation-timeline: scroll(root)");
+ container.camera.tween = null;
+
+ expect(() => new Timeline({ scroll: true, paused: true })).toThrow(
+ RangeError,
+ );
+ expect(() => new Timeline({ scroll: true, hover: true })).toThrow(
+ RangeError,
+ );
+ expect(() => (scroll.paused = true)).toThrow(RangeError);
+ for (const options of [{ loop: true }, { delay: 1 }])
+ expect(
+ () =>
+ new Tween({
+ keyframes: [Transform.rotateY(turn)],
+ timeline: scroll,
+ ...options,
+ }),
+ ).toThrow(RangeError);
+ });
+
it("plays keyframes in sequence, holding what they don't list", () => {
using sequence = new Tween({
from: Filter.opacity(0.5),
@@ -1060,7 +1113,9 @@ describe("Tween", () => {
using hover = new Tween({ keyframes: [Transform.scale(2)], hover: true });
expect(() => (camera.tween = [move, hover])).toThrow(RangeError);
- expect(cssText()).not.toContain(`.${hover.className}, .c3r-view`);
+ expect(cssText()).not.toContain(
+ `.${hover.className}, .c3r-view, .c3r-camera-follower`,
+ );
expect(camera.tween).toEqual([move, grow]);
for (const keyframes of [
[Transform.scale(0)],
@@ -1170,6 +1225,43 @@ describe("Tween", () => {
});
});
+describe("fog", () => {
+ it("rejects an invalid color or length", () => {
+ const container = new Container();
+ expect(() => (container.fog = { color: [0, 0, 2], length: 1 })).toThrow(
+ RangeError,
+ );
+ expect(() => (container.fog = { color: [0, 0, 0], length: 0 })).toThrow(
+ RangeError,
+ );
+ expect(container.fog).toBeNull();
+ });
+
+ it("adds a fog layer to the polygons of a fogged material", async () => {
+ const container = new Container();
+ container.fog = { color: [0, 0, 1], length: 100 };
+ const group = new Group();
+ group.material = new Material();
+ group.material.fog = true;
+ container.root.addChild(group);
+ const polygon = group.addPolygon([
+ vertex(0, 0, 0),
+ vertex(1, 0, 0),
+ vertex(0, 1, 0),
+ ]);
+ await container.bake();
+ expect(
+ polygon.contentElement.querySelector(".c3r-polygon-fog"),
+ ).not.toBeNull();
+ expect(container.domElement.style.getPropertyValue("--c3r-fog-color")).toBe(
+ "0 0 255",
+ );
+ group.material.fog = false;
+ await container.bake();
+ expect(polygon.contentElement.querySelector(".c3r-polygon-fog")).toBeNull();
+ });
+});
+
describe("server-side rendering", () => {
it("exports the stylesheet for static html", () => {
expect(cssText()).toContain(".c3r-polygon");
@@ -1661,6 +1753,11 @@ describe("shadows", () => {
container.lights = { point: { position: [0, 100, 0], intensity: 1 } };
group.tween = swing({ hover: true });
expect(() => container.bake(cast)).toThrow("own hover");
+ group.tween = new Tween({
+ keyframes: [Transform.translate([10, 0, 0])],
+ timeline: new Timeline({ scroll: true }),
+ });
+ expect(() => container.bake(cast)).toThrow("scroll timeline");
});
it("transitions with a caster that moves on hover", async () => {
diff --git a/packages/c3r/test/fog.browser.test.ts b/packages/c3r/test/fog.browser.test.ts
new file mode 100644
index 0000000..5f14477
--- /dev/null
+++ b/packages/c3r/test/fog.browser.test.ts
@@ -0,0 +1,64 @@
+import { expect, it } from "vitest";
+import {
+ Container,
+ Group,
+ Material,
+ Timeline,
+ Transform,
+ Tween,
+ type Vertex,
+} from "c3r";
+
+const SQUARE: Vertex[] = [
+ [-50, -50],
+ [50, -50],
+ [50, 50],
+ [-50, 50],
+].map(([x, y]) => ({ position: [x, y, 0], uv: [0, 0] }));
+
+it("fogs a material by its depth from the eye, following the camera's tween", async () => {
+ const page = document.createElement("div");
+ page.style.height = "300vh";
+ document.body.append(page);
+ const container = new Container();
+ document.body.append(container.domElement);
+ container.fog = { color: [0, 0, 1], length: 1000 };
+ container.camera.transform = Transform.translate([0, 0, 400]);
+ container.camera.tween = new Tween({
+ keyframes: [Transform.translate([0, 0, -100])],
+ timeline: new Timeline({ scroll: true }),
+ });
+ // Scaled, the depth must stay in world units
+ const group = new Group();
+ group.transform = [Transform.translate([0, 0, -100]), Transform.scale(2)];
+ group.material = new Material();
+ group.material.fog = true;
+ container.root.addChild(group);
+ const square = group.addPolygon(SQUARE);
+ await container.bake();
+ const fog = square.contentElement.querySelector(".c3r-polygon-fog")!;
+ const depth = () =>
+ parseFloat(getComputedStyle(fog).getPropertyValue("--c3r-fog-center"));
+ const alpha = () =>
+ parseFloat(
+ getComputedStyle(fog).backgroundImage.match(
+ /rgba\([^)]*,\s*([\d.]+)\)/,
+ )![1],
+ );
+
+ expect(depth()).toBeCloseTo(500, 1);
+ expect(alpha()).toBeCloseTo(1 - Math.exp(-0.5), 2);
+
+ scrollTo(0, (document.documentElement.scrollHeight - innerHeight) / 2);
+ await new Promise(requestAnimationFrame);
+ await new Promise(requestAnimationFrame);
+ expect(depth()).toBeCloseTo(450, 0);
+
+ group.material.fog = false;
+ await container.bake();
+ expect(square.contentElement.querySelector(".c3r-polygon-fog")).toBeNull();
+
+ scrollTo(0, 0);
+ container.domElement.remove();
+ page.remove();
+});
diff --git a/packages/c3r/test/timeline.browser.test.ts b/packages/c3r/test/timeline.browser.test.ts
index beaf9f1..d6b5e7b 100644
--- a/packages/c3r/test/timeline.browser.test.ts
+++ b/packages/c3r/test/timeline.browser.test.ts
@@ -193,6 +193,40 @@ it("keeps a shadow in step when its receiver moves in the scene", async () => {
container.domElement.remove();
});
+it("moves a group and the camera with the page's scroll", async () => {
+ const page = document.createElement("div");
+ page.style.height = "300vh";
+ document.body.append(page);
+ const container = new Container();
+ document.body.append(container.domElement);
+ const scroll = new Timeline({ scroll: true });
+ const move = (step: Transform) =>
+ new Tween({ keyframes: [step], timeline: scroll });
+ const group = new Group();
+ container.root.addChild(group);
+ const slide = move(Transform.translate([100, 0, 0]));
+ group.tween = slide;
+ const walk = move(Transform.translate([0, 0, -100]));
+ container.camera.tween = walk;
+ const view = container.domElement.querySelector(".c3r-view")!;
+ const at = (element: Element, tween: Tween, axis: string) =>
+ parseFloat(
+ getComputedStyle(element).getPropertyValue(
+ `--${tween.className}-translate3d-${axis}`,
+ ),
+ );
+
+ scrollTo(0, (document.documentElement.scrollHeight - innerHeight) / 2);
+ await new Promise(requestAnimationFrame);
+ await new Promise(requestAnimationFrame);
+ expect(at(group.domElement, slide, "x")).toBeCloseTo(50, 0);
+ expect(at(view, walk, "z")).toBeCloseTo(-50, 0);
+
+ scrollTo(0, 0);
+ container.domElement.remove();
+ page.remove();
+});
+
it("brings a container baked before it was shown in step with its timeline", async () => {
const motion = new Timeline();
const lit = () => {