Two lamps
demo-kit/ is what simulates the device for the demo on the start page. The device itself does not need it.
demo-kit/ is what simulates the device for the demo on the start page. The device itself does not need it.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Lamps</title>
<style>
:root {
--bg: #17110e;
--cream: #f6eadb;
--soft: rgba(246, 234, 219, .66);
--faint: rgba(246, 234, 219, .52);
--line: rgba(246, 234, 219, .1);
--card: rgba(255, 236, 214, .045);
--pick: #ffb45e;
--serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, "Noto Serif", serif;
--sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
* { box-sizing: border-box; }
html, body { min-height: 100%; }
body {
margin: 0; color: var(--cream); font: 14px/1.45 var(--sans); overflow-x: hidden;
-webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: transparent;
-webkit-text-size-adjust: 100%; text-size-adjust: 100%;
background-color: var(--bg);
background-image: radial-gradient(130% 62% at 50% 0%, #2b1c14 0%, #17110e 58%, #100c0a 100%);
background-repeat: no-repeat; background-size: 100% 100vh;
}
main {
max-width: 520px; margin: 0 auto; min-height: 100vh; display: flex; flex-direction: column;
padding: calc(14px + env(safe-area-inset-top)) 0 calc(18px + env(safe-area-inset-bottom));
}
.pad { padding-left: calc(20px + env(safe-area-inset-left)); padding-right: calc(20px + env(safe-area-inset-right)); }
button { font: inherit; color: inherit; background: none; border: 0; padding: 0; margin: 0; cursor: pointer; -webkit-appearance: none; appearance: none; }
button:focus-visible { outline: 2px solid var(--cream); outline-offset: 3px; }
.caps { font-size: 10px; letter-spacing: .2em; text-transform: uppercase; color: var(--faint); }
/* ---------- the two names ---------- */
header { text-align: center; }
h1 { margin: 3px 0 0; font: italic 400 25px/1.15 var(--serif); letter-spacing: .01em; overflow-wrap: anywhere; }
h1 i { font-style: normal; font-size: 17px; color: var(--faint); margin: 0 .3em; }
/* ---------- the evening room: two lamps and the way between them ---------- */
.scene { position: relative; height: clamp(250px, 36vh, 300px); margin-top: 2px; flex: none; }
/* The canvas reaches below the scene, so that the light of the lamps fades out instead of ending at an edge. */
#room { position: absolute; left: 0; top: 0; width: 100%; height: calc(100% + 90px); display: block; pointer-events: none;
-webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 26px, #000 calc(100% - 90px), transparent 100%);
mask-image: linear-gradient(to bottom, transparent 0, #000 26px, #000 calc(100% - 90px), transparent 100%); }
.apart { position: absolute; left: 50%; top: 60px; transform: translateX(-50%); text-align: center; pointer-events: none; white-space: nowrap; }
.apart .km { font: 400 31px/1 var(--serif); letter-spacing: .01em; font-variant-numeric: lining-nums; }
.apart .km small { font: italic 400 15px/1 var(--serif); color: var(--soft); margin-left: 5px; }
.apart .caps { display: block; margin-top: 7px; }
.who { position: absolute; bottom: 0; width: 44%; text-align: center; pointer-events: none; }
.who.here { left: 0; }
.who.other { right: 0; }
.who b { display: block; font: italic 400 18px/1.2 var(--serif); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.who .caps { display: block; margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.who .reach { display: inline-flex; align-items: center; gap: 6px; margin-top: 4px; font-size: 11.5px; color: var(--soft); white-space: nowrap; }
.who .reach::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: currentColor; opacity: .5; }
.who .reach.yes { color: #cfe6b4; }
.who .reach.yes::before { opacity: 1; box-shadow: 0 0 8px currentColor; }
.who .reach.no { color: #f0a995; }
.touch { position: absolute; left: 22%; bottom: 60px; width: 104px; height: 124px; transform: translateX(-50%); border-radius: 50%; }
/* ---------- sending ---------- */
.send { margin-top: 14px; position: relative; }
.card { border: 1px solid var(--line); background: var(--card); border-radius: 24px; padding: 15px 16px 16px; }
.swatches { display: flex; justify-content: space-between; align-items: center; }
.swatch { position: relative; width: 44px; height: 44px; border-radius: 50%; flex: none; }
.swatch::before { content: ""; position: absolute; inset: 9px; border-radius: 50%; background: var(--c);
box-shadow: 0 0 14px -2px var(--c); transition: transform .35s cubic-bezier(.2, .8, .3, 1.2), box-shadow .35s; }
.swatch::after { content: ""; position: absolute; inset: 2px; border-radius: 50%; border: 1.5px solid var(--c); opacity: 0;
transform: scale(.8); transition: opacity .3s, transform .35s cubic-bezier(.2, .8, .3, 1.2); }
.swatch[aria-checked="true"]::before { transform: scale(1.12); box-shadow: 0 0 22px 0 var(--c); }
.swatch[aria-checked="true"]::after { opacity: .9; transform: scale(1); }
.patterns { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-top: 11px; }
.pattern { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 9px 0 8px; border-radius: 14px; min-width: 0;
border: 1px solid transparent; color: var(--soft); font-size: 12px; transition: color .3s, background .3s, border-color .3s; }
.pattern svg { width: 36px; height: 14px; display: block; overflow: visible; }
.pattern path { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
.pattern[aria-checked="true"] { color: var(--pick); background: rgba(255, 236, 214, .06); border-color: var(--line); }
.go { display: block; width: 100%; height: 54px; margin-top: 13px; border-radius: 27px; color: #2a1a10;
font: italic 400 19px/1 var(--serif); letter-spacing: .01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding: 0 18px;
background: var(--pick); box-shadow: 0 10px 34px -12px var(--pick), inset 0 1px 0 rgba(255, 255, 255, .45), inset 0 -10px 18px -10px rgba(60, 20, 0, .3);
transition: background .5s, box-shadow .5s, opacity .4s, transform .15s; }
.go:active { transform: scale(.985); }
.go[disabled] { opacity: .72; cursor: default; }
.note { min-height: 19px; margin: 10px 2px 0; text-align: center; font-size: 12.5px; color: var(--soft); transition: opacity .5s; }
.note:empty { opacity: 0; }
/* ---------- the quiet history ---------- */
.quiet { margin-top: 16px; flex: 1; }
.quiet p { margin: 0; font: italic 400 15.5px/1.5 var(--serif); color: var(--soft); text-align: center; }
.quiet p em { font-style: inherit; color: var(--cream); }
ul { list-style: none; margin: 12px 0 0; padding: 0; border-top: 1px solid var(--line); }
li { display: flex; align-items: center; gap: 10px; padding: 8px 2px; border-bottom: 1px solid var(--line); font-size: 12.5px; color: var(--soft); }
li time { width: 40px; flex: none; font-variant-numeric: tabular-nums; color: var(--faint); }
li .dot { width: 9px; height: 9px; border-radius: 50%; flex: none; background: var(--c); box-shadow: 0 0 9px -1px var(--c); }
li.sent .dot { background: transparent; border: 1.5px solid var(--c); box-shadow: none; }
li .what { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
li .how { flex: none; color: var(--faint); }
li.lost .how { color: #f0a995; }
li.new { animation: arrive 1.2s ease 1; }
@keyframes arrive { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
footer { margin-top: 14px; text-align: center; font-size: 11px; color: var(--faint); }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; }
}
</style>
</head>
<body>
<main>
<header class="pad">
<div class="caps" id="device">Two lamps</div>
<h1 id="names"> </h1>
</header>
<section class="scene" aria-label="The two lamps">
<canvas id="room" aria-hidden="true"></canvas>
<div class="apart" id="apart" hidden>
<div class="km"><span id="km"></span><small>km</small></div>
<span class="caps">apart</span>
</div>
<div class="who here">
<b id="hereLabel"> </b>
<span class="caps" id="herePlace"> </span>
<span class="reach" id="hereNote">this lamp</span>
</div>
<div class="who other">
<b id="otherLabel"> </b>
<span class="caps" id="otherPlace"> </span>
<span class="reach" id="reach" role="status">looking</span>
</div>
<button class="touch" id="touch" type="button" aria-label="Touch this lamp to send a glow"></button>
</section>
<section class="send pad">
<div class="card">
<div class="swatches" id="swatches" role="radiogroup" aria-label="Colour"></div>
<div class="patterns" id="patterns" role="radiogroup" aria-label="Pattern"></div>
<button class="go" id="go" type="button">Send a glow</button>
</div>
<div class="note" id="note" role="status"></div>
</section>
<section class="quiet pad" aria-label="Today">
<p id="summary"> </p>
<ul id="entries"></ul>
</section>
<footer class="pad" id="foot"></footer>
</main>
<script>
(function () {
'use strict';
const $ = (id) => document.getElementById(id);
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
const bridge = window.connectivitizer || null; // there only in the app; a browser opened on the lamp asks again and again instead
const COLOURS = ['#ffb45e', '#ff8fa3', '#ff7d5c', '#b9a0ff', '#8fb8ff', '#86e0c2'];
const PATTERNS = {
glow: ['Glow', 'M2 7 H34'],
pulse: ['Pulse', 'M2 11 C7 11 7 3 12 3 S17 11 23 11 S28 3 34 3'],
heartbeat: ['Heartbeat', 'M2 8 H10 L13 2 L16 12 L19 5 L21 8 H34'],
wave: ['Wave', 'M2 10 C12 10 12 3 18 3 S24 10 34 10'],
};
let state = null;
let picked = { color: COLOURS[0], pattern: 'glow' };
let pickedByHand = false;
const glow = { here: null, other: null }; // what each lamp shows: { rgb, pattern, seconds, start, end } in this page's clock
const bloom = { here: 0, other: 0 }; // a short flare when light leaves or arrives
const travels = []; // light on its way: { to, rgb, p, fade, id, delivered, arrived, seeds }
const seen = new Set(); // ids of history entries this page has already shown
const delivered = new Map();
const listed = new Set(); // ids that have been in the list below, so that only a new line fades in
let known = false; // the history has been read once: what comes after it is new
let noteTimer = 0;
// ---------- small helpers ----------
function rgbOf(hex) {
return /^#[0-9a-f]{6}$/i.test(hex || '') ? [parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16)] : [255, 180, 94];
}
function rgba(c, a) { return 'rgba(' + Math.round(c[0]) + ',' + Math.round(c[1]) + ',' + Math.round(c[2]) + ',' + Math.max(0, Math.min(1, a)).toFixed(3) + ')'; }
function clock(t) { return new Date(t * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); }
function text(id, value) { const el = $(id); if (el.textContent !== value) el.textContent = value; }
function note(value, seconds) {
clearTimeout(noteTimer);
text('note', value);
if (seconds) noteTimer = setTimeout(() => text('note', ''), seconds * 1000);
}
// How bright a glow is, 0 to 1 (the same formulas as in the lamp's program).
function brightness(pattern, seconds, total) {
if (seconds < 0 || seconds >= total) return 0;
const fade = Math.max(0, Math.min(1, seconds / 1.5, (total - seconds) / 3));
if (reduced) return fade * .9;
let shape;
if (pattern === 'pulse') shape = .25 + .75 * (.5 - .5 * Math.cos(2 * Math.PI * seconds / 1.6));
else if (pattern === 'heartbeat') {
const phase = seconds % 1.4;
shape = .35 + .65 * Math.max(Math.exp(-Math.pow((phase - .12) / .07, 2)), .75 * Math.exp(-Math.pow((phase - .42) / .09, 2)));
} else if (pattern === 'wave') shape = .35 + .65 * (.5 - .5 * Math.cos(2 * Math.PI * seconds / 5));
else shape = .92 + .08 * Math.sin(2 * Math.PI * seconds / 6);
return fade * shape;
}
// ---------- the controls ----------
function buildControls(own) {
const colours = [own].concat(COLOURS.filter((c) => c !== own)).slice(0, 6);
$('swatches').textContent = '';
colours.forEach((colour) => {
const b = document.createElement('button');
b.type = 'button'; b.className = 'swatch'; b.style.setProperty('--c', colour);
b.setAttribute('role', 'radio'); b.setAttribute('aria-label', 'Colour ' + colour); b.dataset.colour = colour;
b.onclick = () => { pickedByHand = true; picked.color = colour; renderPicked(); };
$('swatches').appendChild(b);
});
$('patterns').textContent = '';
Object.keys(PATTERNS).forEach((key) => {
const b = document.createElement('button');
b.type = 'button'; b.className = 'pattern'; b.setAttribute('role', 'radio'); b.dataset.pattern = key;
b.innerHTML = '<svg viewBox="0 0 36 14" aria-hidden="true"><path d="' + PATTERNS[key][1] + '"/></svg><span>' + PATTERNS[key][0] + '</span>';
b.onclick = () => { picked.pattern = key; renderPicked(); };
$('patterns').appendChild(b);
});
renderPicked();
}
function renderPicked() {
document.documentElement.style.setProperty('--pick', picked.color);
document.querySelectorAll('.swatch').forEach((b) => b.setAttribute('aria-checked', String(b.dataset.colour === picked.color)));
document.querySelectorAll('.pattern').forEach((b) => b.setAttribute('aria-checked', String(b.dataset.pattern === picked.pattern)));
}
function sending() { return travels.some((t) => t.to === 'other' && !t.arrived && t.delivered !== false); }
function renderButton() {
const other = state ? state.other.label : '';
$('go').disabled = !state || sending();
text('go', sending() ? 'On its way' : other ? 'Send a glow to ' + other : 'Send a glow');
}
// ---------- what the lamp says ----------
function local(g) {
if (!g) return null;
const now = performance.now();
return { rgb: rgbOf(g.color), pattern: g.pattern, seconds: g.seconds, start: now - (g.seconds - g.remainingSeconds) * 1000, end: now + g.remainingSeconds * 1000 };
}
function applyState(next) {
const first = !state;
state = next;
glow.here = local(next.here.glow);
glow.other = local(next.other.glow);
text('device', next.here.name);
$('names').innerHTML = '';
$('names').append(next.here.label, Object.assign(document.createElement('i'), { textContent: '&' }), next.other.label);
text('hereLabel', next.here.label); text('herePlace', next.here.place || next.here.name);
text('otherLabel', next.other.label); text('otherPlace', next.other.place || next.other.name);
if (typeof next.distanceKm === 'number') { text('km', next.distanceKm.toLocaleString()); $('apart').hidden = false; }
const reach = $('reach');
reach.className = 'reach' + (next.other.reachable === true ? ' yes' : next.other.reachable === false ? ' no' : '');
text('reach', next.link === 'none' ? 'no link' : next.other.reachable === true ? 'in reach' : next.other.reachable === false ? 'out of reach' : 'looking');
if (first) {
if (!pickedByHand) picked.color = next.here.color;
buildControls(next.here.color);
}
renderButton();
}
function renderHistory(history) {
const today = history.today, other = state ? state.other.label : 'the other lamp';
const times = (n) => n === 1 ? 'once' : n + ' times';
const p = $('summary');
p.textContent = '';
const add = (value, strong) => p.append(strong ? Object.assign(document.createElement('em'), { textContent: value }) : value);
if (today.received > 0) { add('This lamp glowed '); add(times(today.received), true); add(' today, last at '); add(clock(today.lastReceived), true); add('.'); }
else add('This lamp has not glowed yet today.');
if (today.sent > 0) { add(' You sent '); add(today.sent === 1 ? 'one glow' : today.sent + ' glows', true); add('.'); }
const list = $('entries');
list.textContent = '';
history.entries.slice(0, 3).forEach((entry) => {
const li = document.createElement('li');
const got = entry.direction === 'received';
li.className = (got ? 'got' : 'sent') + (entry.delivered === false ? ' lost' : '') + (known && !listed.has(entry.id) ? ' new' : '');
li.style.setProperty('--c', entry.color);
const time = document.createElement('time'); time.textContent = clock(entry.t);
const dot = document.createElement('span'); dot.className = 'dot';
const what = document.createElement('span'); what.className = 'what';
what.textContent = (got ? 'from ' : 'to ') + other + ', ' + (PATTERNS[entry.pattern] ? PATTERNS[entry.pattern][0].toLowerCase() : entry.pattern);
const how = document.createElement('span'); how.className = 'how';
how.textContent = entry.delivered === false ? 'did not arrive' : entry.delivered === null ? 'on its way' : entry.via === 'touch' ? 'by touch' : 'by phone';
li.append(time, dot, what, how);
list.appendChild(li);
});
history.entries.forEach((entry) => {
// Without the socket this is where the page learns that a glow has arrived, or has not.
if (delivered.get(entry.id) === null && entry.delivered !== null) onDelivered(entry, null);
listed.add(entry.id); seen.add(entry.id); delivered.set(entry.id, entry.delivered);
});
known = true;
}
// ---------- light on its way ----------
function travel(to, entry) {
if (travels.some((t) => t.id === entry.id)) return;
const seeds = [];
for (let i = 0; i < 34; i++) seeds.push({ d: Math.random() * .46, a: (Math.random() - .5) * 34, f: .7 + Math.random() * 1.6, ph: Math.random() * 6.3, s: .3 + Math.random() * .9 });
travels.push({ to: to, rgb: rgbOf(entry.color), p: 0, fade: 1, id: entry.id, delivered: to === 'here' ? true : entry.delivered, arrived: false, seeds: seeds });
bloom[to === 'here' ? 'other' : 'here'] = 1;
renderButton();
}
function onGlow(entry) {
seen.add(entry.id); delivered.set(entry.id, entry.delivered);
travel(entry.direction === 'received' ? 'here' : 'other', entry);
if (entry.direction === 'received' && state) note('A glow from ' + state.other.label + '.', 6);
}
function onDelivered(entry, error) {
delivered.set(entry.id, entry.delivered);
const t = travels.find((x) => x.id === entry.id);
if (t) t.delivered = entry.delivered;
if (entry.delivered) {
const path = state && state.other.path;
const say = () => note(path === 'direct' ? 'It arrived. The lamps reached each other directly.' : path === 'relayed' ? 'It arrived. The lamps reached each other through the relay.' : 'It arrived.', 8);
// The lamp has the answer before the light on the page is there: the words wait for the light.
if (t && !t.arrived) t.then = say; else say();
} else {
note(error === 'NO_LINK' ? 'This lamp runs on its own for now, so the glow had nowhere to go.' : 'It did not arrive. The other lamp could not be reached.', 10);
}
renderButton();
}
function send() {
if (!state || sending()) return;
$('go').disabled = true;
note('');
fetch('/glow', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ color: picked.color, pattern: picked.pattern }) })
.then((r) => r.ok ? r.json() : Promise.reject(new Error('status ' + r.status)))
.then((answer) => { onGlow(answer.entry); refreshHistory(); })
.catch(() => { note('The lamp did not answer.', 8); renderButton(); });
}
$('go').onclick = send;
$('touch').onclick = send;
// ---------- talking to the lamp ----------
function getJson(path) { return fetch(path).then((r) => r.ok ? r.json() : Promise.reject(new Error('status ' + r.status))); }
function refreshHistory() { return getJson('/history').then(renderHistory, () => {}); }
let live = false;
function listen() {
if (!bridge || typeof bridge.webSocket !== 'function') return;
let socket;
try { socket = bridge.webSocket('/events'); } catch (e) { return; }
socket.onopen = () => { live = true; };
socket.onmessage = (event) => {
let message;
try { message = JSON.parse(event.data); } catch (e) { return; }
if (message.state) applyState(message.state);
if (message.type === 'glow' && message.entry) onGlow(message.entry);
if (message.type === 'delivered' && message.entry) onDelivered(message.entry, message.error);
if (message.type !== 'state') refreshHistory();
};
socket.onclose = () => { live = false; setTimeout(listen, 4000); };
}
// Without the socket: ask for the state and the history, and find what is new in them.
function poll() {
if (live) return;
Promise.all([getJson('/state'), getJson('/history')]).then((answers) => {
applyState(answers[0]);
if (known) {
answers[1].entries.slice().reverse().forEach((entry) => {
if (!seen.has(entry.id)) onGlow(entry);
});
}
renderHistory(answers[1]);
}, () => { if (!state) note('The lamp does not answer.'); });
}
poll();
setInterval(poll, 1500);
listen();
function renderFoot() {
const device = bridge && bridge.device;
if (!device) { text('foot', bridge ? '' : 'Opened straight from the lamp.'); return; }
text('foot', 'This phone reaches the lamp ' + (device.path === 'direct' ? 'directly' : 'through the relay') + (device.endToEndEncrypted ? ', end-to-end encrypted.' : '.'));
}
renderFoot();
if (bridge && bridge.ready && typeof bridge.ready.then === 'function') bridge.ready.then(renderFoot, () => {});
// ---------- the room ----------
const canvas = $('room'), ctx = canvas.getContext('2d');
const BELOW = 90; // how far the canvas reaches below the scene (see the style of #room)
let W = 0, H = 0, ratio = 1;
function size() {
const box = canvas.getBoundingClientRect();
ratio = Math.min(window.devicePixelRatio || 1, 2.5);
W = box.width; H = box.height;
canvas.width = Math.round(W * ratio); canvas.height = Math.round(H * ratio);
}
size();
window.addEventListener('resize', size);
const sprites = new Map(); // one soft dot per colour, drawn once
function sprite(rgb) {
const key = rgb.join(',');
let s = sprites.get(key);
if (!s) {
s = document.createElement('canvas'); s.width = s.height = 64;
const c = s.getContext('2d'), g = c.createRadialGradient(32, 32, 0, 32, 32, 32);
g.addColorStop(0, rgba(rgb.map((v) => v + (255 - v) * .6), 1)); g.addColorStop(.22, rgba(rgb, .6)); g.addColorStop(.55, rgba(rgb, .14)); g.addColorStop(1, rgba(rgb, 0));
c.fillStyle = g; c.fillRect(0, 0, 64, 64);
sprites.set(key, s);
}
return s;
}
const shown = { here: { rgb: [255, 180, 94], level: 0 }, other: { rgb: [143, 184, 255], level: 0 } };
const motes = [];
for (let i = 0; i < 16; i++) motes.push({ side: i % 2 ? 'here' : 'other', x: (Math.random() - .5) * 150, y: Math.random(), v: .012 + Math.random() * .02, r: .6 + Math.random() * 1.1, ph: Math.random() * 6.3 });
function geometry() {
const base = H - BELOW - 74, r = Math.min(31, W * .082);
const cy = base - 12 - r * .93;
return { base: base, r: r, cy: cy, here: W * .22, other: W * .78, apex: 32 };
}
function onArc(g, from, to, u) {
const x0 = g[from], x2 = g[to], y0 = g.cy - g.r * .9, x1 = (x0 + x2) / 2, y1 = 2 * g.apex - y0, v = 1 - u;
return [v * v * x0 + 2 * v * u * x1 + u * u * x2, v * v * y0 + 2 * v * u * y1 + u * u * y0];
}
function want(side, now) {
const own = state ? rgbOf(state[side].color) : shown[side].rgb;
const arriving = travels.some((t) => t.to === side && !t.arrived);
const g = glow[side];
let level = reduced ? .14 : .14 + .03 * Math.sin(now / 1900 + (side === 'here' ? 0 : 2));
let rgb = own;
if (side === 'other' && state && state.other.reachable === false) level *= .35;
if (g && now < g.end && !arriving) { level = Math.max(level, brightness(g.pattern, (now - g.start) / 1000, g.seconds)); rgb = g.rgb; }
return { rgb: rgb, level: Math.min(1.25, level + bloom[side] * .55) };
}
function drawLamp(g, side) {
const x = g[side], s = shown[side], c = s.rgb, l = s.level, r = g.r, cy = g.cy, base = g.base;
ctx.globalCompositeOperation = 'lighter';
// The light on the wall and on the shelf.
let halo = ctx.createRadialGradient(x, cy, 0, x, cy, r * (2.6 + 3.4 * l));
halo.addColorStop(0, rgba(c, .1 + .42 * l)); halo.addColorStop(.35, rgba(c, .04 + .15 * l)); halo.addColorStop(1, rgba(c, 0));
ctx.fillStyle = halo; ctx.fillRect(0, 0, W, H);
ctx.save(); ctx.translate(x, base + 1); ctx.scale(1, .16);
halo = ctx.createRadialGradient(0, 0, 0, 0, 0, 86);
halo.addColorStop(0, rgba(c, .12 + .5 * l)); halo.addColorStop(1, rgba(c, 0));
ctx.fillStyle = halo; ctx.beginPath(); ctx.arc(0, 0, 86, 0, 6.3); ctx.fill(); ctx.restore();
ctx.globalCompositeOperation = 'source-over';
// The shelf.
const shelf = ctx.createLinearGradient(x - 66, 0, x + 66, 0);
shelf.addColorStop(0, 'rgba(246,234,219,0)'); shelf.addColorStop(.5, 'rgba(246,234,219,' + (.2 + .25 * Math.min(1, l)).toFixed(3) + ')'); shelf.addColorStop(1, 'rgba(246,234,219,0)');
ctx.fillStyle = shelf; ctx.fillRect(x - 66, base, 132, 1);
// The foot and the neck.
ctx.fillStyle = '#2c211b';
ctx.beginPath(); ctx.moveTo(x - 17, base); ctx.lineTo(x - 11, base - 8); ctx.quadraticCurveTo(x, base - 11, x + 11, base - 8); ctx.lineTo(x + 17, base); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#211813'; ctx.fillRect(x - 6, base - 14, 12, 6);
ctx.fillStyle = rgba(c, .1 + .45 * Math.min(1, l)); ctx.fillRect(x - 10, base - 9, 20, 1);
// The globe: dark glass, then the light in it.
ctx.beginPath(); ctx.arc(x, cy, r, 0, 6.3);
ctx.fillStyle = '#31251f'; ctx.fill();
const inner = ctx.createRadialGradient(x, cy + r * .12, 0, x, cy, r);
const k = Math.min(1, l);
inner.addColorStop(0, rgba(c.map((v) => v + (255 - v) * k * .8), .25 + .75 * k));
inner.addColorStop(.55, rgba(c, .16 + .74 * k)); inner.addColorStop(1, rgba(c, .1 + .5 * k));
ctx.fillStyle = inner; ctx.fill();
ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(255,244,228,' + (.14 + .2 * k).toFixed(3) + ')'; ctx.stroke();
ctx.beginPath(); ctx.arc(x, cy, r * .72, Math.PI * 1.12, Math.PI * 1.42);
ctx.lineWidth = 2; ctx.lineCap = 'round'; ctx.strokeStyle = 'rgba(255,255,255,' + (.12 + .2 * k).toFixed(3) + ')'; ctx.stroke();
}
function drawTravel(g, t, now) {
const from = t.to === 'here' ? 'other' : 'here', dot = sprite(t.rgb);
ctx.globalCompositeOperation = 'lighter';
if (reduced) {
// No movement: the whole way lights up and fades.
ctx.beginPath();
for (let i = 0; i <= 40; i++) { const p = onArc(g, from, t.to, i / 40); if (i) ctx.lineTo(p[0], p[1]); else ctx.moveTo(p[0], p[1]); }
ctx.lineWidth = 2; ctx.strokeStyle = rgba(t.rgb, .7 * t.fade * Math.sin(Math.PI * Math.min(1, t.p / 1.46))); ctx.stroke();
ctx.globalCompositeOperation = 'source-over';
return;
}
t.seeds.forEach((seed) => {
const u = t.p - seed.d;
if (u <= 0 || u >= 1) return;
for (let k = 0; k < 4; k++) {
const uk = u - k * .022;
if (uk <= 0) break;
const e = uk * uk * (3 - 2 * uk);
const p = onArc(g, from, t.to, e), q = onArc(g, from, t.to, Math.min(1, e + .01));
const nx = -(q[1] - p[1]), ny = q[0] - p[0], n = Math.hypot(nx, ny) || 1;
const off = seed.a * Math.sin(Math.PI * e) * Math.sin(now / 1000 * seed.f + seed.ph + e * 3);
const edge = Math.min(1, uk * 9, (1 - uk) * 7);
const sz = (5 + 9 * seed.s) * (1 - k * .2);
ctx.globalAlpha = t.fade * edge * (k ? .5 - k * .12 : 1) * (.45 + .45 * seed.s);
ctx.drawImage(dot, p[0] + nx / n * off - sz / 2, p[1] + ny / n * off - sz / 2, sz, sz);
}
});
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
}
let last = performance.now();
function frame(now) {
const dt = Math.min(reduced ? .3 : .1, Math.max(0, (now - last) / 1000));
last = now;
if (!W || !H) size();
const g = geometry();
// Light on its way: it slows down short of the other lamp until that lamp has answered.
for (let i = travels.length - 1; i >= 0; i--) {
const t = travels[i];
const waits = t.delivered === null ? Math.max(.03, Math.min(1, (.78 - t.p) / .3)) : 1;
if (t.delivered === false) t.fade -= dt / .9;
else t.p += dt / (t.to === 'here' ? 2.8 : 3.4) * waits;
if (!t.arrived && t.p >= 1.04) { t.arrived = true; bloom[t.to] = 1; if (t.then) t.then(); renderButton(); }
if (t.p >= 1.46 || t.fade <= 0) { travels.splice(i, 1); renderButton(); }
}
['here', 'other'].forEach((side) => {
bloom[side] = Math.max(0, bloom[side] - dt / 1.5);
const w = want(side, now), s = shown[side], k = reduced ? 1 : 1 - Math.exp(-dt * 7);
s.level += (w.level - s.level) * k;
s.rgb = s.rgb.map((v, i) => v + (w.rgb[i] - v) * (reduced ? 1 : 1 - Math.exp(-dt * 4)));
});
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
ctx.clearRect(0, 0, W, H);
// The way between the lamps, always faintly there.
ctx.beginPath();
for (let i = 0; i <= 48; i++) { const p = onArc(g, 'here', 'other', i / 48); if (i) ctx.lineTo(p[0], p[1]); else ctx.moveTo(p[0], p[1]); }
ctx.setLineDash([1, 7]); ctx.lineCap = 'round'; ctx.lineWidth = 1.4; ctx.strokeStyle = 'rgba(246,234,219,.2)'; ctx.stroke(); ctx.setLineDash([]);
drawLamp(g, 'here'); drawLamp(g, 'other');
// Dust in the light of each lamp.
if (!reduced) {
ctx.globalCompositeOperation = 'lighter';
motes.forEach((m) => {
m.y -= m.v * dt; if (m.y < 0) m.y += 1;
const s = shown[m.side], x = g[m.side] + m.x + Math.sin(now / 2600 + m.ph) * 8, y = g.base - 6 - m.y * (g.base - 30);
const near = Math.max(0, 1 - Math.hypot(x - g[m.side], y - g.cy) / (g.r * (2.2 + 2.6 * s.level)));
ctx.fillStyle = rgba(s.rgb, near * (.25 + .5 * Math.min(1, s.level)) * Math.sin(Math.PI * m.y));
ctx.beginPath(); ctx.arc(x, y, m.r, 0, 6.3); ctx.fill();
});
ctx.globalCompositeOperation = 'source-over';
}
travels.forEach((t) => drawTravel(g, t, now));
}
if (reduced) { setInterval(() => frame(performance.now()), 250); frame(performance.now()); }
else (function loop(now) { frame(now || performance.now()); requestAnimationFrame(loop); })();
})();
</script>
</body>
</html>