Skip to content

Instantly share code, notes, and snippets.

@jcreedcmu
Created November 30, 2022 23:34
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/601413164ff887d47e13d28cd83f05d5 to your computer and use it in GitHub Desktop.
Save jcreedcmu/601413164ff887d47e13d28cd83f05d5 to your computer and use it in GitHub Desktop.
collabradoodle renderer
const W = 52;
const H = 30;
const MAX_ITER = 1000;
function iters(cr, ci) {
let zi = 0;
let zr = 0;
for (let i = 0; i < MAX_ITER; i++) {
[zr, zi] = [zr * zr - zi * zi + cr, 2 * zr * zi + ci];
if (zr * zr + zi * zi > 16.0) return i;
}
return MAX_ITER;
}
function mandelnum(i, j) {
const x = -0.6 + 3.2 * ((i / W) - 0.5);
const y = 3.2 * (H / W) * ((j / H) - 0.5);
const I = iters(x, y);
return (I > 900) ? 0 : I > 5 ? 1 : I > 3 ? 2 : I > 2 ? 3 : 4;
}
function render(renderChar, newLine) {
for (let j = 0; j < H; j++) {
for (let i = 0; i < W; i++) {
renderChar(i, j, mandelnum(i, j));
}
newLine();
}
}
/// Terminal testing
function renderCharTerminal(i, j, n) {
process.stdout.write(['# ', '- ', '& ', '^ ', ' '][n]);
}
function newLineTerminal() {
process.stdout.write("\n");
}
/// Websocket version
const [black, white, red, blue, yellow] = [70, 64, 164, 132, 178];
// I reverse-engineered what `coordOf` and `plot` had to be by doing things like
//
// oldsend = WebSocket.prototype.send; WebSocket.prototype.send = function(...args) { oldsend.call(this, ...args); window.ws = this; window.msg = args[0]; console.log(new Uint8Array(msg).join(",")); };
//
// in the developer console, and playing around in the interface.
function coordOf(n) {
const t = 2 * n;
if (t < 216) return [t];
const rem = t - 216;
return [216 + Math.floor(rem / 256), rem % 256];
}
function plot(n, color) {
ws.send(new Uint8Array([0,10,0,1,30,51,119,111,56,121,95,54,121,115,117,120,118,113,121,100,1,color,...coordOf(n)]).buffer);
}
function renderCharCollab(x, y, n) {
plot(y * W + x, [black, blue, red, yellow, white][n]);
}
const testing = false;
if (testing) {
render(renderCharTerminal, newLineTerminal);
}
else {
render(renderCharCollab, () => {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment