Skip to content

Instantly share code, notes, and snippets.

@jcreedcmu
Created February 7, 2022 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcreedcmu/52b7d9ec654b5572108d980f5d711d73 to your computer and use it in GitHub Desktop.
Save jcreedcmu/52b7d9ec654b5572108d980f5d711d73 to your computer and use it in GitHub Desktop.
Generate a nice dithered circle
// for any integer coordinates x, y, returns a float in [0,1] which is
// interpreted as threshold a float-valued function should have to
// reach in order to make a bitmap pixel.
function dither(x: number, y: number): number {
return (x == 0 && y == 0
? 0
: ([0, 2, 3, 1][(y % 2) * 2 + (x % 2)] + dither(x >> 1, y >> 1)) / 4);
}
function tableau(edge: number, f: (x: number, y: number) => number): number[][] {
const table: number[][] = [...Array(edge).keys()].map(k => []);
for (let ii = 0; ii < edge; ii++) {
for (let jj = 0; jj < edge; jj++) {
if (f(ii / edge, jj / edge) > dither(ii, jj))
table[ii][jj] = 1;
}
}
return table;
}
function func(x: number, y: number): number {
return 5 * (Math.pow(x - 0.5, 2) + Math.pow(y - 0.5, 2));
}
function bitmap(edge: number): string {
const tab = tableau(edge, func);
let str = `P1 ${tab.length} ${tab.length}\n`;
for (let i = 0; i < tab.length; i++) {
for (let j = 0; j < tab.length; j++) {
str += (tab[i][j] ? 1 : 0) + ' ';
}
str += '\n';
}
return str;
}
import * as fs from 'fs';
fs.writeFileSync('/tmp/a.pbm', bitmap(256), 'utf8');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment