Compare commits

..

1 Commits

Author SHA1 Message Date
Mike Lynch
4f1e73d498 Removed logging statement 2025-03-26 18:00:22 +11:00
8 changed files with 127 additions and 217 deletions

1
package-lock.json generated
View File

@ -80,6 +80,7 @@
},
"node_modules/@clack/prompts/node_modules/is-unicode-supported": {
"version": "1.3.0",
"extraneous": true,
"inBundle": true,
"license": "MIT",
"engines": {

View File

@ -2,7 +2,6 @@ import { Resvg } from "@resvg/resvg-js";
import { promises } from "fs";
import { JSDOM } from "jsdom";
import * as d3 from "d3";
import * as d3c from "d3-color";
import yargs from "yargs/yargs";
import { hideBin } from "yargs/helpers";
import spawn from "await-spawn";
@ -12,17 +11,14 @@ const xmlns = "http://www.w3.org/2000/xmlns/";
const xlinkns = "http://www.w3.org/1999/xlink";
const svgns = "http://www.w3.org/2000/svg";
import {RADIUS_OPTS, RADIUS_DESC, radius_func, DotMaker} from './src/components/dots.js';
import {PALETTES} from './src/components/palettes.js';
import {ColourNamer} from './src/components/colour_namer.js';
import {RADIUS_OPTS, RADIUS_DESC, DotMaker} from './src/components/dots.js';
import {PALETTES, ColourNamer} from './src/components/palettes.js';
const CELL = 10;
const MAG = 2;
const WIDTH = 200;
const WIDTH = 20;
const HEIGHT = WIDTH;
// number of pixels which have to be visible for a colour to be
// mentioned in the alt text
const VISIBLE_DOG = 400;
const VISIBLE_DOG = 1000;
function randomise_params() {
const palette_name = random.choice(Array.from(PALETTES.keys()));
@ -36,37 +32,13 @@ function randomise_params() {
f: random.choice(RADIUS_OPTS),
r: random.float(0, 0.4),
}});
const cell = 5 + random.float() * random.float() * 55;
return {
background: palette[0],
palette: palette_name,
patterns: patterns,
cell: cell,
patterns: patterns
}
}
async function load_or_random_params(paramf) {
if( paramf ) {
const pjson = await promises.readFile(paramf);
const params = JSON.parse(pjson);
params.background = d3c.color(params.background);
params.patterns.forEach((p) => {
p.colour = d3c.color(p.colour);
});
return params;
}
return randomise_params();
}
async function save_params(paramf, params) {
params.background = params.background.formatHex();
params.patterns.forEach((p) => {
p.colour = p.colour.formatHex();
});
await promises.writeFile(paramf, JSON.stringify(params));
}
// lol the best way I found to to this was imagemagick!
@ -136,34 +108,30 @@ function poptimal_svg(params) {
const document = window.document;
const container = d3.select(document.body).append("div");
const width = WIDTH / params.cell;
const height = WIDTH / params.cell;
const dm = new DotMaker(width, height);
const dm = new DotMaker(WIDTH);
const svg = container.append("svg")
.attr("width", WIDTH * MAG)
.attr("height", HEIGHT * MAG)
.attr("viewBox", [ 0, 0, width, height ]);
.attr("width", WIDTH * CELL * MAG)
.attr("height", HEIGHT * CELL * MAG)
.attr("viewBox", [ 0, 0, WIDTH, HEIGHT ]);
const background = svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.attr("width", WIDTH)
.attr("height", WIDTH)
.attr("fill", params.background);
params.patterns.map((p) => {
const dots = dm.dots(1 / p.m, p.n, false);
const rfunc = radius_func(p.f);
const dots = dm.dots(1 / p.m, p.n);
const dots_g = svg.append("g")
.attr("id", `dots${p.i}`);
dots_g.selectAll("circle")
.data(dots)
.join("circle")
.attr("r", (d) => rfunc(d, p.r, width, height))
.attr("r", (d) => dm.radius(d, p.f, p.r))
.attr("fill", p.colour)
.attr("cx", (d) => d.x)
.attr("cy", (d) => d.y);
@ -214,22 +182,20 @@ async function post_image(image, alt_text, cf) {
async function main() {
const argv = yargs(hideBin(process.argv))
.usage("Usage: -s SIZE [-o output] -c config.json [-p params.json]")
.usage("Usage: -s SIZE -o output.png -c config.json")
.default('s', 1200)
.default('c', 'config.json').argv;
const cfjson = await promises.readFile(argv.c);
const cf = JSON.parse(cfjson);
const ts = String(Date.now());
const fn = (argv.o || ts) + '.png';
const jsfn = (argv.o || ts) + '.json';
const fn = argv.o || String(Date.now()) + '.png';
const imgfile = cf['working_dir'] + '/' + fn;
const paramsfile = cf['working_dir'] + '/' + jsfn;
const params = await load_or_random_params(argv.p);
const params = randomise_params();
const colourf = params.palette === 'grayscale' ? cf['grayscale'] : cf['colour'];
const namer = new ColourNamer();
@ -249,14 +215,14 @@ async function main() {
const pngData = resvg.render();
const pngBuffer = pngData.asPng();
await promises.writeFile(imgfile, pngBuffer);
// generate the alt_text last to check the image file histogram
// so we don't include obscured colours
const hist = await get_histogram(imgfile);
const alt_text = image_description(namer, params, hist);
params.alt_text = alt_text;
await save_params(paramsfile, params);
console.log(alt_text);
console.log(imgfile);
if( cf['base_url'] ) {

View File

@ -1,39 +0,0 @@
import { promises } from "fs";
import * as d3 from "d3-color";
import * as d3cd from "d3-color-difference";
class ColourNamer {
constructor() {
this.colmap = new Map();
}
async load_colours(colourfile) {
const colourBuff = await promises.readFile(colourfile);
const colours = colourBuff.toString();
const seen = new Set();
colours.split(/\n/).map((l) => {
const m = l.match(/(\d+)\s+(\d+)\s+(\d+)\s+(.*)/);
if( m ) {
const sig = `${m[1]},${m[2]},${m[3]}`;
if( !seen.has(sig) ) {
this.colmap.set(m[4], d3.rgb(m[1], m[2], m[3]));
seen.add(sig);
}
}
});
}
colour_to_text(d3color) {
const diffs = []
for( const [ name, colour] of this.colmap) {
diffs.push({name: name, dist: d3cd.differenceCie76(colour, d3color)});
}
diffs.sort((a, b) => a.dist - b.dist);
return diffs[0].name;
}
}
export { ColourNamer}

View File

@ -11,17 +11,14 @@ const RADIUS_OPTS = [
"right-down",
"left-up",
"left-down",
"circle-in",
"circle-out",
"hyper-in",
"hyper-out",
"grid",
"in",
"out",
"noise",
];
const RADIUS_DESC = {
"const": "of constant size",
"right": "getting larger towards the right",
"right": "getting larger towards the left",
"left": "getting larger towards the left",
"up": "getting larger towards the top",
"down": "getting larger towards the bottom",
@ -29,100 +26,87 @@ const RADIUS_DESC = {
"right-down": "getting larger towards the lower right",
"left-up": "getting larger towards the upper left",
"left-down": "getting larger towards the lower left",
"circle-in": "forming a circle at the centre",
"circle-out": "leaving a circular gap at the centre",
"hyper-in": "forming a starlike pattern at the centre",
"hyper-out": "leaving a starlike gap in the centre",
"in": "getting larger in the centre",
"out": "getting larger at the edges",
"noise": "of random sizes",
"grid": "forming a grid pattern",
}
function distance(dx, dy) {
return Math.sqrt(dx ** 2 + dy ** 2);
}
function int_range(v1, v2) {
const vs = [v1, v2];
vs.sort((a, b) => a - b);
const low = Math.floor(vs[0] - 1);
const high = Math.ceil(vs[1] + 1);
const low = Math.floor(vs[0]);
const high = Math.ceil(vs[1]);
return [...Array(high - low + 1).keys()].map((i) => i + low);
}
function randint(min, max) {
return min + Math.floor(Math.random() * (max + 1));
}
class DotMaker {
constructor(width, height) {
constructor(width) {
this.width = width;
this.height = height;
this.wh = 0.5 * (width + height);
this.cx = 0.5 * width;
this.cy = 0.5 * height;
this.cy = 0.5 * width;
}
dots(m, n, clip) {
dots(m, n) {
if( m - n === 0 ) {
return [];
}
const ps = [];
const is = int_range(-this.width, this.height / m)
const is = int_range(-this.width, this.width / m)
is.map((i) => {
const js = int_range(m * i + (m - n) * this.width, m * i)
js.map((j) => {
const x = (j - m * i) / (m - n);
const y = m * (x + i);
if( !clip || (x > 0 && y > 0 && x < this.width && y < this.height) ) {
if( x > 0 && y > 0 && x < this.width && y < this.width ) {
ps.push({i:i, j:j, x:x, y:y});
}
});
});
return ps;
}
radius(d, func, maxr) {
switch (func) {
case "const":
return maxr;
case "right":
return maxr * d.x / this.width;
case "left":
return maxr * (this.width - d.x) / this.width;
case "down":
return maxr * d.y / this.width;
case "up":
return maxr * (this.width - d.y) / this.width;
case "right-up":
return 0.5 * maxr * (d.x + this.width - d.y) / this.width;
case "left-up":
return 0.5 * maxr * (this.width - d.x + this.width - d.y) / this.width;
case "right-down":
return 0.5 * maxr * (d.x + d.y) / this.width;
case "left-down":
return 0.5 * maxr * (this.width - d.x + d.y) / this.width;
case "out":
return 2 * maxr * distance((d.x - this.cx), (d.y - this.cy)) / this.width;
case "in":
return 2 * maxr * (0.5 * this.width - distance((d.x - this.cx), (d.y - this.cy))) / this.width;
// case "hyper-out":
// return 2 * maxr * Math.abs(d.x - this.cx) (d.y - this.cy)) / this.width;
// case "hyoer-in":
// return 2 * maxr * (0.5 * this.width - distance((d.x - this.cx), (d.y - this.cy))) / this.width;
case "noise":
return maxr * Math.random();
default:
return maxr;
}
}
}
function radius_func(func) {
switch (func) {
case "const":
return (d, r, w, h) => r;
case "right":
return (d, r, w, h) => r * d.x / w;
case "left":
return (d, r, w, h) => r * (w - d.x) / w;
case "down":
return (d, r, w, h) => r * d.y / h;
case "up":
return (d, r, w, h) => r * (h - d.y) / h;
case "right-up":
return (d, r, w, h) => r * (d.x + h - d.y) / (w + h);
case "left-up":
return (d, r, w, h) => r * (w - d.x + h - d.y) / (w + h);
case "right-down":
return (d, r, w, h) => r * (d.x + d.y) / (w + h);
case "left-down":
return (d, r, w, h) => r * (w - d.x + d.y) / (w + h);
case "circle-out":
return (d, r, w, h) => 4 * r * distance((d.x - w / 2), (d.y - h / 2)) / (w + h);
case "circle-in":
return (d, r, w, h) => 4 * r * (0.5 * (w + h) - distance((d.x - w / 2), (d.y - h / 2))) / (w + h);
case "hyper-in":
return (d, r, w, h) => 2 * r * (1 - Math.abs((d.x - w / 2) * (d.y - h / 2)) / (w + h));
case "hyper-out":
return (d, r, w, h) => 2 * r * Math.abs((d.x - w / 2) * (d.y - h / 2)) / (w + h);
case "noise":
return (d, r, w, h) => r * Math.random();
case "grid":
const xk = Math.PI * (2 * randint(1, 10) - 1);
const yk = Math.PI * (2 * randint(1, 10) - 1);
return (d, r, w, h) => r * (0.5 + 0.5 * (Math.sin(xk * d.x / w) + Math.sin(yk * d.y / h)));
default:
return (d, r, w, h) => r;
}
}
export { RADIUS_OPTS, RADIUS_DESC, DotMaker, radius_func };
export { RADIUS_OPTS, RADIUS_DESC, DotMaker };

View File

@ -73,7 +73,7 @@ export async function download_as_png (svg) {
const opts = {
fitTo: {
mode: 'width', // If you need to change the size
value: 1200,
value: 400,
}
};
const resvgJS = new resvg.Resvg(svgstr, opts)

View File

@ -2,7 +2,9 @@
import * as d3 from "d3-color";
import shuffle from "lodash.shuffle";
import random from "random";
import { promises } from "fs";
import * as d3cd from "d3-color-difference";
const PALETTES = new Map([
[ "random RGB", palette_random ],
@ -76,6 +78,36 @@ function palette_cmy() {
return shuffle(cols);
}
class ColourNamer {
constructor() {
this.colmap = new Map();
}
async load_colours(colourfile) {
const colourBuff = await promises.readFile(colourfile);
const colours = colourBuff.toString();
const seen = new Set();
colours.split(/\n/).map((l) => {
const m = l.match(/(\d+)\s+(\d+)\s+(\d+)\s+(.*)/);
if( m ) {
const sig = `${m[1]},${m[2]},${m[3]}`;
if( !seen.has(sig) ) {
this.colmap.set(m[4], d3.rgb(m[1], m[2], m[3]));
seen.add(sig);
}
}
});
}
colour_to_text(d3color) {
const diffs = []
for( const [ name, colour] of this.colmap) {
diffs.push({name: name, dist: d3cd.differenceCie76(colour, d3color)});
}
diffs.sort((a, b) => a.dist - b.dist);
return diffs[0].name;
}
}
export { PALETTES }
export { PALETTES, ColourNamer }

View File

@ -8,15 +8,15 @@ toc: false
colourful generative patterns using [d3](https://d3js.org/) and [Observable Framework](https://observablehq.com/framework/)
<p>v1.2.2 | by <a href="https://mikelynch.org">mike lynch</a> | <a href="https://aus.social/@mikelynch">@mikelynch@aus.social</a> | <a href="https://git.tilde.town/bombinans/poptimal">source</a> | <a href="https://mikelynch.org/2025/Mar/09/poptimal/">about</a></p>
<p>v1.1.1 | by <a href="https://mikelynch.org">mike lynch</a> | <a href="https://aus.social/@mikelynch">@mikelynch@aus.social</a> | <a href="https://git.tilde.town/bombinans/poptimal">source</a></p>
<div class="grid grid-cols-3">
<div class="grid grid-cols-2">
<div class="card grid-colspan-1">
<div class="card">
```js
import {RADIUS_OPTS, DotMaker, radius_func} from './components/dots.js';
import {RADIUS_OPTS, DotMaker} from './components/dots.js';
import {DotControls} from './components/controls.js';
import {PALETTES} from './components/palettes.js';
import {download, download_as_svg, download_as_png} from './components/download.js';
@ -24,26 +24,18 @@ import random from "npm:random";
import * as resvg from 'npm:@resvg/resvg-wasm';
const CELL = 10;
const MAG = 2;
const WIDTH = 200;
const HEIGHT = 200;
const WIDTH = 20;
const HEIGHT = WIDTH;
const cell_input = Inputs.range([5,60], {value: 10, label: "cell size"});
const cell = view(cell_input);
const dm = new DotMaker(WIDTH);
```
```js
const bg_input = Inputs.color({
label: "background", value: d3.color("white").formatHex()
});
const bg_input = Inputs.color({label: "background", value: d3.color("yellow").formatHex()});
const bg = view(bg_input);
const ctrl1 = new DotControls(d3.color("white").formatHex(), RADIUS_OPTS);
const ctrl2 = new DotControls(d3.color("white").formatHex(), RADIUS_OPTS);
const ctrl1 = new DotControls(d3.color("red").formatHex(), RADIUS_OPTS);
const ctrl2 = new DotControls(d3.color("blue").formatHex(), RADIUS_OPTS);
const fg1 = view(ctrl1.fg);
@ -95,8 +87,6 @@ ctrl1.null_grid();
ctrl2.null_grid();
palette_input.value = PALETTES.get(rpalette);
palette_input.dispatchEvent(new Event("input"));
cell_input.value = 5 + random.float() * random.float() * 55;
cell_input.dispatchEvent(new Event("input"));
ctrl1.random_grid();
ctrl2.random_grid();
@ -123,26 +113,14 @@ if( palette_fn ) {
```
</div>
<div class="card grid-colspan-2">
<div>
```js
const width = WIDTH / cell;
const height = HEIGHT / cell;
const dots1 = dm.dots(1 / m1, n1);
const dots2 = dm.dots(1 / m2, n2);
const dm = new DotMaker(width, height);
const dots1 = dm.dots(1 / m1, n1, false);
const dots2 = dm.dots(1 / m2, n2, false);
```
```js
const rfunc1 = radius_func(f1);
const rfunc2 = radius_func(f2);
```
@ -151,18 +129,9 @@ const rfunc2 = radius_func(f2);
const svg = d3.create("svg")
.attr("width", WIDTH * MAG)
.attr("height", HEIGHT * MAG)
.attr("viewBox", [ 0, 0, width, height ]);
svg.append("clipPath")
.attr("id", "clipRect")
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height);
.attr("width", WIDTH * CELL * MAG)
.attr("height", HEIGHT * CELL * MAG)
.attr("viewBox", [ 0, 0, WIDTH, HEIGHT ]);
// re transitions: they should only run when updating the palette and
@ -182,15 +151,14 @@ bg_g.selectAll("rect")
.join("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.attr("width", WIDTH)
.attr("height", WIDTH)
.attr("fill", (d) => d.bg)
;
const dots_g1 = svg.append("g")
.attr("id", "dots1")
.attr("clip-path", "url(#clipRect)");
.attr("id", "dots1");
dots_g1.selectAll("circle")
.data(dots1)
@ -200,8 +168,7 @@ dots_g1.selectAll("circle")
.attr("fill", fg1);
const dots_g2 = svg.append("g")
.attr("id", "dots2")
.attr("clip-path", "url(#clipRect)");
.attr("id", "dots2");
dots_g2.selectAll("circle")
.data(dots2)
@ -217,8 +184,8 @@ display(svg.node());
```js
// separate code block for when I understand transitions better
dots_g1.selectAll("circle").attr("r", (d) => rfunc1(d, r1, width, height));
dots_g2.selectAll("circle").attr("r", (d) => rfunc2(d, r2, width, height));
dots_g1.selectAll("circle").attr("r", (d) => dm.radius(d, f1, r1));
dots_g2.selectAll("circle").attr("r", (d) => dm.radius(d, f2, r2));
```
@ -244,7 +211,6 @@ display(download(() => {
```
(PNGs made with <a href="https://github.com/thx/resvg-js">resvg-wasm</a> in-browser)
</div>
</div>
<style>