Files
spore/test/pixelstream/spiral-bloom.js

98 lines
2.7 KiB
JavaScript

const dgram = require('dgram');
const {
createFrame,
frameToPayload,
hexToRgb,
samplePalette,
toIndex,
} = require('./shared-frame-utils');
const DEFAULT_PORT = 4210;
const DEFAULT_WIDTH = 16;
const DEFAULT_HEIGHT = 16;
const DEFAULT_INTERVAL_MS = 55;
const paletteStops = [
{ stop: 0.0, color: hexToRgb('051923') },
{ stop: 0.2, color: hexToRgb('0c4057') },
{ stop: 0.45, color: hexToRgb('1d7a70') },
{ stop: 0.7, color: hexToRgb('39b15f') },
{ stop: 0.88, color: hexToRgb('9dd54c') },
{ stop: 1.0, color: hexToRgb('f7f5bc') },
];
const host = process.argv[2];
const port = parseInt(process.argv[3] || String(DEFAULT_PORT), 10);
const width = parseInt(process.argv[4] || String(DEFAULT_WIDTH), 10);
const height = parseInt(process.argv[5] || String(DEFAULT_HEIGHT), 10);
const intervalMs = parseInt(process.argv[6] || String(DEFAULT_INTERVAL_MS), 10);
if (!host) {
console.error('Usage: node spiral-bloom.js <device-ip> [port] [width] [height] [interval-ms]');
process.exit(1);
}
if (Number.isNaN(port) || Number.isNaN(width) || Number.isNaN(height) || Number.isNaN(intervalMs)) {
console.error('Invalid numeric argument. Expected integers for port, width, height, and interval-ms.');
process.exit(1);
}
if (width <= 0 || height <= 0) {
console.error('Matrix dimensions must be positive integers.');
process.exit(1);
}
const socket = dgram.createSocket('udp4');
const isBroadcast = host === '255.255.255.255' || host.endsWith('.255');
const frame = createFrame(width, height);
let rotation = 0;
let hueShift = 0;
const frameTimeSeconds = intervalMs / 1000;
if (isBroadcast) {
socket.bind(() => {
socket.setBroadcast(true);
});
}
socket.on('error', (error) => {
console.error('Socket error:', error.message);
});
function generateFrame() {
rotation += frameTimeSeconds * 0.7;
hueShift += frameTimeSeconds * 0.2;
const cx = (width - 1) / 2;
const cy = (height - 1) / 2;
const radiusNorm = Math.hypot(cx, cy) || 1;
for (let row = 0; row < height; ++row) {
for (let col = 0; col < width; ++col) {
const dx = col - cx;
const dy = row - cy;
const radius = Math.hypot(dx, dy) / radiusNorm;
const angle = Math.atan2(dy, dx);
const arm = 0.5 + 0.5 * Math.sin(5 * (angle + rotation) + hueShift * Math.PI * 2);
const value = Math.min(1, radius * 0.8 + arm * 0.4);
frame[toIndex(col, row, width)] = samplePalette(paletteStops, value);
}
}
return frameToPayload(frame);
}
function sendFrame() {
const payload = generateFrame();
const message = Buffer.from(payload, 'utf8');
socket.send(message, port, host);
}
setInterval(sendFrame, intervalMs);
console.log(
`Streaming spiral bloom to ${host}:${port} (${width}x${height}, interval=${intervalMs}ms)`,
);