Add the film gallery generator and brand logo

scripts/film-samples.mjs renders the sample frames and B&W filter strip for the
film-looks page, and logo.png is the asset the app, bundles and site deploy all
expect at the repo root.
This commit is contained in:
2026-11-29 01:15:52 +00:00
parent 335cb3c757
commit d42727618e
2 changed files with 672 additions and 0 deletions
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 975 KiB

+672
View File
@@ -0,0 +1,672 @@
#!/usr/bin/env node
/**
* Render film-look sample frames and build the film gallery page.
*
* Every frame is produced by the app's own WebGL renderer with the preset's real
* edits, so the gallery shows what Luminary actually does rather than a mock-up.
* Black and white looks are documented with the contrast filter they carry, and
* one stock is rendered through every colour filter the editor offers.
*
* node scripts/film-samples.mjs --photo sample.jpg
* node scripts/film-samples.mjs --photo sample.jpg --out /tmp/film --per-category 2
*
* Output stays outside the checkout (default ~/.cache/luminary-film-gallery):
*
* <out>/original.jpg the untouched frame
* <out>/<preset-id>.jpg one frame per sampled stock
* <out>/<preset-id>--<filter>.jpg the black and white filter demo
* <out>/film.html the gallery page
* <out>/film-looks.json the catalogue data
*
* Copy the frames to the site's assets/film/ and film.html to the site root.
* Needs Chrome/Chromium with WebGL2 (SwiftShader is used when there is no GPU).
*/
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
import { createServer } from 'vite';
import { FILM_PRESETS } from '../src/lib/presets.ts';
// Filled from Vite's ssrLoadModule below: edits.ts imports './curves' without an
// extension, which Node's own resolver cannot follow from a plain import here.
let BW_FILTERS = [];
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const DIR = path.join(ROOT, '.film-samples');
const PAGE = path.join(DIR, 'index.html');
const PORT = 5201;
const RENDER_WIDTH = 1000;
const RENDER_HEIGHT = 667;
const JPEG_QUALITY = 84;
/** The stock used to show what each B&W contrast filter does. */
const BW_DEMO_STOCK = 'film-tri-x-400';
const FILTER_HINTS = {
none: 'No filter: the stock as it renders by default',
yellow: 'Mild: slightly darker sky, natural skin',
orange: 'Stronger: deeper sky, warmer skin separation',
red: 'Dramatic: near-black sky, bright skin and foliage highlights',
green: 'Lifts foliage, darkens lips and skin blemishes',
blue: 'Lightens haze and shadow detail, darkens skin',
};
const CATEGORY_ORDER = [
'Colour Negative',
'Colour Slide',
'Black & White',
'Cinema',
'Instant',
'Redscale',
'Experimental',
];
const CATEGORY_HINTS = {
'Colour Negative':
'C-41 print films: warm skin, open shadows and the colour people mean by "film".',
'Colour Slide':
'E-6 and K-14 reversal films: dense blacks, saturated colour and very little latitude.',
'Black & White':
'Panchromatic stocks and chromogenic B&W, each with its own grain, contrast and colour filter.',
Cinema: 'Motion-picture negatives: flat midtones and soft shoulders, built to grade.',
Instant: 'Integral and peel-apart instant film: lifted blacks, soft colour, gentle contrast.',
Redscale: 'Film exposed through its base: amber highlights, red midtones, deep shadows.',
Experimental:
'Cross-process, faded print, infrared and other deliberate departures from a normal negative.',
};
/** Three representative stocks per category: the ones people ask for by name. */
const SAMPLE_PICKS = {
'Colour Negative': ['film-portra-400', 'film-gold-200', 'film-ektar-100'],
'Colour Slide': ['film-velvia-50', 'film-provia-100f', 'film-kodachrome-64'],
'Black & White': ['film-tri-x-400', 'film-tmax-100', 'film-hp5-plus-400'],
Cinema: ['film-cinestill-800t', 'film-vision3-250d', 'film-cinestill-50d'],
Instant: ['film-polaroid-600', 'film-instax-mini', 'film-fp-100c'],
Redscale: ['film-redscale-xr', 'film-redscale-deep', 'film-redscale-gold-200'],
Experimental: ['film-lomochrome-purple', 'film-xpro-cross-process', 'film-aerochrome'],
};
const HELP = `Luminary film gallery generator
Usage: node scripts/film-samples.mjs --photo <file> [options]
--photo <file> source frame (JPEG/PNG) to render every look onto
--out <dir> output directory (default: <cache>/luminary-film-gallery)
--per-category <n> sampled stocks per category (default: 3, max: all picks)
--quality <1-100> JPEG quality for the frames (default: ${JPEG_QUALITY})
--help print this text
Frames come from the app's own renderer in headless Chrome, so WebGL2 must work
there (SwiftShader is fine). ${BW_DEMO_STOCK} is also rendered through every B&W
colour filter. The repository is not modified; the temporary render page is
deleted at the end.
`;
const CHROME_CANDIDATES = [
process.env.CHROME_PATH,
'google-chrome',
'google-chrome-stable',
'chromium',
'chromium-browser',
].filter(Boolean);
function fail(message) {
process.stderr.write(`film-samples: FAILED: ${message}\n`);
process.exit(1);
}
function log(step, message) {
process.stdout.write(`film-samples: ${step.padEnd(9)} ${message}\n`);
}
function parseArgs(argv) {
const options = {
photo: null,
out: path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-film-gallery'),
perCategory: 3,
quality: JPEG_QUALITY,
help: false,
};
const value = (index, flag) => {
const next = argv[index + 1];
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
return next;
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--photo') {
options.photo = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--out') {
options.out = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--per-category') {
options.perCategory = Number(value(i, arg));
i += 1;
} else if (arg === '--quality') {
options.quality = Number(value(i, arg));
i += 1;
} else if (arg === '--help' || arg === '-h') {
options.help = true;
} else {
fail(`unknown option ${arg} (see --help)`);
}
}
if (!Number.isInteger(options.perCategory) || options.perCategory < 1) {
fail('--per-category must be a positive integer');
}
if (!Number.isInteger(options.quality) || options.quality < 1 || options.quality > 100) {
fail('--quality must be 1-100');
}
if (!options.help && !options.photo) fail('--photo is required (see --help)');
if (options.photo && !existsSync(options.photo)) fail(`photo not found: ${options.photo}`);
return options;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function spawnSyncOk(bin) {
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
return new Promise((resolve) => {
probe.on('error', () => resolve(false));
probe.on('exit', (code) => resolve(code === 0));
});
}
async function findChrome() {
for (const candidate of CHROME_CANDIDATES) {
if (candidate.includes(path.sep)) {
if (existsSync(candidate)) return candidate;
continue;
}
if (await spawnSyncOk(candidate)) return candidate;
}
return null;
}
const PAGE_HTML = `<!doctype html>
<meta charset="utf-8" />
<pre id="out">boot</pre>
<script type="module">
import { Renderer } from '/src/gl/renderer.ts';
import { FILM_PRESETS } from '/src/lib/presets.ts';
import { defaultEdits, normalizeEdits } from '/src/lib/edits.ts';
const pre = document.getElementById('out');
try {
const canvas = document.createElement('canvas');
const renderer = new Renderer(canvas);
const blob = await (await fetch('/.film-samples/photo.jpg')).blob();
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
renderer.setImage(bitmap, null);
const size = { width: ${RENDER_WIDTH}, height: ${RENDER_HEIGHT} };
// filter is only used by the B&W strip: it overrides the stock's own filter.
window.renderLook = async (id, filter) => {
const preset = FILM_PRESETS.find((entry) => entry.id === id);
const edits = preset
? normalizeEdits(
filter
? { ...preset.edits, bw: true, bwFilter: filter, bwFilterAmount: 100 }
: preset.edits,
)
: defaultEdits();
renderer.render(edits, size);
return canvas.toDataURL('image/jpeg', ${JPEG_QUALITY} / 100);
};
window.ready = true;
pre.textContent = 'READY';
} catch (error) {
pre.textContent = 'ERROR ' + (error && error.message ? error.message : String(error));
}
</script>
`;
async function drive(chromeBin, url, jobs, outDir, quality) {
const port = 9333;
const child = spawn(
chromeBin,
[
'--headless=new',
'--no-sandbox',
'--disable-gpu-sandbox',
'--use-gl=angle',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
`--remote-debugging-port=${port}`,
`--user-data-dir=${path.join(DIR, 'profile')}`,
'about:blank',
],
{ stdio: 'ignore' },
);
try {
let target = null;
for (let i = 0; i < 120 && !target; i++) {
try {
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
target = (await res.json()).find((t) => t.type === 'page') ?? null;
} catch {
/* devtools not up yet */
}
if (!target) await sleep(250);
}
if (!target) throw new Error('Chrome DevTools endpoint never came up');
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
ws.onopen = resolve;
ws.onerror = () => reject(new Error('DevTools websocket failed'));
});
let nextId = 1;
const pending = new Map();
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
};
const send = (method, params = {}) => {
const id = nextId++;
return new Promise((resolve) => {
pending.set(id, resolve);
ws.send(JSON.stringify({ id, method, params }));
});
};
const evaluate = async (expression, awaitPromise = false) => {
const response = await send('Runtime.evaluate', {
expression,
awaitPromise,
returnByValue: true,
});
if (response.result?.exceptionDetails) {
throw new Error(
response.result.exceptionDetails.exception?.description ??
response.result.exceptionDetails.text,
);
}
return response.result?.result?.value;
};
await send('Page.enable');
await send('Runtime.enable');
await send('Page.navigate', { url });
const deadline = Date.now() + 120000;
let status = '';
while (Date.now() < deadline) {
status = (await evaluate("document.getElementById('out')?.textContent ?? ''")) ?? '';
if (status.startsWith('READY') || status.startsWith('ERROR')) break;
await sleep(400);
}
if (status.startsWith('ERROR')) throw new Error(status.slice(6));
if (!status.startsWith('READY')) throw new Error('the render page never became ready');
const written = [];
for (const job of jobs) {
const dataUrl = await evaluate(
`window.renderLook(${JSON.stringify(job.id)}, ${JSON.stringify(job.filter ?? null)})`,
true,
);
if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/jpeg;base64,')) {
throw new Error(`renderer returned no JPEG for ${job.file}`);
}
const buffer = Buffer.from(dataUrl.slice('data:image/jpeg;base64,'.length), 'base64');
const file = path.join(outDir, job.file);
// Re-encode so the frames carry consistent metadata and no EXIF bloat.
await sharp(buffer).jpeg({ quality, mozjpeg: true }).toFile(file);
log('render', `${job.file} (${(buffer.length / 1024).toFixed(0)} KB)`);
written.push(job.file);
}
ws.close();
return written;
} finally {
child.kill('SIGKILL');
await sleep(400);
}
}
/* ------------------------------------------------------------------ page ---- */
function escapeHtml(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function slug(category) {
return category
.toLowerCase()
.replace(/&/g, 'and')
.replace(/[^a-z0-9]+/g, '-')
.replace(/(^-|-$)/g, '');
}
function filterLabel(id) {
return BW_FILTERS.find((filter) => filter.id === id)?.label ?? null;
}
function buildFilterDemo(catalogue) {
const group = catalogue.find((entry) => entry.category === 'Black & White');
if (!group) return '';
const withFilter = group.looks.filter((look) => look.filter && look.filter !== 'none').length;
const figures = BW_FILTERS.map(
(filter) => `<figure>
<img src="assets/film/${BW_DEMO_STOCK}--${filter.id}.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" loading="lazy" alt="${escapeHtml(
filter.label,
)} filter on ${escapeHtml(group.looks.find((look) => look.id === BW_DEMO_STOCK)?.name ?? 'a black and white film')}">
<figcaption>${escapeHtml(filter.label)}</figcaption>
<p>${escapeHtml(FILTER_HINTS[filter.id] ?? '')}</p>
</figure>`,
).join('\n ');
return ` <div class="film-filter-demo">
<h3>Colour filters, the way they were used on the lens</h3>
<p class="film-filter-lede">
Before digital, contrast in black and white came from screwing a coloured filter onto
the lens: it held back its own colour, so a red filter turned a blue sky nearly black
while leaving skin bright, and a green one lifted foliage. Each monochrome look here
records the filter it was built with, and ${withFilter} of the ${group.looks.length}
name one. The same Tri-X 400 frame through every filter:
</p>
<div class="film-filters">
${figures}
</div>
<p class="fineprint">Filter strength is adjustable in the editor, so a look can be dialled back from the full strength shown here.</p>
</div>
`;
}
function buildPage(catalogue, framesByCategory) {
const total = catalogue.reduce((sum, group) => sum + group.looks.length, 0);
const chips = catalogue
.map(
(group) =>
`<a href="#${slug(group.category)}">${escapeHtml(group.category)} <span>${group.looks.length}</span></a>`,
)
.join('\n ');
const sections = catalogue
.map((group) => {
const frames = framesByCategory[group.category] ?? [];
const figures = frames
.map(
(frame) => `<figure class="film-set">
<img src="assets/film/${frame.id}.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" loading="lazy" alt="${escapeHtml(frame.name)} applied to the sample photograph">
<figcaption>${escapeHtml(frame.name)}${frame.iso ? ` · ISO ${frame.iso}` : ''}${
frame.process ? ` · ${escapeHtml(frame.process)}` : ''
}</figcaption>
</figure>`,
)
.join('\n ');
const looks = group.looks
.map(
(look) => `<li>
<span class="film-name">${escapeHtml(look.name)}</span>
<span class="film-meta">${[
look.iso ? `ISO ${look.iso}` : '',
look.process ?? '',
look.filter && look.filter !== 'none' ? `${filterLabel(look.filter)} filter` : '',
]
.filter(Boolean)
.join(' · ')}</span>
${look.note ? `<span class="film-note">${escapeHtml(look.note)}</span>` : ''}
</li>`,
)
.join('\n ');
return ` <section class="section${group.index % 2 === 1 ? ' section-alt' : ''}" id="${slug(group.category)}">
<div class="wrap">
<div class="section-head">
<p class="kicker">${escapeHtml(group.category)} · ${group.looks.length} looks</p>
<h2>${escapeHtml(group.category)}</h2>
<p class="section-lede">${escapeHtml(CATEGORY_HINTS[group.category] ?? '')}</p>
</div>
${group.category === 'Black & White' ? buildFilterDemo(catalogue) : ''} <div class="film-sets">
${figures}
</div>
<ul class="film-looks">
${looks}
</ul>
</div>
</section>`;
})
.join('\n\n');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Luminary film looks: ${total} documented film emulations</title>
<meta name="description" content="The full Luminary film pack: ${total} film looks by category, each with the stock, ISO, process and a note on the look, rendered on one frame by Luminary's own editor. Black and white looks also record their contrast filter.">
<meta name="theme-color" content="#0c0e11">
<meta property="og:title" content="Luminary film looks: ${total} documented emulations">
<meta property="og:description" content="Colour negative, slide, black and white, cinema, instant, redscale and experimental looks, with frames rendered by the editor itself and the B&W contrast filters shown side by side.">
<meta property="og:type" content="website">
<meta property="og:image" content="assets/film/film-portra-400.jpg">
<link rel="icon" href="assets/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="assets/icon-256.png">
<link rel="stylesheet" href="styles.css?v=20261128g">
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
<header class="site-header">
<div class="wrap header-inner">
<a class="brand" href="index.html" aria-label="Luminary home">
<span class="brand-mark"><img src="assets/icon-256.png" alt="" width="36" height="36"></span>
<span class="brand-name">Luminary</span>
</a>
<nav class="nav" aria-label="Main">
<a href="index.html#develop">Raw editing</a>
<a href="film.html">Film looks</a>
<a href="index.html#library">Organise</a>
<a href="index.html#proofing">Galleries</a>
<a href="index.html#downloads">Download</a>
</nav>
<div class="header-actions">
<details class="mobile-nav">
<summary>Menu</summary>
<nav class="mobile-menu" aria-label="Sections">
<a href="index.html#develop">Raw editing</a>
<a href="film.html">Film looks</a>
<a href="index.html#library">Organise</a>
<a href="index.html#proofing">Galleries</a>
<a href="index.html#downloads">Download</a>
<a href="index.html#install">Install</a>
</nav>
</details>
<a class="btn btn-primary btn-small" href="index.html#downloads">Download</a>
</div>
</div>
</header>
<main id="main">
<section class="hero film-hero" id="top">
<div class="wrap">
<p class="eyebrow"><span class="dot"></span> Film pack · ${total} looks</p>
<h1>${total} film looks.<br><em>One frame, one engine.</em></h1>
<p class="lede">
Every frame below was rendered by Luminary's own editor with the look applied to the
same photograph — no screenshots from another app, no pasted LUTs. Each entry lists
the stock it emulates, its ISO and process, and a note on what it does.
</p>
<div class="film-cats" aria-label="Categories">
${chips}
</div>
<p class="fineprint">Sample frame: a digital photograph, unedited, rendered at ${RENDER_WIDTH}×${RENDER_HEIGHT}. Grain and colour come from the look itself.</p>
</div>
</section>
<section class="section" id="sample">
<div class="wrap">
<figure class="film-original">
<img src="assets/film/original.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" alt="The sample photograph with no film look applied">
<figcaption>The starting frame: no look, no crop, no colour work.</figcaption>
</figure>
<p class="fineprint">
The black and white section also shows the colour-filter technique: the same stock
rendered through yellow, orange, red, green and blue filters, the way contrast was
shaped on film before digital.
</p>
</div>
</section>
${sections}
</main>
<footer class="site-footer">
<div class="wrap footer-inner">
<div class="footer-brand">
<span class="brand-mark small"><img src="assets/icon-256.png" alt="" width="28" height="28"></span>
<div>
<p class="footer-name">Luminary</p>
<p class="footer-note">A photo library and raw editor for people who'd rather own their photos. MIT licensed. © 2026 Brian Hursey.</p>
</div>
</div>
<nav class="footer-links" aria-label="Footer">
<a href="index.html">Product page</a>
<a href="index.html#downloads">Download</a>
<a href="index.html#changelog">Changelog</a>
<a href="https://git.maple-street.net/bhursey/luminary" target="_blank" rel="noopener">Source</a>
<a href="mailto:bhursey@gmail.com?subject=Luminary%20film%20looks">Feedback</a>
</nav>
</div>
</footer>
</body>
</html>
`;
}
/* ------------------------------------------------------------------ main ---- */
function filterDemoJobs() {
return BW_FILTERS.map((filter) => ({
id: BW_DEMO_STOCK,
filter: filter.id,
file: `${BW_DEMO_STOCK}--${filter.id}.jpg`,
}));
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
process.stdout.write(HELP);
return 0;
}
const chromeBin = await findChrome();
if (!chromeBin) {
fail('no Chrome/Chromium found; set CHROME_PATH or install one (WebGL2 is required)');
}
const categories = CATEGORY_ORDER.filter((category) =>
FILM_PRESETS.some((preset) => preset.category === category),
);
const catalogue = categories.map((category, index) => ({
category,
index,
looks: FILM_PRESETS.filter((preset) => preset.category === category).map((preset) => ({
id: preset.id,
name: preset.name,
iso: preset.film?.speed ?? null,
process: preset.film?.process ?? null,
filter: preset.edits.bw ? preset.edits.bwFilter ?? 'none' : null,
note: preset.description ?? null,
})),
}));
const framesByCategory = {};
const jobs = [{ id: 'original', file: 'original.jpg' }];
for (const group of catalogue) {
const picks = (SAMPLE_PICKS[group.category] ?? [])
.filter((id) => group.looks.some((look) => look.id === id))
.slice(0, options.perCategory);
framesByCategory[group.category] = picks.map((id) => {
const look = group.looks.find((entry) => entry.id === id);
return { id, name: look.name, iso: look.iso, process: look.process };
});
for (const id of picks) jobs.push({ id, file: `${id}.jpg` });
}
await mkdir(options.out, { recursive: true });
await rm(DIR, { recursive: true, force: true });
await mkdir(DIR, { recursive: true });
// A 3:2 frame keeps every look comparable; the page states the source size.
await sharp(options.photo)
.rotate()
.resize(RENDER_WIDTH, RENDER_HEIGHT, { fit: 'cover', position: 'centre' })
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
.toFile(path.join(DIR, 'photo.jpg'));
const server = await createServer({
root: ROOT,
logLevel: 'error',
server: { host: '127.0.0.1', port: PORT, strictPort: false },
});
await server.listen();
const base = (server.resolvedUrls?.local?.[0] ?? `http://127.0.0.1:${PORT}/`).replace(/\/$/, '');
// The editor's own filter list, so the page cannot drift from the app.
BW_FILTERS = (await server.ssrLoadModule('/src/lib/edits.ts')).BW_FILTERS;
jobs.push(...filterDemoJobs());
await writeFile(PAGE, PAGE_HTML);
log('photo', `${path.relative(process.cwd(), options.photo)} → ${RENDER_WIDTH}×${RENDER_HEIGHT}`);
log('render', `${jobs.length} frames through the editor's renderer`);
let written;
try {
written = await drive(chromeBin, `${base}/.film-samples/`, jobs, options.out, options.quality);
} finally {
await server.close();
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {});
}
if (written.length !== jobs.length) fail(`only ${written.length} of ${jobs.length} frames rendered`);
await writeFile(
path.join(options.out, 'film-looks.json'),
`${JSON.stringify({ total: FILM_PRESETS.length, categories: catalogue }, null, 2)}\n`,
);
await writeFile(path.join(options.out, 'film.html'), buildPage(catalogue, framesByCategory));
const bytes = (
await Promise.all(written.map((file) => readFile(path.join(options.out, file))))
).reduce((sum, buffer) => sum + buffer.length, 0);
process.stdout.write(
[
'',
'film gallery PASSED',
` frames ${written.length} JPEGs, ${(bytes / 1024 / 1024).toFixed(1)} MB`,
` looks ${FILM_PRESETS.length} across ${catalogue.length} categories`,
` filters ${BW_FILTERS.length} on ${BW_DEMO_STOCK}`,
` page ${path.join(options.out, 'film.html')}`,
` data ${path.join(options.out, 'film-looks.json')}`,
'',
'Copy the frames to assets/film/ and film.html to the site root.',
'',
].join('\n'),
);
return 0;
}
main().then(
(code) => {
process.exitCode = code;
},
(error) => {
fail(error instanceof Error ? error.message : String(error));
},
);