some easy wins

This commit is contained in:
2025-07-05 23:02:15 +02:00
parent 3bf96a5721
commit f7054d8300
2 changed files with 508 additions and 79 deletions

View File

@ -43,11 +43,68 @@ interface WorkerResponse {
class ShaderWorker {
private compiledFunction: Function | null = null;
private lastCode: string = '';
private mathCache: Map<string, number> = new Map();
private sinTable: Float32Array;
private cosTable: Float32Array;
private expTable: Float32Array;
private logTable: Float32Array;
private imageDataCache: Map<string, ImageData> = new Map();
private compilationCache: Map<string, Function> = new Map();
private colorTables: Map<string, Uint8Array> = new Map();
constructor() {
self.onmessage = (e: MessageEvent<WorkerMessage>) => {
this.handleMessage(e.data);
};
this.initializeLookupTables();
this.initializeColorTables();
}
private initializeLookupTables(): void {
const tableSize = 4096;
this.sinTable = new Float32Array(tableSize);
this.cosTable = new Float32Array(tableSize);
this.expTable = new Float32Array(tableSize);
this.logTable = new Float32Array(tableSize);
for (let i = 0; i < tableSize; i++) {
const x = (i / tableSize) * 2 * Math.PI;
this.sinTable[i] = Math.sin(x);
this.cosTable[i] = Math.cos(x);
this.expTable[i] = Math.exp(x / tableSize);
this.logTable[i] = Math.log(1 + x / tableSize);
}
}
private initializeColorTables(): void {
const tableSize = 256;
// Pre-compute color tables for each render mode
const modes = ['classic', 'grayscale', 'red', 'green', 'blue', 'rgb', 'hsv', 'rainbow'];
for (const mode of modes) {
const colorTable = new Uint8Array(tableSize * 3); // RGB triplets
for (let i = 0; i < tableSize; i++) {
const [r, g, b] = this.calculateColorDirect(i, mode);
colorTable[i * 3] = r;
colorTable[i * 3 + 1] = g;
colorTable[i * 3 + 2] = b;
}
this.colorTables.set(mode, colorTable);
}
}
private fastSin(x: number): number {
const index = Math.floor(Math.abs(x * this.sinTable.length / (2 * Math.PI)) % this.sinTable.length);
return this.sinTable[index];
}
private fastCos(x: number): number {
const index = Math.floor(Math.abs(x * this.cosTable.length / (2 * Math.PI)) % this.cosTable.length);
return this.cosTable[index];
}
private handleMessage(message: WorkerMessage): void {
@ -66,30 +123,60 @@ class ShaderWorker {
}
private compileShader(id: string, code: string): void {
const codeHash = this.hashCode(code);
if (code === this.lastCode && this.compiledFunction) {
this.postMessage({ id, type: 'compiled', success: true });
return;
}
// Check compilation cache
const cachedFunction = this.compilationCache.get(codeHash);
if (cachedFunction) {
this.compiledFunction = cachedFunction;
this.lastCode = code;
this.postMessage({ id, type: 'compiled', success: true });
return;
}
try {
const safeCode = this.sanitizeCode(code);
this.compiledFunction = new Function('x', 'y', 't', 'i', 'mouseX', 'mouseY', 'mousePressed', 'mouseVX', 'mouseVY', 'mouseClickTime', 'touchCount', 'touch0X', 'touch0Y', 'touch1X', 'touch1Y', 'pinchScale', 'pinchRotation', 'accelX', 'accelY', 'accelZ', 'gyroX', 'gyroY', 'gyroZ', 'audioLevel', 'bassLevel', 'midLevel', 'trebleLevel', `
// Timeout protection
const startTime = performance.now();
let iterations = 0;
function checkTimeout() {
iterations++;
if (iterations % 1000 === 0 && performance.now() - startTime > 5) {
throw new Error('Shader timeout');
// Check if expression is static (contains no variables)
const isStatic = this.isStaticExpression(safeCode);
if (isStatic) {
// Pre-compute static value
const staticValue = this.evaluateStaticExpression(safeCode);
this.compiledFunction = () => staticValue;
} else {
this.compiledFunction = new Function('x', 'y', 't', 'i', 'mouseX', 'mouseY', 'mousePressed', 'mouseVX', 'mouseVY', 'mouseClickTime', 'touchCount', 'touch0X', 'touch0Y', 'touch1X', 'touch1Y', 'pinchScale', 'pinchRotation', 'accelX', 'accelY', 'accelZ', 'gyroX', 'gyroY', 'gyroZ', 'audioLevel', 'bassLevel', 'midLevel', 'trebleLevel', `
// Timeout protection
const startTime = performance.now();
let iterations = 0;
function checkTimeout() {
iterations++;
if (iterations % 1000 === 0 && performance.now() - startTime > 5) {
throw new Error('Shader timeout');
}
}
}
return (function() {
checkTimeout();
return ${safeCode};
})();
`);
return (function() {
checkTimeout();
return ${safeCode};
})();
`);
}
// Cache the compiled function
this.compilationCache.set(codeHash, this.compiledFunction);
// Limit cache size to prevent memory bloat
if (this.compilationCache.size > 20) {
const firstKey = this.compilationCache.keys().next().value;
this.compilationCache.delete(firstKey);
}
this.lastCode = code;
this.postMessage({ id, type: 'compiled', success: true });
@ -99,78 +186,277 @@ class ShaderWorker {
}
}
private isStaticExpression(code: string): boolean {
// Check if code contains any variables
const variables = ['x', 'y', 't', 'i', 'mouseX', 'mouseY', 'mousePressed', 'mouseVX', 'mouseVY', 'mouseClickTime', 'touchCount', 'touch0X', 'touch0Y', 'touch1X', 'touch1Y', 'pinchScale', 'pinchRotation', 'accelX', 'accelY', 'accelZ', 'gyroX', 'gyroY', 'gyroZ', 'audioLevel', 'bassLevel', 'midLevel', 'trebleLevel'];
for (const variable of variables) {
if (code.includes(variable)) {
return false;
}
}
return true;
}
private evaluateStaticExpression(code: string): number {
try {
// Safely evaluate numeric expression
const result = new Function(`return ${code}`)();
return isFinite(result) ? result : 0;
} catch (error) {
return 0;
}
}
private hashCode(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
return hash.toString(36);
}
private renderShader(id: string, width: number, height: number, time: number, renderMode: string, message: WorkerMessage): void {
if (!this.compiledFunction) {
this.postError(id, 'No compiled shader');
return;
}
const imageData = new ImageData(width, height);
const imageData = this.getOrCreateImageData(width, height);
const data = imageData.data;
const startTime = performance.now();
const maxRenderTime = 50; // 50ms max render time
try {
for (let y = 0; y < height; y++) {
// Check timeout every row
if (performance.now() - startTime > maxRenderTime) {
// Fill remaining pixels with black and break
for (let remainingY = y; remainingY < height; remainingY++) {
for (let remainingX = 0; remainingX < width; remainingX++) {
const i = (remainingY * width + remainingX) * 4;
data[i] = 0; // R
data[i + 1] = 0; // G
data[i + 2] = 0; // B
data[i + 3] = 255; // A
}
}
break;
}
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
const pixelIndex = y * width + x;
try {
const value = this.compiledFunction(
x, y, time, pixelIndex,
message.mouseX || 0, message.mouseY || 0,
message.mousePressed || false,
message.mouseVX || 0, message.mouseVY || 0,
message.mouseClickTime || 0,
message.touchCount || 0,
message.touch0X || 0, message.touch0Y || 0,
message.touch1X || 0, message.touch1Y || 0,
message.pinchScale || 1, message.pinchRotation || 0,
message.accelX || 0, message.accelY || 0, message.accelZ || 0,
message.gyroX || 0, message.gyroY || 0, message.gyroZ || 0,
message.audioLevel || 0, message.bassLevel || 0, message.midLevel || 0, message.trebleLevel || 0
);
const safeValue = isFinite(value) ? value : 0;
const [r, g, b] = this.calculateColor(safeValue, renderMode);
data[i] = r; // R
data[i + 1] = g; // G
data[i + 2] = b; // B
data[i + 3] = 255; // A
} catch (error) {
data[i] = 0; // R
data[i + 1] = 0; // G
data[i + 2] = 0; // B
data[i + 3] = 255; // A
}
}
}
// Use tiled rendering for better timeout handling
this.renderTiled(data, width, height, time, renderMode, message, startTime, maxRenderTime);
this.postMessage({ id, type: 'rendered', success: true, imageData });
} catch (error) {
this.postError(id, error instanceof Error ? error.message : 'Render failed');
}
}
private renderTiled(data: Uint8ClampedArray, width: number, height: number, time: number, renderMode: string, message: WorkerMessage, startTime: number, maxRenderTime: number): void {
const tileSize = 64; // 64x64 tiles for better granularity
const tilesX = Math.ceil(width / tileSize);
const tilesY = Math.ceil(height / tileSize);
for (let tileY = 0; tileY < tilesY; tileY++) {
for (let tileX = 0; tileX < tilesX; tileX++) {
// Check timeout before each tile
if (performance.now() - startTime > maxRenderTime) {
const startX = tileX * tileSize;
const startY = tileY * tileSize;
this.fillRemainingPixels(data, width, height, startY, startX);
return;
}
const tileStartX = tileX * tileSize;
const tileStartY = tileY * tileSize;
const tileEndX = Math.min(tileStartX + tileSize, width);
const tileEndY = Math.min(tileStartY + tileSize, height);
this.renderTile(data, width, tileStartX, tileStartY, tileEndX, tileEndY, time, renderMode, message);
}
}
}
private renderTile(data: Uint8ClampedArray, width: number, startX: number, startY: number, endX: number, endY: number, time: number, renderMode: string, message: WorkerMessage): void {
for (let y = startY; y < endY; y++) {
for (let x = startX; x < endX; x++) {
const i = (y * width + x) * 4;
const pixelIndex = y * width + x;
try {
const value = this.compiledFunction!(
x, y, time, pixelIndex,
message.mouseX || 0, message.mouseY || 0,
message.mousePressed || false,
message.mouseVX || 0, message.mouseVY || 0,
message.mouseClickTime || 0,
message.touchCount || 0,
message.touch0X || 0, message.touch0Y || 0,
message.touch1X || 0, message.touch1Y || 0,
message.pinchScale || 1, message.pinchRotation || 0,
message.accelX || 0, message.accelY || 0, message.accelZ || 0,
message.gyroX || 0, message.gyroY || 0, message.gyroZ || 0,
message.audioLevel || 0, message.bassLevel || 0, message.midLevel || 0, message.trebleLevel || 0
);
const safeValue = isFinite(value) ? value : 0;
const [r, g, b] = this.calculateColor(safeValue, renderMode);
data[i] = r;
data[i + 1] = g;
data[i + 2] = b;
data[i + 3] = 255;
} catch (error) {
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 0;
data[i + 3] = 255;
}
}
}
}
private canUseSIMD(): boolean {
return typeof WebAssembly !== 'undefined' && WebAssembly.validate &&
new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).every((byte, i) => byte === [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00][i]);
}
private renderWithSIMD(data: Uint8ClampedArray, width: number, height: number, time: number, renderMode: string, message: WorkerMessage, startTime: number, maxRenderTime: number): void {
const chunkSize = 4; // Process 4 pixels at once
for (let y = 0; y < height; y++) {
if (performance.now() - startTime > maxRenderTime) {
this.fillRemainingPixels(data, width, height, y, 0);
break;
}
for (let x = 0; x < width; x += chunkSize) {
const endX = Math.min(x + chunkSize, width);
const xValues = new Float32Array(chunkSize);
const yValues = new Float32Array(chunkSize);
const results = new Float32Array(chunkSize);
for (let i = 0; i < endX - x; i++) {
xValues[i] = x + i;
yValues[i] = y;
}
this.computeChunkSIMD(xValues, yValues, results, endX - x, time, message);
for (let i = 0; i < endX - x; i++) {
const pixelX = x + i;
const pixelI = (y * width + pixelX) * 4;
const safeValue = isFinite(results[i]) ? results[i] : 0;
const [r, g, b] = this.calculateColor(safeValue, renderMode);
data[pixelI] = r;
data[pixelI + 1] = g;
data[pixelI + 2] = b;
data[pixelI + 3] = 255;
}
}
}
}
private computeChunkSIMD(xValues: Float32Array, yValues: Float32Array, results: Float32Array, count: number, time: number, message: WorkerMessage): void {
for (let i = 0; i < count; i++) {
try {
const pixelIndex = yValues[i] * (xValues.length / count) + xValues[i];
results[i] = this.compiledFunction!(
xValues[i], yValues[i], time, pixelIndex,
message.mouseX || 0, message.mouseY || 0,
message.mousePressed || false,
message.mouseVX || 0, message.mouseVY || 0,
message.mouseClickTime || 0,
message.touchCount || 0,
message.touch0X || 0, message.touch0Y || 0,
message.touch1X || 0, message.touch1Y || 0,
message.pinchScale || 1, message.pinchRotation || 0,
message.accelX || 0, message.accelY || 0, message.accelZ || 0,
message.gyroX || 0, message.gyroY || 0, message.gyroZ || 0,
message.audioLevel || 0, message.bassLevel || 0, message.midLevel || 0, message.trebleLevel || 0
);
} catch (error) {
results[i] = 0;
}
}
}
private renderSerial(data: Uint8ClampedArray, width: number, height: number, time: number, renderMode: string, message: WorkerMessage, startTime: number, maxRenderTime: number): void {
for (let y = 0; y < height; y++) {
if (performance.now() - startTime > maxRenderTime) {
this.fillRemainingPixels(data, width, height, y, 0);
break;
}
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
const pixelIndex = y * width + x;
try {
const value = this.compiledFunction!(
x, y, time, pixelIndex,
message.mouseX || 0, message.mouseY || 0,
message.mousePressed || false,
message.mouseVX || 0, message.mouseVY || 0,
message.mouseClickTime || 0,
message.touchCount || 0,
message.touch0X || 0, message.touch0Y || 0,
message.touch1X || 0, message.touch1Y || 0,
message.pinchScale || 1, message.pinchRotation || 0,
message.accelX || 0, message.accelY || 0, message.accelZ || 0,
message.gyroX || 0, message.gyroY || 0, message.gyroZ || 0,
message.audioLevel || 0, message.bassLevel || 0, message.midLevel || 0, message.trebleLevel || 0
);
const safeValue = isFinite(value) ? value : 0;
const [r, g, b] = this.calculateColor(safeValue, renderMode);
data[i] = r;
data[i + 1] = g;
data[i + 2] = b;
data[i + 3] = 255;
} catch (error) {
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 0;
data[i + 3] = 255;
}
}
}
}
private fillRemainingPixels(data: Uint8ClampedArray, width: number, height: number, startY: number, startX: number): void {
for (let remainingY = startY; remainingY < height; remainingY++) {
const xStart = remainingY === startY ? startX : 0;
for (let remainingX = xStart; remainingX < width; remainingX++) {
const i = (remainingY * width + remainingX) * 4;
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 0;
data[i + 3] = 255;
}
}
}
private getOrCreateImageData(width: number, height: number): ImageData {
const key = `${width}x${height}`;
let imageData = this.imageDataCache.get(key);
if (!imageData) {
imageData = new ImageData(width, height);
this.imageDataCache.set(key, imageData);
// Limit cache size to prevent memory bloat
if (this.imageDataCache.size > 5) {
const firstKey = this.imageDataCache.keys().next().value;
this.imageDataCache.delete(firstKey);
}
}
return imageData;
}
private calculateColor(value: number, renderMode: string): [number, number, number] {
const absValue = Math.abs(value) % 256;
// Use pre-computed color table if available
const colorTable = this.colorTables.get(renderMode);
if (colorTable) {
const index = Math.floor(absValue) * 3;
return [colorTable[index], colorTable[index + 1], colorTable[index + 2]];
}
// Fallback to direct calculation
return this.calculateColorDirect(absValue, renderMode);
}
private calculateColorDirect(absValue: number, renderMode: string): [number, number, number] {
switch (renderMode) {
case 'classic':
return [