Created
February 7, 2022 23:45
-
-
Save jcreedcmu/52b7d9ec654b5572108d980f5d711d73 to your computer and use it in GitHub Desktop.
Generate a nice dithered circle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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