@genart-dev/core 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +92 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -7
- package/dist/index.d.ts +10 -7
- package/dist/index.js +93 -10
- package/dist/index.js.map +1 -1
- package/package.json +13 -10
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/sketch/adapters/p5.ts","../src/sketch/adapters/canvas2d.ts","../src/sketch/adapters/three.ts","../src/sketch/adapters/glsl.ts","../src/sketch/adapters/svg.ts","../src/sketch/registry.ts","../src/skill/skills.ts","../src/skill/registry.ts"],"sourcesContent":["// Re-export all format types and utilities for convenience\n// Consumers of @genart-dev/core get the full format API without a separate import\nexport * from \"@genart-dev/format\";\n\n// Core types (runtime interfaces not in the format package)\nexport type {\n SkillDefinition,\n SkillReference,\n ValidationResult,\n CompiledAlgorithm,\n RuntimeDependency,\n CaptureOptions,\n RendererAdapter,\n SketchInstance,\n} from \"./types.js\";\n\n// Renderer adapters\nexport {\n P5RendererAdapter,\n Canvas2DRendererAdapter,\n ThreeRendererAdapter,\n GLSLRendererAdapter,\n SVGRendererAdapter,\n} from \"./sketch/adapters/index.js\";\nexport { hexToVec3 } from \"./sketch/adapters/glsl.js\";\n\n// Renderer registry\nexport {\n RendererRegistry,\n createDefaultRegistry,\n} from \"./sketch/registry.js\";\n\n// Skill system\nexport {\n SkillRegistry,\n createDefaultSkillRegistry,\n COMPOSITION_SKILLS,\n COLOR_SKILLS,\n} from \"./skill/index.js\";\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\n\nconst P5_CDN_VERSION = \"1.11.3\";\nconst P5_CDN_URL = `https://cdnjs.cloudflare.com/ajax/libs/p5.js/${P5_CDN_VERSION}/p5.min.js`;\n\n/**\n * Compiled p5 algorithm — wraps the algorithm source string\n * and a factory function for creating p5 instance-mode sketches.\n */\ninterface P5CompiledAlgorithm {\n source: string;\n factory: (p: unknown, state: SketchState) => unknown;\n}\n\n/**\n * P5 Renderer Adapter — full implementation.\n *\n * Validates algorithms for the `sketch(p, state)` instance-mode signature,\n * compiles them into executable factories, and creates live sketch instances.\n */\nexport class P5RendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"p5\";\n readonly displayName = \"p5.js\";\n readonly algorithmLanguage = \"javascript\" as const;\n\n validate(algorithm: string): ValidationResult {\n const errors: string[] = [];\n\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n\n // Check for the instance-mode sketch function signature\n const hasSketchFn =\n /function\\s+sketch\\s*\\(\\s*p\\s*,\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*(?:function\\s*)?\\(\\s*p\\s*,\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*\\(\\s*p\\s*,\\s*state\\s*\\)\\s*=>/.test(algorithm);\n\n if (!hasSketchFn) {\n errors.push(\n 'p5 algorithms must export a function with signature: function sketch(p, state)',\n );\n }\n\n // Check for p.setup assignment\n const hasSetup = /p\\s*\\.\\s*setup\\s*=/.test(algorithm);\n if (!hasSetup) {\n errors.push(\"p5 algorithms must assign p.setup\");\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n async compile(algorithm: string): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `p5 compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n // Wrap the algorithm source into a factory function\n // The factory takes (p, state) and returns the sketch module\n const wrappedSource = `\n return (function() {\n ${algorithm}\n return sketch;\n })();\n `;\n\n try {\n const factory = new Function(wrappedSource) as () => (\n p: unknown,\n state: SketchState,\n ) => unknown;\n const compiled: P5CompiledAlgorithm = {\n source: algorithm,\n factory: factory(),\n };\n return compiled;\n } catch (err) {\n throw new Error(\n `p5 compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { factory } = compiled as P5CompiledAlgorithm;\n\n let p5Instance: Record<string, unknown> | null = null;\n let container: HTMLElement | null = null;\n let currentState = { ...state };\n let animating = true;\n let sketchModule: Record<string, unknown> | null = null;\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n\n // Requires p5 to be available globally or as a module\n const P5Constructor = (globalThis as Record<string, unknown>)[\n \"p5\"\n ] as new (\n sketch: (p: Record<string, unknown>) => void,\n container: HTMLElement,\n ) => Record<string, unknown>;\n\n if (!P5Constructor) {\n throw new Error(\n \"p5.js is not loaded. Include p5.js before mounting a p5 sketch.\",\n );\n }\n\n p5Instance = new P5Constructor((p: Record<string, unknown>) => {\n sketchModule = factory(p, currentState) as Record<string, unknown>;\n }, el);\n },\n\n unmount() {\n if (p5Instance && typeof p5Instance[\"remove\"] === \"function\") {\n (p5Instance[\"remove\"] as () => void)();\n }\n p5Instance = null;\n sketchModule = null;\n container = null;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState };\n if (\n sketchModule &&\n typeof sketchModule[\"initializeSystem\"] === \"function\"\n ) {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n redraw() {\n if (p5Instance && typeof p5Instance[\"redraw\"] === \"function\") {\n (p5Instance[\"redraw\"] as () => void)();\n }\n },\n\n pause() {\n animating = false;\n if (p5Instance && typeof p5Instance[\"noLoop\"] === \"function\") {\n (p5Instance[\"noLoop\"] as () => void)();\n }\n },\n\n resume() {\n animating = true;\n if (p5Instance && typeof p5Instance[\"loop\"] === \"function\") {\n (p5Instance[\"loop\"] as () => void)();\n }\n },\n\n get isAnimating() {\n return animating;\n },\n\n async captureFrame(options?: CaptureOptions): Promise<string> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const canvasEl = container.querySelector(\"canvas\");\n if (!canvasEl) throw new Error(\"No canvas element found\");\n\n const format = options?.format ?? \"png\";\n const quality = options?.quality ?? 1.0;\n const mimeType =\n format === \"jpeg\"\n ? \"image/jpeg\"\n : format === \"webp\"\n ? \"image/webp\"\n : \"image/png\";\n\n return canvasEl.toDataURL(mimeType, quality);\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const canvasEl = container.querySelector(\"canvas\");\n if (!canvasEl) throw new Error(\"No canvas element found\");\n const ctx = canvasEl.getContext(\"2d\");\n if (!ctx) throw new Error(\"Cannot get 2D context from canvas\");\n return ctx.getImageData(0, 0, canvasEl.width, canvasEl.height);\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n // Offscreen rendering requires a DOM context (browser or jsdom)\n // This creates a temporary container, mounts, captures, and unmounts\n const el = document.createElement(\"div\");\n el.style.position = \"absolute\";\n el.style.left = \"-9999px\";\n document.body.appendChild(el);\n\n try {\n const instance = this.createInstance(compiled, state, canvas);\n instance.mount(el);\n\n // Wait for setup to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n\n const dataUrl = await instance.captureFrame(options);\n instance.dispose();\n\n // Convert data URL to Uint8Array\n const base64 = dataUrl.split(\",\")[1] ?? \"\";\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n } finally {\n document.body.removeChild(el);\n }\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const pixelDensity = sketch.canvas.pixelDensity ?? 1;\n\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n // Build a keyed COLORS object from ColorDef keys → colorPalette values\n // so algorithms can use state.COLORS.bg instead of state.colorPalette[0].\n const colorsMap: Record<string, string> = {};\n for (let i = 0; i < sketch.colors.length; i++) {\n const colorDef = sketch.colors[i];\n if (colorDef) {\n colorsMap[colorDef.key] = sketch.state.colorPalette[i] ?? \"#000000\";\n }\n }\n const colorsJson = JSON.stringify(colorsMap);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <script src=\"${P5_CDN_URL}\"></script>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #111; }\n #canvas-container canvas { display: block; max-width: 100vw; max-height: 100vh; }\n </style>\n</head>\n<body>\n <div id=\"canvas-container\"></div>\n <script>\n const state = ${stateJson};\n state.canvas = { width: ${width}, height: ${height}, pixelDensity: ${pixelDensity} };\n // Convenience aliases — algorithms may use either naming convention\n state.WIDTH = ${width};\n state.HEIGHT = ${height};\n state.SEED = state.seed;\n state.PARAMS = state.params;\n state.COLORS = ${colorsJson};\n\n ${sketch.algorithm}\n\n new p5(function(p) {\n sketch(p, state);\n }, document.getElementById('canvas-container'));\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `function sketch(p, state) {\n const { WIDTH, HEIGHT, SEED, PARAMS, COLORS } = state;\n p.setup = () => {\n p.createCanvas(WIDTH, HEIGHT);\n p.randomSeed(SEED);\n };\n p.draw = () => {\n p.background(COLORS.background);\n // generative algorithm here\n };\n return { initializeSystem() { /* rebuild from state */ } };\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n return [\n {\n name: \"p5\",\n version: P5_CDN_VERSION,\n cdnUrl: P5_CDN_URL,\n },\n ];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\n\n/**\n * Compiled Canvas 2D algorithm — wraps the algorithm source string\n * and a factory function for creating canvas sketches.\n */\ninterface Canvas2DCompiledAlgorithm {\n source: string;\n factory: (\n ctx: CanvasRenderingContext2D,\n state: SketchState,\n ) => Record<string, unknown>;\n}\n\n/**\n * Canvas 2D Renderer Adapter — full implementation.\n *\n * Validates algorithms for the `sketch(ctx, state)` function signature,\n * compiles them into executable factories, and creates live sketch instances.\n */\nexport class Canvas2DRendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"canvas2d\";\n readonly displayName = \"Canvas 2D\";\n readonly algorithmLanguage = \"javascript\" as const;\n\n validate(algorithm: string): ValidationResult {\n const errors: string[] = [];\n\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n\n // Check for the canvas2d sketch function signature\n const hasSketchFn =\n /function\\s+sketch\\s*\\(\\s*ctx\\s*,\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*(?:function\\s*)?\\(\\s*ctx\\s*,\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*\\(\\s*ctx\\s*,\\s*state\\s*\\)\\s*=>/.test(algorithm);\n\n if (!hasSketchFn) {\n errors.push(\n 'Canvas 2D algorithms must export a function with signature: function sketch(ctx, state)',\n );\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n async compile(algorithm: string): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `Canvas 2D compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const wrappedSource = `\n return (function() {\n ${algorithm}\n return sketch;\n })();\n `;\n\n try {\n const factory = new Function(wrappedSource) as () => (\n ctx: CanvasRenderingContext2D,\n state: SketchState,\n ) => Record<string, unknown>;\n const compiled: Canvas2DCompiledAlgorithm = {\n source: algorithm,\n factory: factory(),\n };\n return compiled;\n } catch (err) {\n throw new Error(\n `Canvas 2D compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { factory } = compiled as Canvas2DCompiledAlgorithm;\n\n let canvasEl: HTMLCanvasElement | null = null;\n let ctx: CanvasRenderingContext2D | null = null;\n let container: HTMLElement | null = null;\n let currentState = { ...state };\n let animating = false;\n let animationFrameId: number | null = null;\n let sketchModule: Record<string, unknown> | null = null;\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n canvasEl = document.createElement(\"canvas\");\n canvasEl.width = canvas.width;\n canvasEl.height = canvas.height;\n\n const density = canvas.pixelDensity ?? 1;\n if (density !== 1) {\n canvasEl.width = canvas.width * density;\n canvasEl.height = canvas.height * density;\n canvasEl.style.width = `${canvas.width}px`;\n canvasEl.style.height = `${canvas.height}px`;\n }\n\n el.appendChild(canvasEl);\n ctx = canvasEl.getContext(\"2d\");\n if (!ctx) throw new Error(\"Failed to get 2D rendering context\");\n\n if (density !== 1) {\n ctx.scale(density, density);\n }\n\n sketchModule = factory(ctx, currentState);\n if (sketchModule && typeof sketchModule[\"initializeSystem\"] === \"function\") {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n unmount() {\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n if (canvasEl && container) {\n container.removeChild(canvasEl);\n }\n canvasEl = null;\n ctx = null;\n container = null;\n sketchModule = null;\n animating = false;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState };\n if (sketchModule && typeof sketchModule[\"initializeSystem\"] === \"function\") {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n redraw() {\n if (sketchModule && typeof sketchModule[\"initializeSystem\"] === \"function\") {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n pause() {\n animating = false;\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n },\n\n resume() {\n animating = true;\n if (sketchModule && typeof sketchModule[\"draw\"] === \"function\") {\n const loop = () => {\n if (!animating) return;\n (sketchModule![\"draw\"] as () => void)();\n animationFrameId = requestAnimationFrame(loop);\n };\n loop();\n }\n },\n\n get isAnimating() {\n return animating;\n },\n\n async captureFrame(options?: CaptureOptions): Promise<string> {\n if (!canvasEl) throw new Error(\"Sketch is not mounted\");\n const format = options?.format ?? \"png\";\n const quality = options?.quality ?? 1.0;\n const mimeType =\n format === \"jpeg\"\n ? \"image/jpeg\"\n : format === \"webp\"\n ? \"image/webp\"\n : \"image/png\";\n return canvasEl.toDataURL(mimeType, quality);\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!canvasEl || !ctx) throw new Error(\"Sketch is not mounted\");\n return ctx.getImageData(0, 0, canvasEl.width, canvasEl.height);\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n const el = document.createElement(\"div\");\n el.style.position = \"absolute\";\n el.style.left = \"-9999px\";\n document.body.appendChild(el);\n\n try {\n const instance = this.createInstance(compiled, state, canvas);\n instance.mount(el);\n\n await new Promise((resolve) => setTimeout(resolve, 50));\n\n const dataUrl = await instance.captureFrame(options);\n instance.dispose();\n\n const base64 = dataUrl.split(\",\")[1] ?? \"\";\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n } finally {\n document.body.removeChild(el);\n }\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const pixelDensity = sketch.canvas.pixelDensity ?? 1;\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n html, body { width: 100%; height: 100%; overflow: hidden; background: #111; }\n body { display: flex; justify-content: center; align-items: center; }\n canvas { display: block; }\n </style>\n</head>\n<body>\n <canvas id=\"canvas\" width=\"${width * pixelDensity}\" height=\"${height * pixelDensity}\" style=\"width:${width}px;height:${height}px;\"></canvas>\n <script>\n try {\n const state = ${stateJson};\n state.canvas = { width: ${width}, height: ${height}, pixelDensity: ${pixelDensity} };\n\n ${sketch.algorithm}\n\n const canvas = document.getElementById('canvas');\n const ctx = canvas.getContext('2d');\n ${pixelDensity !== 1 ? `ctx.scale(${pixelDensity}, ${pixelDensity});` : \"\"}\n const module = sketch(ctx, state);\n if (module && module.initializeSystem) module.initializeSystem();\n } catch (e) {\n document.body.style.background = '#300';\n document.body.style.color = '#f88';\n document.body.style.fontFamily = 'monospace';\n document.body.style.fontSize = '12px';\n document.body.style.padding = '16px';\n document.body.textContent = 'Sketch error: ' + e.message;\n }\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `function sketch(ctx, state) {\n const { width, height } = state.canvas;\n function initializeSystem() {\n ctx.clearRect(0, 0, width, height);\n // generative algorithm here\n }\n return { initializeSystem };\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n // Canvas 2D has no external dependencies\n return [];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\n\nconst THREE_CDN_VERSION = \"0.172.0\";\nconst THREE_CDN_URL = `https://cdn.jsdelivr.net/npm/three@${THREE_CDN_VERSION}/build/three.module.min.js`;\n\n/**\n * Compiled Three.js algorithm — wraps the algorithm source string\n * and a factory function for creating Three.js sketches.\n */\ninterface ThreeCompiledAlgorithm {\n source: string;\n factory: (\n THREE: unknown,\n state: SketchState & { canvas: CanvasSpec },\n container: HTMLElement,\n ) => Record<string, unknown>;\n}\n\n/**\n * Three.js Renderer Adapter — full implementation.\n *\n * Validates algorithms for the `sketch(THREE, state, container)` signature,\n * compiles them into executable factories, and creates live sketch instances.\n */\nexport class ThreeRendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"three\";\n readonly displayName = \"Three.js\";\n readonly algorithmLanguage = \"javascript\" as const;\n\n validate(algorithm: string): ValidationResult {\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n // Basic validation — check for sketch function signature\n const hasSketchFn =\n /function\\s+sketch\\s*\\(\\s*THREE\\s*,\\s*state\\s*,\\s*container\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*(?:function\\s*)?\\(\\s*THREE\\s*,\\s*state\\s*,\\s*container\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*\\(\\s*THREE\\s*,\\s*state\\s*,\\s*container\\s*\\)\\s*=>/.test(algorithm);\n\n if (!hasSketchFn) {\n return {\n valid: false,\n errors: [\n \"Three.js algorithms must export a function with signature: function sketch(THREE, state, container)\",\n ],\n };\n }\n return { valid: true, errors: [] };\n }\n\n async compile(algorithm: string): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `Three.js compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const wrappedSource = `\n return (function() {\n ${algorithm}\n return sketch;\n })();\n `;\n\n try {\n const factory = new Function(wrappedSource) as () => (\n THREE: unknown,\n state: SketchState & { canvas: CanvasSpec },\n container: HTMLElement,\n ) => Record<string, unknown>;\n const compiled: ThreeCompiledAlgorithm = {\n source: algorithm,\n factory: factory(),\n };\n return compiled;\n } catch (err) {\n throw new Error(\n `Three.js compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { factory } = compiled as ThreeCompiledAlgorithm;\n\n let container: HTMLElement | null = null;\n let currentState = { ...state, canvas };\n let sketchModule: Record<string, unknown> | null = null;\n let animating = false;\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n\n // Requires THREE to be available globally\n const THREEGlobal = (globalThis as Record<string, unknown>)[\"THREE\"];\n\n if (!THREEGlobal) {\n throw new Error(\n \"Three.js is not loaded. Include Three.js before mounting a Three.js sketch.\",\n );\n }\n\n sketchModule = factory(THREEGlobal, currentState, el);\n animating = true;\n },\n\n unmount() {\n if (\n sketchModule &&\n typeof sketchModule[\"dispose\"] === \"function\"\n ) {\n (sketchModule[\"dispose\"] as () => void)();\n }\n if (container) {\n container.innerHTML = \"\";\n }\n sketchModule = null;\n container = null;\n animating = false;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState, canvas };\n if (\n sketchModule &&\n typeof sketchModule[\"initializeSystem\"] === \"function\"\n ) {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n redraw() {\n if (\n sketchModule &&\n typeof sketchModule[\"initializeSystem\"] === \"function\"\n ) {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n pause() {\n animating = false;\n if (\n sketchModule &&\n typeof sketchModule[\"pause\"] === \"function\"\n ) {\n (sketchModule[\"pause\"] as () => void)();\n }\n },\n\n resume() {\n animating = true;\n if (\n sketchModule &&\n typeof sketchModule[\"resume\"] === \"function\"\n ) {\n (sketchModule[\"resume\"] as () => void)();\n }\n },\n\n get isAnimating() {\n return animating;\n },\n\n async captureFrame(options?: CaptureOptions): Promise<string> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const canvasEl = container.querySelector(\"canvas\");\n if (!canvasEl) throw new Error(\"No canvas element found\");\n\n const format = options?.format ?? \"png\";\n const quality = options?.quality ?? 1.0;\n const mimeType =\n format === \"jpeg\"\n ? \"image/jpeg\"\n : format === \"webp\"\n ? \"image/webp\"\n : \"image/png\";\n\n return canvasEl.toDataURL(mimeType, quality);\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const canvasEl = container.querySelector(\"canvas\");\n if (!canvasEl) throw new Error(\"No canvas element found\");\n const ctx = canvasEl.getContext(\"2d\");\n if (!ctx) throw new Error(\"Cannot get 2D context from canvas\");\n return ctx.getImageData(0, 0, canvasEl.width, canvasEl.height);\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n const el = document.createElement(\"div\");\n el.style.position = \"absolute\";\n el.style.left = \"-9999px\";\n document.body.appendChild(el);\n\n try {\n const instance = this.createInstance(compiled, state, canvas);\n instance.mount(el);\n\n // Three.js scenes need more setup time\n await new Promise((resolve) => setTimeout(resolve, 200));\n\n const dataUrl = await instance.captureFrame(options);\n instance.dispose();\n\n const base64 = dataUrl.split(\",\")[1] ?? \"\";\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n } finally {\n document.body.removeChild(el);\n }\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const pixelDensity = sketch.canvas.pixelDensity ?? 1;\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #111; overflow: hidden; }\n #canvas-container { width: ${width}px; height: ${height}px; }\n #canvas-container canvas { display: block; max-width: 100vw; max-height: 100vh; }\n </style>\n</head>\n<body>\n <div id=\"canvas-container\"></div>\n <script type=\"module\">\n import * as THREE from '${THREE_CDN_URL}';\n\n const state = ${stateJson};\n state.canvas = { width: ${width}, height: ${height}, pixelDensity: ${pixelDensity} };\n\n ${sketch.algorithm}\n\n sketch(THREE, state, document.getElementById('canvas-container'));\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `function sketch(THREE, state, container) {\n const scene = new THREE.Scene();\n const camera = new THREE.PerspectiveCamera(75, state.canvas.width / state.canvas.height, 0.1, 1000);\n const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });\n renderer.setSize(state.canvas.width, state.canvas.height);\n container.appendChild(renderer.domElement);\n camera.position.z = 5;\n\n let animating = true;\n let animId = null;\n\n function initializeSystem() {\n // Rebuild scene from state.params and state.seed\n while (scene.children.length > 0) scene.remove(scene.children[0]);\n const geometry = new THREE.BoxGeometry();\n const material = new THREE.MeshBasicMaterial({ color: 0x22d3ee });\n const cube = new THREE.Mesh(geometry, material);\n scene.add(cube);\n }\n\n function animate() {\n if (!animating) return;\n animId = requestAnimationFrame(animate);\n renderer.render(scene, camera);\n }\n\n function pause() {\n animating = false;\n if (animId !== null) cancelAnimationFrame(animId);\n }\n\n function resume() {\n animating = true;\n animate();\n }\n\n function dispose() {\n pause();\n renderer.dispose();\n container.removeChild(renderer.domElement);\n }\n\n initializeSystem();\n animate();\n\n return { initializeSystem, dispose, pause, resume };\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n return [\n {\n name: \"three\",\n version: THREE_CDN_VERSION,\n cdnUrl: THREE_CDN_URL,\n },\n ];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\n\n/** Built-in uniforms that are not mapped from user parameters. */\nconst BUILTIN_UNIFORMS = new Set([\n \"u_resolution\",\n \"u_time\",\n \"u_seed\",\n]);\n\n/** Standard fullscreen quad vertex shader for WebGL2. */\nconst FULLSCREEN_QUAD_VERTEX = `#version 300 es\nin vec2 a_position;\nvoid main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n}`;\n\n/**\n * Compiled GLSL algorithm — contains the fragment and vertex shaders\n * plus extracted uniform name mappings.\n */\ninterface GLSLCompiledAlgorithm {\n fragmentSource: string;\n vertexSource: string;\n uniformNames: {\n params: string[];\n colors: string[];\n };\n}\n\n/**\n * Parse a hex color string to RGB floats in [0, 1] range.\n * Accepts \"#rrggbb\" or \"rrggbb\" format.\n */\nexport function hexToVec3(hex: string): [number, number, number] {\n const clean = hex.replace(/^#/, \"\");\n const r = parseInt(clean.substring(0, 2), 16) / 255;\n const g = parseInt(clean.substring(2, 4), 16) / 255;\n const b = parseInt(clean.substring(4, 6), 16) / 255;\n return [r, g, b];\n}\n\n/**\n * Extract uniform declarations from GLSL source.\n * Returns uniform names categorized as built-in, param-mapped, or color-mapped.\n */\nfunction extractUniforms(source: string): {\n params: string[];\n colors: string[];\n} {\n const params: string[] = [];\n const colors: string[] = [];\n const uniformRegex = /uniform\\s+(?:float|vec[234]|int|mat[234])\\s+(u_\\w+)/g;\n let match;\n\n while ((match = uniformRegex.exec(source)) !== null) {\n const name = match[1]!;\n if (BUILTIN_UNIFORMS.has(name)) continue;\n // Color uniforms are vec3 named u_color followed by a digit\n if (/^u_color\\d+$/.test(name)) {\n colors.push(name);\n } else {\n params.push(name);\n }\n }\n\n return { params, colors };\n}\n\n/**\n * GLSL Renderer Adapter — full implementation.\n *\n * Validates GLSL fragment shaders, compiles them with a fullscreen quad\n * vertex shader, and creates live sketch instances using WebGL2.\n */\nexport class GLSLRendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"glsl\";\n readonly displayName = \"GLSL Shader\";\n readonly algorithmLanguage = \"glsl\" as const;\n\n validate(algorithm: string): ValidationResult {\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n // Basic GLSL validation — check for version directive and main function\n const hasVersion = /#version\\s+\\d+\\s+es/.test(algorithm);\n const hasMain = /void\\s+main\\s*\\(\\s*\\)/.test(algorithm);\n const hasFragColor =\n /fragColor/.test(algorithm) || /gl_FragColor/.test(algorithm);\n\n const errors: string[] = [];\n if (!hasVersion) {\n errors.push(\"GLSL shaders should start with a #version directive (e.g., #version 300 es)\");\n }\n if (!hasMain) {\n errors.push(\"GLSL shaders must contain a void main() function\");\n }\n if (!hasFragColor) {\n errors.push(\"GLSL shaders must write to fragColor or gl_FragColor\");\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n async compile(algorithm: string): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `GLSL compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const uniforms = extractUniforms(algorithm);\n\n const compiled: GLSLCompiledAlgorithm = {\n fragmentSource: algorithm,\n vertexSource: FULLSCREEN_QUAD_VERTEX,\n uniformNames: uniforms,\n };\n\n return compiled;\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { fragmentSource, vertexSource, uniformNames } =\n compiled as GLSLCompiledAlgorithm;\n\n let canvasEl: HTMLCanvasElement | null = null;\n let gl: WebGL2RenderingContext | null = null;\n let program: WebGLProgram | null = null;\n let vao: WebGLVertexArrayObject | null = null;\n let positionBuffer: WebGLBuffer | null = null;\n let container: HTMLElement | null = null;\n let currentState = { ...state };\n let animating = false;\n let animationFrameId: number | null = null;\n let startTime = 0;\n\n function compileShader(\n glCtx: WebGL2RenderingContext,\n type: number,\n source: string,\n ): WebGLShader {\n const shader = glCtx.createShader(type);\n if (!shader) throw new Error(\"Failed to create shader\");\n glCtx.shaderSource(shader, source);\n glCtx.compileShader(shader);\n if (!glCtx.getShaderParameter(shader, glCtx.COMPILE_STATUS)) {\n const info = glCtx.getShaderInfoLog(shader);\n glCtx.deleteShader(shader);\n throw new Error(`Shader compilation error: ${info}`);\n }\n return shader;\n }\n\n function bindUniforms(glCtx: WebGL2RenderingContext, prog: WebGLProgram) {\n // Built-in uniforms\n const resLoc = glCtx.getUniformLocation(prog, \"u_resolution\");\n if (resLoc) {\n glCtx.uniform2f(resLoc, canvas.width, canvas.height);\n }\n\n const seedLoc = glCtx.getUniformLocation(prog, \"u_seed\");\n if (seedLoc) {\n glCtx.uniform1f(seedLoc, currentState.seed);\n }\n\n const timeLoc = glCtx.getUniformLocation(prog, \"u_time\");\n if (timeLoc) {\n const elapsed = (performance.now() - startTime) / 1000;\n glCtx.uniform1f(timeLoc, elapsed);\n }\n\n // Parameter uniforms: u_paramName → state.params[paramName]\n for (const uName of uniformNames.params) {\n const loc = glCtx.getUniformLocation(prog, uName);\n if (!loc) continue;\n // Strip u_ prefix to get param key\n const paramKey = uName.substring(2);\n const value = currentState.params[paramKey];\n if (value !== undefined) {\n glCtx.uniform1f(loc, value);\n }\n }\n\n // Color uniforms: u_color1 → state.colorPalette[0], etc.\n for (const uName of uniformNames.colors) {\n const loc = glCtx.getUniformLocation(prog, uName);\n if (!loc) continue;\n // Extract 1-indexed number from u_colorN\n const idx = parseInt(uName.replace(\"u_color\", \"\"), 10) - 1;\n const hex = currentState.colorPalette[idx];\n if (hex) {\n const [r, g, b] = hexToVec3(hex);\n glCtx.uniform3f(loc, r, g, b);\n }\n }\n }\n\n function renderFrame() {\n if (!gl || !program || !vao) return;\n\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.useProgram(program);\n bindUniforms(gl, program);\n\n gl.bindVertexArray(vao);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n gl.bindVertexArray(null);\n }\n\n function animationLoop() {\n if (!animating) return;\n renderFrame();\n animationFrameId = requestAnimationFrame(animationLoop);\n }\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n canvasEl = document.createElement(\"canvas\");\n canvasEl.width = canvas.width;\n canvasEl.height = canvas.height;\n\n const density = canvas.pixelDensity ?? 1;\n if (density !== 1) {\n canvasEl.width = canvas.width * density;\n canvasEl.height = canvas.height * density;\n canvasEl.style.width = `${canvas.width}px`;\n canvasEl.style.height = `${canvas.height}px`;\n }\n\n el.appendChild(canvasEl);\n\n gl = canvasEl.getContext(\"webgl2\", {\n preserveDrawingBuffer: true,\n });\n if (!gl) throw new Error(\"WebGL2 is not supported\");\n\n // Compile and link shaders\n const vertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSource);\n const fragShader = compileShader(\n gl,\n gl.FRAGMENT_SHADER,\n fragmentSource,\n );\n\n program = gl.createProgram();\n if (!program) throw new Error(\"Failed to create WebGL program\");\n gl.attachShader(program, vertShader);\n gl.attachShader(program, fragShader);\n gl.linkProgram(program);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const info = gl.getProgramInfoLog(program);\n throw new Error(`Program linking error: ${info}`);\n }\n\n // Clean up individual shaders (linked into program)\n gl.deleteShader(vertShader);\n gl.deleteShader(fragShader);\n\n // Set up fullscreen quad (two triangles covering clip space)\n // prettier-ignore\n const positions = new Float32Array([\n -1, -1, 1, -1, -1, 1,\n -1, 1, 1, -1, 1, 1,\n ]);\n\n positionBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);\n\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n const aPosition = gl.getAttribLocation(program, \"a_position\");\n gl.enableVertexAttribArray(aPosition);\n gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);\n\n gl.bindVertexArray(null);\n\n startTime = performance.now();\n animating = true;\n animationLoop();\n },\n\n unmount() {\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n animating = false;\n\n if (gl) {\n if (vao) gl.deleteVertexArray(vao);\n if (positionBuffer) gl.deleteBuffer(positionBuffer);\n if (program) gl.deleteProgram(program);\n }\n\n if (canvasEl && container) {\n container.removeChild(canvasEl);\n }\n\n gl = null;\n program = null;\n vao = null;\n positionBuffer = null;\n canvasEl = null;\n container = null;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState };\n // Uniforms are rebound on the next frame\n if (!animating) {\n renderFrame();\n }\n },\n\n redraw() {\n renderFrame();\n },\n\n pause() {\n animating = false;\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n },\n\n resume() {\n if (!animating) {\n animating = true;\n animationLoop();\n }\n },\n\n get isAnimating() {\n return animating;\n },\n\n async captureFrame(options?: CaptureOptions): Promise<string> {\n if (!canvasEl) throw new Error(\"Sketch is not mounted\");\n const format = options?.format ?? \"png\";\n const quality = options?.quality ?? 1.0;\n const mimeType =\n format === \"jpeg\"\n ? \"image/jpeg\"\n : format === \"webp\"\n ? \"image/webp\"\n : \"image/png\";\n return canvasEl.toDataURL(mimeType, quality);\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!canvasEl || !gl) throw new Error(\"Sketch is not mounted\");\n\n const width = gl.drawingBufferWidth;\n const height = gl.drawingBufferHeight;\n const pixels = new Uint8Array(width * height * 4);\n gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);\n\n // WebGL pixels are bottom-up — flip vertically\n const flipped = new Uint8Array(width * height * 4);\n const rowSize = width * 4;\n for (let y = 0; y < height; y++) {\n const srcOffset = y * rowSize;\n const dstOffset = (height - 1 - y) * rowSize;\n flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);\n }\n\n return new ImageData(\n new Uint8ClampedArray(flipped.buffer),\n width,\n height,\n );\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n const el = document.createElement(\"div\");\n el.style.position = \"absolute\";\n el.style.left = \"-9999px\";\n document.body.appendChild(el);\n\n try {\n const instance = this.createInstance(compiled, state, canvas);\n instance.mount(el);\n\n // Wait for initial render\n await new Promise((resolve) => setTimeout(resolve, 50));\n\n const dataUrl = await instance.captureFrame(options);\n instance.dispose();\n\n const base64 = dataUrl.split(\",\")[1] ?? \"\";\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n } finally {\n document.body.removeChild(el);\n }\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const pixelDensity = sketch.canvas.pixelDensity ?? 1;\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n // Extract uniforms from the fragment shader for binding code\n const uniforms = extractUniforms(sketch.algorithm);\n const paramBindings = uniforms.params\n .map((u) => {\n const key = u.substring(2); // strip u_ prefix\n return ` { const loc = gl.getUniformLocation(program, \"${u}\"); if (loc && state.params[\"${key}\"] !== undefined) gl.uniform1f(loc, state.params[\"${key}\"]); }`;\n })\n .join(\"\\n\");\n\n const colorBindings = uniforms.colors\n .map((u) => {\n const idx = parseInt(u.replace(\"u_color\", \"\"), 10) - 1;\n return ` { const loc = gl.getUniformLocation(program, \"${u}\"); if (loc && state.colorPalette[${idx}]) { const c = state.colorPalette[${idx}].replace('#',''); gl.uniform3f(loc, parseInt(c.substring(0,2),16)/255, parseInt(c.substring(2,4),16)/255, parseInt(c.substring(4,6),16)/255); } }`;\n })\n .join(\"\\n\");\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #111; }\n canvas { display: block; max-width: 100vw; max-height: 100vh; }\n </style>\n</head>\n<body>\n <canvas id=\"canvas\" width=\"${width * pixelDensity}\" height=\"${height * pixelDensity}\" style=\"width:${width}px;height:${height}px;\"></canvas>\n <script>\n const state = ${stateJson};\n\n const canvas = document.getElementById('canvas');\n const gl = canvas.getContext('webgl2', { preserveDrawingBuffer: true });\n if (!gl) { document.body.textContent = 'WebGL2 not supported'; throw new Error('No WebGL2'); }\n\n // Vertex shader: fullscreen quad\n const vertSrc = \\`${FULLSCREEN_QUAD_VERTEX}\\`;\n\n // Fragment shader\n const fragSrc = \\`${sketch.algorithm.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\").replace(/\\$/g, \"\\\\$\")}\\`;\n\n function createShader(type, src) {\n const s = gl.createShader(type);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));\n return s;\n }\n\n const program = gl.createProgram();\n gl.attachShader(program, createShader(gl.VERTEX_SHADER, vertSrc));\n gl.attachShader(program, createShader(gl.FRAGMENT_SHADER, fragSrc));\n gl.linkProgram(program);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program));\n\n const positions = new Float32Array([-1,-1, 1,-1, -1,1, -1,1, 1,-1, 1,1]);\n const buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);\n const vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n const aPos = gl.getAttribLocation(program, 'a_position');\n gl.enableVertexAttribArray(aPos);\n gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);\n gl.bindVertexArray(null);\n\n const startTime = performance.now();\n function render() {\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.useProgram(program);\n\n // Built-in uniforms\n { const loc = gl.getUniformLocation(program, 'u_resolution'); if (loc) gl.uniform2f(loc, ${width}, ${height}); }\n { const loc = gl.getUniformLocation(program, 'u_seed'); if (loc) gl.uniform1f(loc, state.seed); }\n { const loc = gl.getUniformLocation(program, 'u_time'); if (loc) gl.uniform1f(loc, (performance.now() - startTime) / 1000); }\n\n // Parameter uniforms\n${paramBindings}\n\n // Color uniforms\n${colorBindings}\n\n gl.bindVertexArray(vao);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n gl.bindVertexArray(null);\n requestAnimationFrame(render);\n }\n render();\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `#version 300 es\nprecision highp float;\nuniform vec2 u_resolution;\nuniform float u_time;\nuniform float u_seed;\nuniform float u_noiseScale; // mapped from state.params.noiseScale\nuniform vec3 u_color1; // mapped from state.colorPalette[0]\nout vec4 fragColor;\nvoid main() {\n vec2 uv = gl_FragCoord.xy / u_resolution;\n fragColor = vec4(uv, 0.5 + 0.5 * sin(u_time), 1.0);\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n // GLSL runs on WebGL — no external CDN dependency\n return [];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\n\n/**\n * Compiled SVG algorithm — wraps the algorithm source string\n * and a factory function for creating SVG sketches.\n */\ninterface SVGCompiledAlgorithm {\n source: string;\n factory: (\n state: SketchState & { canvas: CanvasSpec },\n ) => Record<string, unknown>;\n}\n\n/**\n * SVG Renderer Adapter — full implementation.\n *\n * Validates algorithms for the `sketch(state)` function signature,\n * compiles them into executable factories, and creates live sketch instances.\n * SVG sketches are static — there is no animation loop.\n */\nexport class SVGRendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"svg\";\n readonly displayName = \"SVG\";\n readonly algorithmLanguage = \"javascript\" as const;\n\n validate(algorithm: string): ValidationResult {\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n // Check for sketch function signature\n const hasSketchFn =\n /function\\s+sketch\\s*\\(\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*(?:function\\s*)?\\(\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*\\(\\s*state\\s*\\)\\s*=>/.test(algorithm);\n\n if (!hasSketchFn) {\n return {\n valid: false,\n errors: [\n \"SVG algorithms must export a function with signature: function sketch(state)\",\n ],\n };\n }\n return { valid: true, errors: [] };\n }\n\n async compile(algorithm: string): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `SVG compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const wrappedSource = `\n return (function() {\n ${algorithm}\n return sketch;\n })();\n `;\n\n try {\n const factory = new Function(wrappedSource) as () => (\n state: SketchState & { canvas: CanvasSpec },\n ) => Record<string, unknown>;\n const compiled: SVGCompiledAlgorithm = {\n source: algorithm,\n factory: factory(),\n };\n return compiled;\n } catch (err) {\n throw new Error(\n `SVG compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { factory } = compiled as SVGCompiledAlgorithm;\n\n let container: HTMLElement | null = null;\n let currentState = { ...state, canvas };\n let sketchModule: Record<string, unknown> | null = null;\n\n function regenerate() {\n if (!container || !sketchModule) return;\n if (typeof sketchModule[\"generate\"] === \"function\") {\n const svgString = (sketchModule[\"generate\"] as () => string)();\n container.innerHTML = svgString;\n }\n }\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n sketchModule = factory(currentState);\n regenerate();\n },\n\n unmount() {\n if (container) {\n container.innerHTML = \"\";\n }\n container = null;\n sketchModule = null;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState, canvas };\n // Recreate the sketch module with the new state\n sketchModule = factory(currentState);\n regenerate();\n },\n\n redraw() {\n regenerate();\n },\n\n pause() {\n // No-op: SVG is static\n },\n\n resume() {\n // No-op: SVG is static\n },\n\n get isAnimating() {\n return false;\n },\n\n async captureFrame(_options?: CaptureOptions): Promise<string> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const svgEl = container.querySelector(\"svg\");\n if (!svgEl) throw new Error(\"No SVG element found\");\n\n const serializer = new XMLSerializer();\n const svgString = serializer.serializeToString(svgEl);\n const base64 = btoa(unescape(encodeURIComponent(svgString)));\n return `data:image/svg+xml;base64,${base64}`;\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const svgEl = container.querySelector(\"svg\");\n if (!svgEl) throw new Error(\"No SVG element found\");\n\n // Render SVG to an offscreen canvas via Image\n const serializer = new XMLSerializer();\n const svgString = serializer.serializeToString(svgEl);\n const blob = new Blob([svgString], { type: \"image/svg+xml\" });\n const url = URL.createObjectURL(blob);\n\n const img = new Image();\n await new Promise<void>((resolve, reject) => {\n img.onload = () => resolve();\n img.onerror = () => reject(new Error(\"Failed to load SVG as image\"));\n img.src = url;\n });\n\n const offscreen = document.createElement(\"canvas\");\n offscreen.width = canvas.width;\n offscreen.height = canvas.height;\n const ctx = offscreen.getContext(\"2d\");\n if (!ctx) throw new Error(\"Cannot get 2D context\");\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n URL.revokeObjectURL(url);\n\n return ctx.getImageData(0, 0, canvas.width, canvas.height);\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n _options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n const { factory } = compiled as SVGCompiledAlgorithm;\n const stateWithCanvas = { ...state, canvas };\n const module = factory(stateWithCanvas);\n\n let svgString: string;\n if (typeof module[\"generate\"] === \"function\") {\n svgString = (module[\"generate\"] as () => string)();\n } else {\n throw new Error(\"SVG sketch module must have a generate() method\");\n }\n\n // Encode SVG string as UTF-8 Uint8Array\n const encoder = new TextEncoder();\n return encoder.encode(svgString);\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #111; }\n #svg-container svg { display: block; width: 100%; height: auto; max-width: 100vw; max-height: 100vh; }\n </style>\n</head>\n<body>\n <div id=\"svg-container\"></div>\n <script>\n const state = ${stateJson};\n state.canvas = { width: ${width}, height: ${height} };\n\n ${sketch.algorithm}\n\n const module = sketch(state);\n const svgString = module.generate ? module.generate() : module.initializeSystem();\n document.getElementById('svg-container').innerHTML = svgString;\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `function sketch(state) {\n const { width, height } = state.canvas;\n function generate() {\n return \\`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"\\${width}\" height=\"\\${height}\" viewBox=\"0 0 \\${width} \\${height}\">\n <!-- generated elements -->\n </svg>\\`;\n }\n return { generate, initializeSystem: generate };\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n // SVG has no external dependencies\n return [];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type { RendererType } from \"@genart-dev/format\";\nimport type { RendererAdapter } from \"../types.js\";\nimport { P5RendererAdapter } from \"./adapters/p5.js\";\nimport { Canvas2DRendererAdapter } from \"./adapters/canvas2d.js\";\nimport { ThreeRendererAdapter } from \"./adapters/three.js\";\nimport { GLSLRendererAdapter } from \"./adapters/glsl.js\";\nimport { SVGRendererAdapter } from \"./adapters/svg.js\";\n\n/**\n * Registry for renderer adapters. Manages registration and lookup\n * of RendererAdapter implementations by renderer type.\n */\nexport class RendererRegistry {\n private readonly adapters = new Map<RendererType, RendererAdapter>();\n private defaultType: RendererType = \"p5\";\n\n /**\n * Register a renderer adapter. Replaces any existing adapter for the same type.\n */\n register(adapter: RendererAdapter): void {\n this.adapters.set(adapter.type, adapter);\n }\n\n /**\n * Resolve a renderer adapter by type.\n * If type is undefined, returns the default adapter (p5 — v1.0 compat).\n *\n * @throws Error if the type is not registered.\n */\n resolve(type?: RendererType): RendererAdapter {\n const resolvedType = type ?? this.defaultType;\n const adapter = this.adapters.get(resolvedType);\n if (!adapter) {\n const available = [...this.adapters.keys()].join(\", \");\n throw new Error(\n `Unknown renderer type \"${resolvedType}\". Registered types: ${available || \"(none)\"}`,\n );\n }\n return adapter;\n }\n\n /**\n * List all registered renderer types.\n */\n list(): RendererType[] {\n return [...this.adapters.keys()];\n }\n\n /**\n * Get the default renderer adapter (p5).\n */\n getDefault(): RendererAdapter {\n return this.resolve(this.defaultType);\n }\n\n /**\n * Check if a renderer type is registered.\n */\n has(type: RendererType): boolean {\n return this.adapters.has(type);\n }\n}\n\n/**\n * Create a RendererRegistry pre-loaded with all 5 renderer adapters.\n * This is the standard way to get a registry instance.\n */\nexport function createDefaultRegistry(): RendererRegistry {\n const registry = new RendererRegistry();\n registry.register(new P5RendererAdapter());\n registry.register(new Canvas2DRendererAdapter());\n registry.register(new ThreeRendererAdapter());\n registry.register(new GLSLRendererAdapter());\n registry.register(new SVGRendererAdapter());\n return registry;\n}\n","import type { SkillDefinition } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Composition Theory Skills (Arnheim, Wong)\n// ---------------------------------------------------------------------------\n\nexport const COMPOSITION_SKILLS: readonly SkillDefinition[] = [\n {\n id: \"golden-ratio\",\n name: \"Golden Ratio\",\n category: \"composition\",\n complexity: \"intermediate\",\n description:\n \"Use the golden ratio (1:1.618) to create naturally harmonious proportions and spiral compositions.\",\n theory: `The golden ratio (phi, approximately 1.618) appears throughout nature and has been used in art and architecture for millennia. In generative art, it provides a mathematical foundation for creating compositions that feel naturally balanced.\n\nThe golden rectangle can be recursively subdivided, creating a spiral that guides the viewer's eye. Elements placed along this spiral or at golden section points create visual harmony without the rigidity of symmetric layouts.\n\nKey applications in generative art:\n- Divide the canvas at golden ratio points (61.8% / 38.2%) for element placement\n- Use the golden spiral as a path for distributing elements\n- Scale recursive elements by phi for self-similar patterns\n- Apply phi to spacing, margins, and proportional relationships`,\n principles: [\n \"Divide compositions at 61.8% / 38.2% rather than halves\",\n \"Place focal elements at golden section intersections\",\n \"Use the golden spiral to guide element distribution\",\n \"Scale nested or recursive elements by phi (1.618) or 1/phi (0.618)\",\n \"Apply golden proportions to negative space as well as positive forms\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n { title: \"Principles of Form and Design\", author: \"Wucius Wong\", year: 1993 },\n ],\n suggestedParameters: [\n { key: \"phi\", label: \"Golden Ratio\", min: 1.0, max: 2.0, step: 0.001, default: 1.618 },\n { key: \"subdivisions\", label: \"Subdivisions\", min: 1, max: 12, step: 1, default: 6 },\n ],\n },\n {\n id: \"rule-of-thirds\",\n name: \"Rule of Thirds\",\n category: \"composition\",\n complexity: \"beginner\",\n description:\n \"Divide the canvas into a 3x3 grid and place key elements at intersection points for dynamic balance.\",\n theory: `The rule of thirds is one of the most fundamental composition techniques. By dividing the canvas into nine equal sections with two horizontal and two vertical lines, artists create four \"power points\" at the intersections where the viewer's eye naturally rests.\n\nIn generative art, this grid serves as an anchor system. Rather than centering elements (which creates static compositions), placing density clusters, color accents, or focal geometries at third-line intersections produces dynamic, engaging layouts.\n\nThis rule also applies to the distribution of visual weight: roughly two-thirds of the canvas can be one tone or density, with the remaining third providing contrast.`,\n principles: [\n \"Place primary focal elements at one of the four intersection points\",\n \"Align dominant lines (horizons, divisions) with the third lines, not center\",\n \"Distribute visual weight asymmetrically: 2/3 to 1/3 ratio\",\n \"Use the grid to create tension between filled and empty areas\",\n \"Multiple elements should occupy different intersection points\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n { title: \"Principles of Form and Design\", author: \"Wucius Wong\", year: 1993 },\n ],\n suggestedParameters: [\n { key: \"gridDivisions\", label: \"Grid Divisions\", min: 2, max: 8, step: 1, default: 3 },\n { key: \"focalStrength\", label: \"Focal Strength\", min: 0.1, max: 1.0, step: 0.1, default: 0.7 },\n ],\n },\n {\n id: \"visual-weight\",\n name: \"Visual Weight & Balance\",\n category: \"composition\",\n complexity: \"intermediate\",\n description:\n \"Create equilibrium through the distribution of visual weight — size, density, color intensity, and position.\",\n theory: `Every visual element carries \"weight\" determined by its size, color intensity, texture density, and position relative to the canvas center. Rudolf Arnheim's research showed that viewers perceive compositions as balanced or imbalanced based on this aggregate weight distribution.\n\nIn generative art, visual weight manifests through:\n- **Size**: Larger elements carry more weight\n- **Value contrast**: High-contrast elements are heavier than low-contrast ones\n- **Color saturation**: Saturated colors are heavier than muted ones\n- **Density**: Clusters of small elements can balance a single large one\n- **Position**: Elements farther from center exert more leverage (like a seesaw)\n\nBalance can be symmetrical (formal, stable), asymmetrical (dynamic, interesting), or radial (emanating from center).`,\n principles: [\n \"A small, high-contrast element can balance a large, low-contrast one\",\n \"Elements farther from the center carry more compositional weight\",\n \"Asymmetrical balance creates more visual interest than symmetry\",\n \"Distribute density gradients to create directional visual flow\",\n \"Empty space (negative space) has visual weight and must be balanced too\",\n \"Color saturation and value contribute independently to perceived weight\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n ],\n suggestedParameters: [\n { key: \"balancePoint\", label: \"Balance Point\", min: 0.2, max: 0.8, step: 0.05, default: 0.5 },\n { key: \"weightContrast\", label: \"Weight Contrast\", min: 0.1, max: 2.0, step: 0.1, default: 1.0 },\n ],\n },\n {\n id: \"gestalt-grouping\",\n name: \"Gestalt Grouping\",\n category: \"composition\",\n complexity: \"intermediate\",\n description:\n \"Apply Gestalt principles — proximity, similarity, closure, continuity — to organize elements into perceived wholes.\",\n theory: `Gestalt psychology reveals how humans perceive visual elements as organized groups rather than isolated parts. These principles are powerful tools for generative artists:\n\n- **Proximity**: Elements close together are perceived as a group. Control spacing to create clusters or separations.\n- **Similarity**: Elements sharing color, size, or shape are grouped. Use gradual variation to create sub-groups.\n- **Closure**: The mind completes incomplete shapes. Leave gaps in patterns — viewers will fill them in.\n- **Continuity**: Elements arranged along a line or curve are perceived as related. Use flow fields or parametric curves.\n- **Figure-Ground**: The relationship between foreground elements and background space defines the composition.\n\nIn generative art, these principles help create readable structure from potentially chaotic algorithms.`,\n principles: [\n \"Use proximity (spacing) as the primary grouping mechanism\",\n \"Vary one property (color, size) while keeping others constant to create similarity groups\",\n \"Leave intentional gaps for the viewer's mind to complete (closure)\",\n \"Arrange elements along implied lines or curves for continuity\",\n \"Ensure clear figure-ground separation at all parameter settings\",\n \"Layer multiple Gestalt principles for complex but readable compositions\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n { title: \"Principles of Form and Design\", author: \"Wucius Wong\", year: 1993 },\n ],\n suggestedParameters: [\n { key: \"groupSpacing\", label: \"Group Spacing\", min: 0.5, max: 5.0, step: 0.1, default: 2.0 },\n { key: \"similarity\", label: \"Similarity\", min: 0.0, max: 1.0, step: 0.05, default: 0.8 },\n { key: \"elementCount\", label: \"Element Count\", min: 10, max: 500, step: 10, default: 100 },\n ],\n },\n {\n id: \"figure-ground\",\n name: \"Figure-Ground Relationship\",\n category: \"composition\",\n complexity: \"beginner\",\n description:\n \"Control the interplay between positive forms (figure) and negative space (ground) for clarity and ambiguity.\",\n theory: `The figure-ground relationship is the most fundamental perceptual organization. Every composition consists of figures (perceived objects) and ground (the space around and between them).\n\nStrong figure-ground contrast creates clarity and focus. Deliberate ambiguity — where figure and ground are interchangeable — creates visual puzzles that engage viewers (as in M.C. Escher's tessellations).\n\nIn generative art, controlling figure-ground means managing:\n- Value contrast between elements and background\n- Edge definition (sharp vs. soft boundaries)\n- Density distribution (clustered elements read as figure)\n- Reversibility (can the viewer flip perception?)`,\n principles: [\n \"Maintain sufficient contrast between figure and ground for readability\",\n \"Use value (light/dark) as the primary figure-ground separator\",\n \"Create deliberate ambiguity for visual interest when appropriate\",\n \"Small enclosed areas tend to be perceived as figure; large areas as ground\",\n \"Convex shapes are more likely perceived as figure than concave ones\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n ],\n suggestedParameters: [\n { key: \"contrast\", label: \"Figure-Ground Contrast\", min: 0.1, max: 1.0, step: 0.05, default: 0.7 },\n { key: \"density\", label: \"Figure Density\", min: 0.1, max: 0.9, step: 0.05, default: 0.4 },\n ],\n },\n {\n id: \"rhythm-movement\",\n name: \"Rhythm & Movement\",\n category: \"composition\",\n complexity: \"advanced\",\n description:\n \"Create visual rhythm through repetition, variation, and progression to guide the viewer's eye across the composition.\",\n theory: `Rhythm in visual art functions like rhythm in music — it creates patterns of emphasis and rest that move the viewer's eye through the composition. Wucius Wong identifies several types of visual rhythm:\n\n- **Regular rhythm**: Consistent repetition of identical elements at equal intervals. Creates order and predictability.\n- **Alternating rhythm**: Two or more elements or spacings alternate. Creates more complex patterns.\n- **Progressive rhythm**: Elements gradually change in size, color, spacing, or orientation. Creates directional movement.\n- **Flowing rhythm**: Elements follow organic, curving paths. Creates natural, fluid movement.\n- **Random rhythm**: Irregular repetition with controlled variation. Creates controlled chaos.\n\nIn generative art, rhythm emerges from the interplay between your algorithm's regularity and its stochastic variation. The seed controls the specific instance; the parameters control the type and intensity of rhythm.`,\n principles: [\n \"Establish a base rhythm through regular repetition before introducing variation\",\n \"Use progressive changes in size or spacing to create directional movement\",\n \"Alternate between tension (clustering) and release (spacing) zones\",\n \"Let flow fields or parametric curves create natural movement paths\",\n \"Control the ratio of regularity to randomness via parameters\",\n \"Use acceleration/deceleration in element distribution for energy\",\n ],\n references: [\n { title: \"Principles of Form and Design\", author: \"Wucius Wong\", year: 1993 },\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n ],\n suggestedParameters: [\n { key: \"frequency\", label: \"Rhythm Frequency\", min: 1, max: 20, step: 1, default: 8 },\n { key: \"variation\", label: \"Variation\", min: 0.0, max: 1.0, step: 0.05, default: 0.3 },\n { key: \"flow\", label: \"Flow Strength\", min: 0.0, max: 2.0, step: 0.1, default: 0.5 },\n ],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Color Theory Skills (Albers, Itten)\n// ---------------------------------------------------------------------------\n\nexport const COLOR_SKILLS: readonly SkillDefinition[] = [\n {\n id: \"color-harmony\",\n name: \"Color Harmony Systems\",\n category: \"color\",\n complexity: \"beginner\",\n description:\n \"Use systematic color relationships — complementary, analogous, triadic, split-complementary — for harmonious palettes.\",\n theory: `Color harmony describes combinations of colors that are aesthetically pleasing. Johannes Itten formalized these relationships using the color wheel:\n\n- **Complementary**: Colors opposite on the wheel (e.g., blue/orange). Maximum contrast, vibrant when juxtaposed.\n- **Analogous**: 2-4 adjacent colors on the wheel. Harmonious and calm, low contrast.\n- **Triadic**: Three colors equally spaced (120° apart). Balanced and vibrant.\n- **Split-complementary**: A color plus the two colors adjacent to its complement. High contrast with less tension.\n- **Tetradic**: Two pairs of complementary colors. Rich and complex.\n\nIn generative art, these systems provide algorithmic palette generation. Start with a base hue, then calculate harmonious companions using angular relationships on the HSL color wheel.`,\n principles: [\n \"Choose one dominant color and use harmonics as accents (60-30-10 rule)\",\n \"Complementary pairs create maximum vibrance — use for focal contrast\",\n \"Analogous schemes work well for atmospheric, mood-driven pieces\",\n \"Vary saturation and value within a harmonic scheme for depth\",\n \"Use triadic schemes when you need balanced variety without chaos\",\n ],\n references: [\n { title: \"The Art of Color\", author: \"Johannes Itten\", year: 1961 },\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n ],\n suggestedParameters: [\n { key: \"baseHue\", label: \"Base Hue\", min: 0, max: 360, step: 1, default: 200 },\n { key: \"harmonyAngle\", label: \"Harmony Angle\", min: 15, max: 180, step: 5, default: 120 },\n ],\n suggestedColors: [\n { key: \"base\", label: \"Base Color\", default: \"#2196f3\" },\n { key: \"accent\", label: \"Accent Color\", default: \"#ff9800\" },\n ],\n },\n {\n id: \"simultaneous-contrast\",\n name: \"Simultaneous Contrast\",\n category: \"color\",\n complexity: \"advanced\",\n description:\n \"Exploit how adjacent colors alter each other's perceived hue, value, and saturation — the core of Albers' teaching.\",\n theory: `Josef Albers spent decades demonstrating that color is the most relative medium in art. The same color appears dramatically different depending on its surroundings:\n\n- A gray square on a black background appears lighter than the same gray on white\n- A neutral color surrounded by red appears to shift toward green (and vice versa)\n- Small color areas are more affected by their surroundings than large ones\n\nThis phenomenon — simultaneous contrast — means that in generative art, you cannot choose colors in isolation. The same palette will look different depending on element sizes, spacing, and layering order.\n\nPractical implications:\n- Test colors in context, not in isolation\n- Adjacent complementary colors intensify each other\n- Adjacent similar colors reduce each other's saturation\n- Background color dramatically shifts perception of all foreground elements`,\n principles: [\n \"The same color will appear different depending on what surrounds it\",\n \"Adjacent complementary colors intensify each other (vibration effect)\",\n \"Small color areas are dominated by surrounding colors\",\n \"Background color shifts the perceived hue of all foreground elements\",\n \"Use simultaneous contrast deliberately to create optical effects\",\n \"Test palette choices at various element sizes — effects change with scale\",\n ],\n references: [\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n ],\n suggestedParameters: [\n { key: \"elementSize\", label: \"Element Size\", min: 2, max: 100, step: 1, default: 20 },\n { key: \"borderWidth\", label: \"Border Width\", min: 0, max: 10, step: 0.5, default: 0 },\n ],\n },\n {\n id: \"color-temperature\",\n name: \"Color Temperature\",\n category: \"color\",\n complexity: \"beginner\",\n description:\n \"Use warm (red/orange/yellow) and cool (blue/green/violet) color relationships to create depth and emotional tone.\",\n theory: `Color temperature divides the spectrum into warm colors (reds, oranges, yellows) and cool colors (blues, greens, violets). This division has profound perceptual and emotional effects:\n\n**Spatial effects**: Warm colors appear to advance (come toward the viewer) while cool colors recede. This creates an automatic sense of depth without perspective geometry.\n\n**Emotional associations**: Warm colors evoke energy, passion, urgency. Cool colors evoke calm, distance, contemplation.\n\n**Temperature contrast**: The tension between warm and cool areas creates visual energy. A predominantly cool composition with a warm accent immediately draws the eye to the accent.\n\nIn generative art, map temperature to depth layers: cool backgrounds, warm foregrounds. Or use temperature gradients across the composition to create directional flow.`,\n principles: [\n \"Warm colors advance, cool colors recede — use for spatial depth\",\n \"A small warm accent in a cool composition creates a strong focal point\",\n \"Temperature contrast is as important as value contrast for composition\",\n \"Map color temperature to z-depth or layering order\",\n \"Use temperature gradients to create directional energy flow\",\n ],\n references: [\n { title: \"The Art of Color\", author: \"Johannes Itten\", year: 1961 },\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n ],\n suggestedParameters: [\n { key: \"warmth\", label: \"Warmth\", min: 0.0, max: 1.0, step: 0.05, default: 0.5 },\n { key: \"temperatureRange\", label: \"Temperature Range\", min: 30, max: 180, step: 10, default: 90 },\n ],\n suggestedColors: [\n { key: \"warm\", label: \"Warm Tone\", default: \"#ff6b35\" },\n { key: \"cool\", label: \"Cool Tone\", default: \"#4a90d9\" },\n ],\n },\n {\n id: \"itten-contrasts\",\n name: \"Itten's Seven Contrasts\",\n category: \"color\",\n complexity: \"advanced\",\n description:\n \"Apply Itten's systematic framework of seven color contrasts to create specific visual effects.\",\n theory: `Johannes Itten identified seven fundamental types of color contrast, each producing distinct visual effects:\n\n1. **Contrast of Hue**: Pure hues side by side (red, blue, yellow). Maximum color variety.\n2. **Light-Dark Contrast**: Value differences. The strongest structural contrast.\n3. **Cold-Warm Contrast**: Temperature opposition. Creates spatial depth.\n4. **Complementary Contrast**: Opposite hues. Each intensifies the other.\n5. **Simultaneous Contrast**: Perceived color shift caused by adjacency.\n6. **Contrast of Saturation**: Pure vs. muted colors. Creates focus hierarchy.\n7. **Contrast of Extension**: Relative area sizes of colors. Balances visual weight.\n\nEach contrast type can be parameterized in generative art. A single piece might employ multiple contrasts simultaneously, with parameters controlling the intensity of each.`,\n principles: [\n \"Light-dark contrast provides the structural backbone of any composition\",\n \"Use saturation contrast to create hierarchy: saturated = focal, muted = ambient\",\n \"Complementary contrast creates energy; analogous reduces it\",\n \"Contrast of extension: balance area ratios to color intensity (bright colors need less area)\",\n \"Layer multiple contrast types for visual complexity\",\n \"Control contrast intensity through parameters for exploration\",\n ],\n references: [\n { title: \"The Art of Color\", author: \"Johannes Itten\", year: 1961 },\n ],\n suggestedParameters: [\n { key: \"hueContrast\", label: \"Hue Contrast\", min: 0.0, max: 1.0, step: 0.05, default: 0.5 },\n { key: \"valueContrast\", label: \"Value Contrast\", min: 0.1, max: 1.0, step: 0.05, default: 0.7 },\n { key: \"saturationContrast\", label: \"Saturation Contrast\", min: 0.0, max: 1.0, step: 0.05, default: 0.4 },\n ],\n },\n {\n id: \"value-structure\",\n name: \"Value Structure\",\n category: \"color\",\n complexity: \"intermediate\",\n description:\n \"Organize compositions through light-dark value patterns — the foundation that underlies all color decisions.\",\n theory: `Value (lightness/darkness) is the most important property of color for composition. A piece that works in grayscale will work in any palette; a piece that fails in grayscale cannot be saved by color alone.\n\nValue structure means planning the distribution of lights, mid-tones, and darks across the composition. Classic approaches include:\n\n- **High-key**: Predominantly light values. Airy, ethereal, optimistic.\n- **Low-key**: Predominantly dark values. Dramatic, mysterious, intense.\n- **Full-range**: Full spectrum from near-white to near-black. Maximum contrast and visual impact.\n- **Limited-range**: Narrow value band. Subtle, atmospheric, unified.\n\nIn generative art, map value to depth, density, or importance. Establish a value plan (the notan — simplified light/dark pattern) before adding color complexity.`,\n principles: [\n \"Squint at your output: if the value pattern is unclear, color won't help\",\n \"Limit your palette to 3-5 value steps for strong structure\",\n \"Reserve highest contrast for the focal area\",\n \"Use mid-tones for transitions and atmosphere\",\n \"Dark values carry more visual weight than light ones at equal size\",\n ],\n references: [\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n { title: \"The Art of Color\", author: \"Johannes Itten\", year: 1961 },\n ],\n suggestedParameters: [\n { key: \"valueRange\", label: \"Value Range\", min: 0.1, max: 1.0, step: 0.05, default: 0.8 },\n { key: \"keyValue\", label: \"Key Value\", min: 0.0, max: 1.0, step: 0.05, default: 0.3 },\n ],\n },\n {\n id: \"palette-generation\",\n name: \"Algorithmic Palette Generation\",\n category: \"color\",\n complexity: \"intermediate\",\n description:\n \"Generate cohesive color palettes algorithmically using perceptual color spaces and mathematical relationships.\",\n theory: `Traditional color theory works with the HSL/HSV color wheel, but perceptual uniformity is better achieved in modern color spaces like OKLCH (Oklab Lightness-Chroma-Hue).\n\nIn OKLCH:\n- **L** (lightness, 0-1): Perceptually uniform brightness steps\n- **C** (chroma, 0-0.4): Saturation/vibrancy\n- **H** (hue, 0-360): Hue angle\n\nAlgorithmic palette strategies:\n- **Fixed hue, varying L/C**: Monochromatic palette with perceptual uniformity\n- **Fixed L/C, varying H**: Evenly-spaced hues at consistent brightness (true equiluminant palette)\n- **Seed-based generation**: Use the sketch seed to derive a base hue, then calculate harmonics\n- **Gradient interpolation**: Interpolate between anchor colors in OKLCH for smooth transitions\n\nThe advantage of working in OKLCH over HSL is that equal mathematical steps produce equal perceptual steps — a gradient from dark blue to light blue will look evenly spaced rather than having a perceptual \"jump\" in the middle.`,\n principles: [\n \"Use OKLCH or Oklab for perceptually uniform color operations\",\n \"Generate palettes from seed + base hue for deterministic, explorable results\",\n \"Keep chroma (saturation) consistent across a palette for cohesion\",\n \"Vary lightness for value structure, hue for variety, chroma for energy\",\n \"Map parameter ranges to hue angles for intuitive color exploration\",\n \"Limit generated palettes to 3-7 colors for coherence\",\n ],\n references: [\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n ],\n suggestedParameters: [\n { key: \"baseHue\", label: \"Base Hue\", min: 0, max: 360, step: 1, default: 220 },\n { key: \"chroma\", label: \"Chroma\", min: 0.05, max: 0.35, step: 0.01, default: 0.15 },\n { key: \"paletteSize\", label: \"Palette Size\", min: 3, max: 7, step: 1, default: 5 },\n ],\n },\n];\n","import type { SkillDefinition } from \"../types.js\";\nimport { COMPOSITION_SKILLS, COLOR_SKILLS } from \"./skills.js\";\n\n/**\n * Registry for design knowledge skills.\n * Mirrors the RendererRegistry pattern.\n */\nexport class SkillRegistry {\n private readonly skills = new Map<string, SkillDefinition>();\n\n /** Register a skill definition. */\n register(skill: SkillDefinition): void {\n this.skills.set(skill.id, skill);\n }\n\n /** Resolve a skill by ID. Throws if not found. */\n resolve(id: string): SkillDefinition {\n const skill = this.skills.get(id);\n if (!skill) {\n throw new Error(`Unknown skill: '${id}'`);\n }\n return skill;\n }\n\n /** Get a skill by ID, or undefined if not found. */\n get(id: string): SkillDefinition | undefined {\n return this.skills.get(id);\n }\n\n /** List all skills, optionally filtered by category. */\n list(category?: string): SkillDefinition[] {\n const all = Array.from(this.skills.values());\n if (category) {\n return all.filter((s) => s.category === category);\n }\n return all;\n }\n\n /** Check if a skill ID is registered. */\n has(id: string): boolean {\n return this.skills.has(id);\n }\n\n /** Return unique categories across all registered skills. */\n categories(): string[] {\n const cats = new Set<string>();\n for (const skill of this.skills.values()) {\n cats.add(skill.category);\n }\n return Array.from(cats).sort();\n }\n}\n\n/**\n * Create a skill registry pre-loaded with all built-in skills.\n */\nexport function createDefaultSkillRegistry(): SkillRegistry {\n const registry = new SkillRegistry();\n for (const skill of [...COMPOSITION_SKILLS, ...COLOR_SKILLS]) {\n registry.register(skill);\n }\n return registry;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,0BAAc,+BAFd;;;ACeA,IAAM,iBAAiB;AACvB,IAAM,aAAa,gDAAgD,cAAc;AAiB1E,IAAM,oBAAN,MAAmD;AAAA,EAC/C,OAAqB;AAAA,EACrB,cAAc;AAAA,EACd,oBAAoB;AAAA,EAE7B,SAAS,WAAqC;AAC5C,UAAM,SAAmB,CAAC;AAE1B,QAAI,CAAC,aAAa,UAAU,KAAK,EAAE,WAAW,GAAG;AAC/C,aAAO,EAAE,OAAO,OAAO,QAAQ,CAAC,2BAA2B,EAAE;AAAA,IAC/D;AAGA,UAAM,cACJ,8CAA8C,KAAK,SAAS,KAC5D,2EAA2E,KAAK,SAAS,KACzF,gEAAgE,KAAK,SAAS;AAEhF,QAAI,CAAC,aAAa;AAChB,aAAO;AAAA,QACL;AAAA,MACF;AAAA,IACF;AAGA,UAAM,WAAW,qBAAqB,KAAK,SAAS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AG,YAAY,GAAG;AAC5D,aAAS,SAAS,KAAK;AAAA,EACzB;AACA,SAAO;AACT;","names":["escapeHtml","escapeHtml","escapeHtml","module","escapeHtml"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/sketch/adapters/component-utils.ts","../src/sketch/adapters/p5.ts","../src/sketch/adapters/canvas2d.ts","../src/sketch/adapters/three.ts","../src/sketch/adapters/glsl.ts","../src/sketch/adapters/svg.ts","../src/sketch/registry.ts","../src/skill/skills.ts","../src/skill/registry.ts"],"sourcesContent":["// Re-export all format types and utilities for convenience\n// Consumers of @genart-dev/core get the full format API without a separate import\nexport * from \"@genart-dev/format\";\n\n// Re-export component registry, resolver, and types\nexport {\n COMPONENT_REGISTRY,\n resolveComponents,\n type ComponentEntry,\n type ComponentCategory,\n type RendererTarget,\n type ResolvedComponent,\n} from \"@genart-dev/components\";\n\n// Core types (runtime interfaces not in the format package)\nexport type {\n SkillDefinition,\n SkillReference,\n ValidationResult,\n CompiledAlgorithm,\n RuntimeDependency,\n CaptureOptions,\n RendererAdapter,\n SketchInstance,\n} from \"./types.js\";\n\n// Renderer adapters\nexport {\n P5RendererAdapter,\n Canvas2DRendererAdapter,\n ThreeRendererAdapter,\n GLSLRendererAdapter,\n SVGRendererAdapter,\n} from \"./sketch/adapters/index.js\";\nexport { hexToVec3 } from \"./sketch/adapters/glsl.js\";\n\n// Renderer registry\nexport {\n RendererRegistry,\n createDefaultRegistry,\n} from \"./sketch/registry.js\";\n\n// Skill system\nexport {\n SkillRegistry,\n createDefaultSkillRegistry,\n COMPOSITION_SKILLS,\n COLOR_SKILLS,\n} from \"./skill/index.js\";\n","import type { SketchComponentValue } from \"@genart-dev/format\";\n\n/**\n * Extract component source code from a SketchDefinition.components record.\n * Returns a string of JS code to embed in standalone HTML.\n * Only includes components that have cached `code` (resolved form).\n */\nexport function extractComponentCode(\n components?: Readonly<Record<string, SketchComponentValue>>,\n): string {\n if (!components) return '';\n\n const blocks: string[] = [];\n for (const [name, value] of Object.entries(components)) {\n if (typeof value === 'string') continue; // unresolved — no code to inject\n if (value.code) {\n const ver = value.version ? ` v${value.version}` : '';\n blocks.push(`// --- ${name}${ver} ---\\n${value.code}`);\n }\n }\n return blocks.join('\\n\\n');\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type { ResolvedComponent } from \"@genart-dev/components\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\nimport { extractComponentCode } from \"./component-utils.js\";\n\nconst P5_CDN_VERSION = \"1.11.3\";\nconst P5_CDN_URL = `https://cdnjs.cloudflare.com/ajax/libs/p5.js/${P5_CDN_VERSION}/p5.min.js`;\n\n/**\n * Compiled p5 algorithm — wraps the algorithm source string\n * and a factory function for creating p5 instance-mode sketches.\n */\ninterface P5CompiledAlgorithm {\n source: string;\n factory: (p: unknown, state: SketchState) => unknown;\n}\n\n/**\n * P5 Renderer Adapter — full implementation.\n *\n * Validates algorithms for the `sketch(p, state)` instance-mode signature,\n * compiles them into executable factories, and creates live sketch instances.\n */\nexport class P5RendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"p5\";\n readonly displayName = \"p5.js\";\n readonly algorithmLanguage = \"javascript\" as const;\n\n validate(algorithm: string): ValidationResult {\n const errors: string[] = [];\n\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n\n // Check for the instance-mode sketch function signature\n const hasSketchFn =\n /function\\s+sketch\\s*\\(\\s*p\\s*,\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*(?:function\\s*)?\\(\\s*p\\s*,\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*\\(\\s*p\\s*,\\s*state\\s*\\)\\s*=>/.test(algorithm);\n\n if (!hasSketchFn) {\n errors.push(\n 'p5 algorithms must export a function with signature: function sketch(p, state)',\n );\n }\n\n // Check for p.setup assignment\n const hasSetup = /p\\s*\\.\\s*setup\\s*=/.test(algorithm);\n if (!hasSetup) {\n errors.push(\"p5 algorithms must assign p.setup\");\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n async compile(algorithm: string, components?: ResolvedComponent[]): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `p5 compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const componentCode = components?.map(c =>\n `// --- ${c.name} v${c.version} ---\\n${c.code}`\n ).join('\\n\\n') ?? '';\n\n // Wrap the algorithm source into a factory function\n // The factory takes (p, state) and returns the sketch module\n const wrappedSource = `\n return (function() {\n ${componentCode}\n ${algorithm}\n return sketch;\n })();\n `;\n\n try {\n const factory = new Function(wrappedSource) as () => (\n p: unknown,\n state: SketchState,\n ) => unknown;\n const compiled: P5CompiledAlgorithm = {\n source: algorithm,\n factory: factory(),\n };\n return compiled;\n } catch (err) {\n throw new Error(\n `p5 compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { factory } = compiled as P5CompiledAlgorithm;\n\n let p5Instance: Record<string, unknown> | null = null;\n let container: HTMLElement | null = null;\n let currentState = { ...state };\n let animating = true;\n let sketchModule: Record<string, unknown> | null = null;\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n\n // Requires p5 to be available globally or as a module\n const P5Constructor = (globalThis as Record<string, unknown>)[\n \"p5\"\n ] as new (\n sketch: (p: Record<string, unknown>) => void,\n container: HTMLElement,\n ) => Record<string, unknown>;\n\n if (!P5Constructor) {\n throw new Error(\n \"p5.js is not loaded. Include p5.js before mounting a p5 sketch.\",\n );\n }\n\n p5Instance = new P5Constructor((p: Record<string, unknown>) => {\n sketchModule = factory(p, currentState) as Record<string, unknown>;\n }, el);\n },\n\n unmount() {\n if (p5Instance && typeof p5Instance[\"remove\"] === \"function\") {\n (p5Instance[\"remove\"] as () => void)();\n }\n p5Instance = null;\n sketchModule = null;\n container = null;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState };\n if (\n sketchModule &&\n typeof sketchModule[\"initializeSystem\"] === \"function\"\n ) {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n redraw() {\n if (p5Instance && typeof p5Instance[\"redraw\"] === \"function\") {\n (p5Instance[\"redraw\"] as () => void)();\n }\n },\n\n pause() {\n animating = false;\n if (p5Instance && typeof p5Instance[\"noLoop\"] === \"function\") {\n (p5Instance[\"noLoop\"] as () => void)();\n }\n },\n\n resume() {\n animating = true;\n if (p5Instance && typeof p5Instance[\"loop\"] === \"function\") {\n (p5Instance[\"loop\"] as () => void)();\n }\n },\n\n get isAnimating() {\n return animating;\n },\n\n async captureFrame(options?: CaptureOptions): Promise<string> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const canvasEl = container.querySelector(\"canvas\");\n if (!canvasEl) throw new Error(\"No canvas element found\");\n\n const format = options?.format ?? \"png\";\n const quality = options?.quality ?? 1.0;\n const mimeType =\n format === \"jpeg\"\n ? \"image/jpeg\"\n : format === \"webp\"\n ? \"image/webp\"\n : \"image/png\";\n\n return canvasEl.toDataURL(mimeType, quality);\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const canvasEl = container.querySelector(\"canvas\");\n if (!canvasEl) throw new Error(\"No canvas element found\");\n const ctx = canvasEl.getContext(\"2d\");\n if (!ctx) throw new Error(\"Cannot get 2D context from canvas\");\n return ctx.getImageData(0, 0, canvasEl.width, canvasEl.height);\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n // Offscreen rendering requires a DOM context (browser or jsdom)\n // This creates a temporary container, mounts, captures, and unmounts\n const el = document.createElement(\"div\");\n el.style.position = \"absolute\";\n el.style.left = \"-9999px\";\n document.body.appendChild(el);\n\n try {\n const instance = this.createInstance(compiled, state, canvas);\n instance.mount(el);\n\n // Wait for setup to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n\n const dataUrl = await instance.captureFrame(options);\n instance.dispose();\n\n // Convert data URL to Uint8Array\n const base64 = dataUrl.split(\",\")[1] ?? \"\";\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n } finally {\n document.body.removeChild(el);\n }\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const pixelDensity = sketch.canvas.pixelDensity ?? 1;\n\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n // Build a keyed COLORS object from ColorDef keys → colorPalette values\n // so algorithms can use state.COLORS.bg instead of state.colorPalette[0].\n const colorsMap: Record<string, string> = {};\n for (let i = 0; i < sketch.colors.length; i++) {\n const colorDef = sketch.colors[i];\n if (colorDef) {\n colorsMap[colorDef.key] = sketch.state.colorPalette[i] ?? \"#000000\";\n }\n }\n const colorsJson = JSON.stringify(colorsMap);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <script src=\"${P5_CDN_URL}\"></script>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #111; }\n #canvas-container canvas { display: block; max-width: 100vw; max-height: 100vh; }\n </style>\n</head>\n<body>\n <div id=\"canvas-container\"></div>\n <script>\n const state = ${stateJson};\n state.canvas = { width: ${width}, height: ${height}, pixelDensity: ${pixelDensity} };\n // Convenience aliases — algorithms may use either naming convention\n state.WIDTH = ${width};\n state.HEIGHT = ${height};\n state.SEED = state.seed;\n state.PARAMS = state.params;\n state.COLORS = ${colorsJson};\n\n ${extractComponentCode(sketch.components)}\n ${sketch.algorithm}\n\n new p5(function(p) {\n sketch(p, state);\n }, document.getElementById('canvas-container'));\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `function sketch(p, state) {\n const { WIDTH, HEIGHT, SEED, PARAMS, COLORS } = state;\n p.setup = () => {\n p.createCanvas(WIDTH, HEIGHT);\n p.randomSeed(SEED);\n };\n p.draw = () => {\n p.background(COLORS.background);\n // generative algorithm here\n };\n return { initializeSystem() { /* rebuild from state */ } };\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n return [\n {\n name: \"p5\",\n version: P5_CDN_VERSION,\n cdnUrl: P5_CDN_URL,\n },\n ];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type { ResolvedComponent } from \"@genart-dev/components\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\nimport { extractComponentCode } from \"./component-utils.js\";\n\n/**\n * Compiled Canvas 2D algorithm — wraps the algorithm source string\n * and a factory function for creating canvas sketches.\n */\ninterface Canvas2DCompiledAlgorithm {\n source: string;\n factory: (\n ctx: CanvasRenderingContext2D,\n state: SketchState,\n ) => Record<string, unknown>;\n}\n\n/**\n * Canvas 2D Renderer Adapter — full implementation.\n *\n * Validates algorithms for the `sketch(ctx, state)` function signature,\n * compiles them into executable factories, and creates live sketch instances.\n */\nexport class Canvas2DRendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"canvas2d\";\n readonly displayName = \"Canvas 2D\";\n readonly algorithmLanguage = \"javascript\" as const;\n\n validate(algorithm: string): ValidationResult {\n const errors: string[] = [];\n\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n\n // Check for the canvas2d sketch function signature\n const hasSketchFn =\n /function\\s+sketch\\s*\\(\\s*ctx\\s*,\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*(?:function\\s*)?\\(\\s*ctx\\s*,\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*\\(\\s*ctx\\s*,\\s*state\\s*\\)\\s*=>/.test(algorithm);\n\n if (!hasSketchFn) {\n errors.push(\n 'Canvas 2D algorithms must export a function with signature: function sketch(ctx, state)',\n );\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n async compile(algorithm: string, components?: ResolvedComponent[]): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `Canvas 2D compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const componentCode = components?.map(c =>\n `// --- ${c.name} v${c.version} ---\\n${c.code}`\n ).join('\\n\\n') ?? '';\n\n const wrappedSource = `\n return (function() {\n ${componentCode}\n ${algorithm}\n return sketch;\n })();\n `;\n\n try {\n const factory = new Function(wrappedSource) as () => (\n ctx: CanvasRenderingContext2D,\n state: SketchState,\n ) => Record<string, unknown>;\n const compiled: Canvas2DCompiledAlgorithm = {\n source: algorithm,\n factory: factory(),\n };\n return compiled;\n } catch (err) {\n throw new Error(\n `Canvas 2D compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { factory } = compiled as Canvas2DCompiledAlgorithm;\n\n let canvasEl: HTMLCanvasElement | null = null;\n let ctx: CanvasRenderingContext2D | null = null;\n let container: HTMLElement | null = null;\n let currentState = { ...state };\n let animating = false;\n let animationFrameId: number | null = null;\n let sketchModule: Record<string, unknown> | null = null;\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n canvasEl = document.createElement(\"canvas\");\n canvasEl.width = canvas.width;\n canvasEl.height = canvas.height;\n\n const density = canvas.pixelDensity ?? 1;\n if (density !== 1) {\n canvasEl.width = canvas.width * density;\n canvasEl.height = canvas.height * density;\n canvasEl.style.width = `${canvas.width}px`;\n canvasEl.style.height = `${canvas.height}px`;\n }\n\n el.appendChild(canvasEl);\n ctx = canvasEl.getContext(\"2d\");\n if (!ctx) throw new Error(\"Failed to get 2D rendering context\");\n\n if (density !== 1) {\n ctx.scale(density, density);\n }\n\n sketchModule = factory(ctx, currentState);\n if (sketchModule && typeof sketchModule[\"initializeSystem\"] === \"function\") {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n unmount() {\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n if (canvasEl && container) {\n container.removeChild(canvasEl);\n }\n canvasEl = null;\n ctx = null;\n container = null;\n sketchModule = null;\n animating = false;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState };\n if (sketchModule && typeof sketchModule[\"initializeSystem\"] === \"function\") {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n redraw() {\n if (sketchModule && typeof sketchModule[\"initializeSystem\"] === \"function\") {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n pause() {\n animating = false;\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n },\n\n resume() {\n animating = true;\n if (sketchModule && typeof sketchModule[\"draw\"] === \"function\") {\n const loop = () => {\n if (!animating) return;\n (sketchModule![\"draw\"] as () => void)();\n animationFrameId = requestAnimationFrame(loop);\n };\n loop();\n }\n },\n\n get isAnimating() {\n return animating;\n },\n\n async captureFrame(options?: CaptureOptions): Promise<string> {\n if (!canvasEl) throw new Error(\"Sketch is not mounted\");\n const format = options?.format ?? \"png\";\n const quality = options?.quality ?? 1.0;\n const mimeType =\n format === \"jpeg\"\n ? \"image/jpeg\"\n : format === \"webp\"\n ? \"image/webp\"\n : \"image/png\";\n return canvasEl.toDataURL(mimeType, quality);\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!canvasEl || !ctx) throw new Error(\"Sketch is not mounted\");\n return ctx.getImageData(0, 0, canvasEl.width, canvasEl.height);\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n const el = document.createElement(\"div\");\n el.style.position = \"absolute\";\n el.style.left = \"-9999px\";\n document.body.appendChild(el);\n\n try {\n const instance = this.createInstance(compiled, state, canvas);\n instance.mount(el);\n\n await new Promise((resolve) => setTimeout(resolve, 50));\n\n const dataUrl = await instance.captureFrame(options);\n instance.dispose();\n\n const base64 = dataUrl.split(\",\")[1] ?? \"\";\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n } finally {\n document.body.removeChild(el);\n }\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const pixelDensity = sketch.canvas.pixelDensity ?? 1;\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n html, body { width: 100%; height: 100%; overflow: hidden; background: #111; }\n body { display: flex; justify-content: center; align-items: center; }\n canvas { display: block; }\n </style>\n</head>\n<body>\n <canvas id=\"canvas\" width=\"${width * pixelDensity}\" height=\"${height * pixelDensity}\" style=\"width:${width}px;height:${height}px;\"></canvas>\n <script>\n try {\n const state = ${stateJson};\n state.canvas = { width: ${width}, height: ${height}, pixelDensity: ${pixelDensity} };\n\n ${extractComponentCode(sketch.components)}\n ${sketch.algorithm}\n\n const canvas = document.getElementById('canvas');\n const ctx = canvas.getContext('2d');\n ${pixelDensity !== 1 ? `ctx.scale(${pixelDensity}, ${pixelDensity});` : \"\"}\n const module = sketch(ctx, state);\n if (module && module.initializeSystem) module.initializeSystem();\n } catch (e) {\n document.body.style.background = '#300';\n document.body.style.color = '#f88';\n document.body.style.fontFamily = 'monospace';\n document.body.style.fontSize = '12px';\n document.body.style.padding = '16px';\n document.body.textContent = 'Sketch error: ' + e.message;\n }\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `function sketch(ctx, state) {\n const { width, height } = state.canvas;\n function initializeSystem() {\n ctx.clearRect(0, 0, width, height);\n // generative algorithm here\n }\n return { initializeSystem };\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n // Canvas 2D has no external dependencies\n return [];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type { ResolvedComponent } from \"@genart-dev/components\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\nimport { extractComponentCode } from \"./component-utils.js\";\n\nconst THREE_CDN_VERSION = \"0.172.0\";\nconst THREE_CDN_URL = `https://cdn.jsdelivr.net/npm/three@${THREE_CDN_VERSION}/build/three.module.min.js`;\n\n/**\n * Compiled Three.js algorithm — wraps the algorithm source string\n * and a factory function for creating Three.js sketches.\n */\ninterface ThreeCompiledAlgorithm {\n source: string;\n factory: (\n THREE: unknown,\n state: SketchState & { canvas: CanvasSpec },\n container: HTMLElement,\n ) => Record<string, unknown>;\n}\n\n/**\n * Three.js Renderer Adapter — full implementation.\n *\n * Validates algorithms for the `sketch(THREE, state, container)` signature,\n * compiles them into executable factories, and creates live sketch instances.\n */\nexport class ThreeRendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"three\";\n readonly displayName = \"Three.js\";\n readonly algorithmLanguage = \"javascript\" as const;\n\n validate(algorithm: string): ValidationResult {\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n // Basic validation — check for sketch function signature\n const hasSketchFn =\n /function\\s+sketch\\s*\\(\\s*THREE\\s*,\\s*state\\s*,\\s*container\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*(?:function\\s*)?\\(\\s*THREE\\s*,\\s*state\\s*,\\s*container\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*\\(\\s*THREE\\s*,\\s*state\\s*,\\s*container\\s*\\)\\s*=>/.test(algorithm);\n\n if (!hasSketchFn) {\n return {\n valid: false,\n errors: [\n \"Three.js algorithms must export a function with signature: function sketch(THREE, state, container)\",\n ],\n };\n }\n return { valid: true, errors: [] };\n }\n\n async compile(algorithm: string, components?: ResolvedComponent[]): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `Three.js compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const componentCode = components?.map(c =>\n `// --- ${c.name} v${c.version} ---\\n${c.code}`\n ).join('\\n\\n') ?? '';\n\n const wrappedSource = `\n return (function() {\n ${componentCode}\n ${algorithm}\n return sketch;\n })();\n `;\n\n try {\n const factory = new Function(wrappedSource) as () => (\n THREE: unknown,\n state: SketchState & { canvas: CanvasSpec },\n container: HTMLElement,\n ) => Record<string, unknown>;\n const compiled: ThreeCompiledAlgorithm = {\n source: algorithm,\n factory: factory(),\n };\n return compiled;\n } catch (err) {\n throw new Error(\n `Three.js compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { factory } = compiled as ThreeCompiledAlgorithm;\n\n let container: HTMLElement | null = null;\n let currentState = { ...state, canvas };\n let sketchModule: Record<string, unknown> | null = null;\n let animating = false;\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n\n // Requires THREE to be available globally\n const THREEGlobal = (globalThis as Record<string, unknown>)[\"THREE\"];\n\n if (!THREEGlobal) {\n throw new Error(\n \"Three.js is not loaded. Include Three.js before mounting a Three.js sketch.\",\n );\n }\n\n sketchModule = factory(THREEGlobal, currentState, el);\n animating = true;\n },\n\n unmount() {\n if (\n sketchModule &&\n typeof sketchModule[\"dispose\"] === \"function\"\n ) {\n (sketchModule[\"dispose\"] as () => void)();\n }\n if (container) {\n container.innerHTML = \"\";\n }\n sketchModule = null;\n container = null;\n animating = false;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState, canvas };\n if (\n sketchModule &&\n typeof sketchModule[\"initializeSystem\"] === \"function\"\n ) {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n redraw() {\n if (\n sketchModule &&\n typeof sketchModule[\"initializeSystem\"] === \"function\"\n ) {\n (sketchModule[\"initializeSystem\"] as () => void)();\n }\n },\n\n pause() {\n animating = false;\n if (\n sketchModule &&\n typeof sketchModule[\"pause\"] === \"function\"\n ) {\n (sketchModule[\"pause\"] as () => void)();\n }\n },\n\n resume() {\n animating = true;\n if (\n sketchModule &&\n typeof sketchModule[\"resume\"] === \"function\"\n ) {\n (sketchModule[\"resume\"] as () => void)();\n }\n },\n\n get isAnimating() {\n return animating;\n },\n\n async captureFrame(options?: CaptureOptions): Promise<string> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const canvasEl = container.querySelector(\"canvas\");\n if (!canvasEl) throw new Error(\"No canvas element found\");\n\n const format = options?.format ?? \"png\";\n const quality = options?.quality ?? 1.0;\n const mimeType =\n format === \"jpeg\"\n ? \"image/jpeg\"\n : format === \"webp\"\n ? \"image/webp\"\n : \"image/png\";\n\n return canvasEl.toDataURL(mimeType, quality);\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const canvasEl = container.querySelector(\"canvas\");\n if (!canvasEl) throw new Error(\"No canvas element found\");\n const ctx = canvasEl.getContext(\"2d\");\n if (!ctx) throw new Error(\"Cannot get 2D context from canvas\");\n return ctx.getImageData(0, 0, canvasEl.width, canvasEl.height);\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n const el = document.createElement(\"div\");\n el.style.position = \"absolute\";\n el.style.left = \"-9999px\";\n document.body.appendChild(el);\n\n try {\n const instance = this.createInstance(compiled, state, canvas);\n instance.mount(el);\n\n // Three.js scenes need more setup time\n await new Promise((resolve) => setTimeout(resolve, 200));\n\n const dataUrl = await instance.captureFrame(options);\n instance.dispose();\n\n const base64 = dataUrl.split(\",\")[1] ?? \"\";\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n } finally {\n document.body.removeChild(el);\n }\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const pixelDensity = sketch.canvas.pixelDensity ?? 1;\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #111; overflow: hidden; }\n #canvas-container { width: ${width}px; height: ${height}px; }\n #canvas-container canvas { display: block; max-width: 100vw; max-height: 100vh; }\n </style>\n</head>\n<body>\n <div id=\"canvas-container\"></div>\n <script type=\"module\">\n import * as THREE from '${THREE_CDN_URL}';\n\n const state = ${stateJson};\n state.canvas = { width: ${width}, height: ${height}, pixelDensity: ${pixelDensity} };\n\n ${extractComponentCode(sketch.components)}\n ${sketch.algorithm}\n\n sketch(THREE, state, document.getElementById('canvas-container'));\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `function sketch(THREE, state, container) {\n const scene = new THREE.Scene();\n const camera = new THREE.PerspectiveCamera(75, state.canvas.width / state.canvas.height, 0.1, 1000);\n const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });\n renderer.setSize(state.canvas.width, state.canvas.height);\n container.appendChild(renderer.domElement);\n camera.position.z = 5;\n\n let animating = true;\n let animId = null;\n\n function initializeSystem() {\n // Rebuild scene from state.params and state.seed\n while (scene.children.length > 0) scene.remove(scene.children[0]);\n const geometry = new THREE.BoxGeometry();\n const material = new THREE.MeshBasicMaterial({ color: 0x22d3ee });\n const cube = new THREE.Mesh(geometry, material);\n scene.add(cube);\n }\n\n function animate() {\n if (!animating) return;\n animId = requestAnimationFrame(animate);\n renderer.render(scene, camera);\n }\n\n function pause() {\n animating = false;\n if (animId !== null) cancelAnimationFrame(animId);\n }\n\n function resume() {\n animating = true;\n animate();\n }\n\n function dispose() {\n pause();\n renderer.dispose();\n container.removeChild(renderer.domElement);\n }\n\n initializeSystem();\n animate();\n\n return { initializeSystem, dispose, pause, resume };\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n return [\n {\n name: \"three\",\n version: THREE_CDN_VERSION,\n cdnUrl: THREE_CDN_URL,\n },\n ];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n SketchComponentValue,\n} from \"@genart-dev/format\";\nimport type { ResolvedComponent } from \"@genart-dev/components\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\n\n/** Built-in uniforms that are not mapped from user parameters. */\nconst BUILTIN_UNIFORMS = new Set([\n \"u_resolution\",\n \"u_time\",\n \"u_seed\",\n]);\n\n/** Standard fullscreen quad vertex shader for WebGL2. */\nconst FULLSCREEN_QUAD_VERTEX = `#version 300 es\nin vec2 a_position;\nvoid main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n}`;\n\n/**\n * Compiled GLSL algorithm — contains the fragment and vertex shaders\n * plus extracted uniform name mappings.\n */\ninterface GLSLCompiledAlgorithm {\n fragmentSource: string;\n vertexSource: string;\n uniformNames: {\n params: string[];\n colors: string[];\n };\n}\n\n/**\n * Parse a hex color string to RGB floats in [0, 1] range.\n * Accepts \"#rrggbb\" or \"rrggbb\" format.\n */\nexport function hexToVec3(hex: string): [number, number, number] {\n const clean = hex.replace(/^#/, \"\");\n const r = parseInt(clean.substring(0, 2), 16) / 255;\n const g = parseInt(clean.substring(2, 4), 16) / 255;\n const b = parseInt(clean.substring(4, 6), 16) / 255;\n return [r, g, b];\n}\n\n/**\n * Extract uniform declarations from GLSL source.\n * Returns uniform names categorized as built-in, param-mapped, or color-mapped.\n */\nfunction extractUniforms(source: string): {\n params: string[];\n colors: string[];\n} {\n const params: string[] = [];\n const colors: string[] = [];\n const uniformRegex = /uniform\\s+(?:float|vec[234]|int|mat[234])\\s+(u_\\w+)/g;\n let match;\n\n while ((match = uniformRegex.exec(source)) !== null) {\n const name = match[1]!;\n if (BUILTIN_UNIFORMS.has(name)) continue;\n // Color uniforms are vec3 named u_color followed by a digit\n if (/^u_color\\d+$/.test(name)) {\n colors.push(name);\n } else {\n params.push(name);\n }\n }\n\n return { params, colors };\n}\n\n/**\n * Inject raw GLSL source into a shader, after #version and precision directives.\n */\nfunction injectGLSLSource(algorithm: string, codeToInject: string): string {\n if (!codeToInject) return algorithm;\n\n // Trim leading whitespace — GLSL sources often arrive with indentation\n const trimmed = algorithm.trimStart();\n\n // Extract #version line\n const versionMatch = trimmed.match(/^(#version\\s+\\S+[^\\n]*\\n)/);\n const versionLine = versionMatch?.[1] ?? '';\n let shaderBody = versionMatch ? trimmed.slice(versionLine.length) : trimmed;\n\n // Extract precision statement(s) — may also have leading whitespace per line\n const precisionLines: string[] = [];\n let precisionMatch: RegExpMatchArray | null;\n while ((precisionMatch = shaderBody.match(/^\\s*(precision\\s+\\w+\\s+\\w+;\\s*\\n)/)) !== null) {\n precisionLines.push(precisionMatch[1]!);\n shaderBody = shaderBody.slice(precisionMatch[0]!.length);\n }\n\n // Reassemble: version → precision → injected code → user shader\n return versionLine + precisionLines.join('') + '\\n'\n + codeToInject + '\\n\\n'\n + shaderBody;\n}\n\n/**\n * Inject GLSL component code into a shader source from resolved components.\n */\nfunction injectGLSLComponents(\n algorithm: string,\n components?: ResolvedComponent[],\n): string {\n if (!components || components.length === 0) return algorithm;\n\n const componentCode = components.map(c =>\n `// --- ${c.name} v${c.version} ---\\n${c.code}`\n ).join('\\n\\n');\n\n return injectGLSLSource(algorithm, componentCode);\n}\n\n/**\n * Extract GLSL component code from SketchDefinition.components for standalone HTML.\n * Returns assembled GLSL source (no directives — caller handles placement).\n */\nfunction extractGLSLComponentCode(\n components?: Readonly<Record<string, SketchComponentValue>>,\n): string {\n if (!components) return '';\n\n const blocks: string[] = [];\n for (const [name, value] of Object.entries(components)) {\n if (typeof value === 'string') continue;\n if (value.code) {\n const ver = value.version ? ` v${value.version}` : '';\n blocks.push(`// --- ${name}${ver} ---\\n${value.code}`);\n }\n }\n return blocks.join('\\n\\n');\n}\n\n/**\n * GLSL Renderer Adapter — full implementation.\n *\n * Validates GLSL fragment shaders, compiles them with a fullscreen quad\n * vertex shader, and creates live sketch instances using WebGL2.\n */\nexport class GLSLRendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"glsl\";\n readonly displayName = \"GLSL Shader\";\n readonly algorithmLanguage = \"glsl\" as const;\n\n validate(algorithm: string): ValidationResult {\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n // Basic GLSL validation — check for version directive and main function\n const hasVersion = /#version\\s+\\d+\\s+es/.test(algorithm);\n const hasMain = /void\\s+main\\s*\\(\\s*\\)/.test(algorithm);\n const hasFragColor =\n /fragColor/.test(algorithm) || /gl_FragColor/.test(algorithm);\n\n const errors: string[] = [];\n if (!hasVersion) {\n errors.push(\"GLSL shaders should start with a #version directive (e.g., #version 300 es)\");\n }\n if (!hasMain) {\n errors.push(\"GLSL shaders must contain a void main() function\");\n }\n if (!hasFragColor) {\n errors.push(\"GLSL shaders must write to fragColor or gl_FragColor\");\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n async compile(algorithm: string, components?: ResolvedComponent[]): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `GLSL compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const fragmentSource = injectGLSLComponents(algorithm, components);\n const uniforms = extractUniforms(fragmentSource);\n\n const compiled: GLSLCompiledAlgorithm = {\n fragmentSource,\n vertexSource: FULLSCREEN_QUAD_VERTEX,\n uniformNames: uniforms,\n };\n\n return compiled;\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { fragmentSource, vertexSource, uniformNames } =\n compiled as GLSLCompiledAlgorithm;\n\n let canvasEl: HTMLCanvasElement | null = null;\n let gl: WebGL2RenderingContext | null = null;\n let program: WebGLProgram | null = null;\n let vao: WebGLVertexArrayObject | null = null;\n let positionBuffer: WebGLBuffer | null = null;\n let container: HTMLElement | null = null;\n let currentState = { ...state };\n let animating = false;\n let animationFrameId: number | null = null;\n let startTime = 0;\n\n function compileShader(\n glCtx: WebGL2RenderingContext,\n type: number,\n source: string,\n ): WebGLShader {\n const shader = glCtx.createShader(type);\n if (!shader) throw new Error(\"Failed to create shader\");\n glCtx.shaderSource(shader, source);\n glCtx.compileShader(shader);\n if (!glCtx.getShaderParameter(shader, glCtx.COMPILE_STATUS)) {\n const info = glCtx.getShaderInfoLog(shader);\n glCtx.deleteShader(shader);\n throw new Error(`Shader compilation error: ${info}`);\n }\n return shader;\n }\n\n function bindUniforms(glCtx: WebGL2RenderingContext, prog: WebGLProgram) {\n // Built-in uniforms\n const resLoc = glCtx.getUniformLocation(prog, \"u_resolution\");\n if (resLoc) {\n glCtx.uniform2f(resLoc, canvas.width, canvas.height);\n }\n\n const seedLoc = glCtx.getUniformLocation(prog, \"u_seed\");\n if (seedLoc) {\n glCtx.uniform1f(seedLoc, currentState.seed);\n }\n\n const timeLoc = glCtx.getUniformLocation(prog, \"u_time\");\n if (timeLoc) {\n const elapsed = (performance.now() - startTime) / 1000;\n glCtx.uniform1f(timeLoc, elapsed);\n }\n\n // Parameter uniforms: u_paramName → state.params[paramName]\n for (const uName of uniformNames.params) {\n const loc = glCtx.getUniformLocation(prog, uName);\n if (!loc) continue;\n // Strip u_ prefix to get param key\n const paramKey = uName.substring(2);\n const value = currentState.params[paramKey];\n if (value !== undefined) {\n glCtx.uniform1f(loc, value);\n }\n }\n\n // Color uniforms: u_color1 → state.colorPalette[0], etc.\n for (const uName of uniformNames.colors) {\n const loc = glCtx.getUniformLocation(prog, uName);\n if (!loc) continue;\n // Extract 1-indexed number from u_colorN\n const idx = parseInt(uName.replace(\"u_color\", \"\"), 10) - 1;\n const hex = currentState.colorPalette[idx];\n if (hex) {\n const [r, g, b] = hexToVec3(hex);\n glCtx.uniform3f(loc, r, g, b);\n }\n }\n }\n\n function renderFrame() {\n if (!gl || !program || !vao) return;\n\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.useProgram(program);\n bindUniforms(gl, program);\n\n gl.bindVertexArray(vao);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n gl.bindVertexArray(null);\n }\n\n function animationLoop() {\n if (!animating) return;\n renderFrame();\n animationFrameId = requestAnimationFrame(animationLoop);\n }\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n canvasEl = document.createElement(\"canvas\");\n canvasEl.width = canvas.width;\n canvasEl.height = canvas.height;\n\n const density = canvas.pixelDensity ?? 1;\n if (density !== 1) {\n canvasEl.width = canvas.width * density;\n canvasEl.height = canvas.height * density;\n canvasEl.style.width = `${canvas.width}px`;\n canvasEl.style.height = `${canvas.height}px`;\n }\n\n el.appendChild(canvasEl);\n\n gl = canvasEl.getContext(\"webgl2\", {\n preserveDrawingBuffer: true,\n });\n if (!gl) throw new Error(\"WebGL2 is not supported\");\n\n // Compile and link shaders\n const vertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSource);\n const fragShader = compileShader(\n gl,\n gl.FRAGMENT_SHADER,\n fragmentSource,\n );\n\n program = gl.createProgram();\n if (!program) throw new Error(\"Failed to create WebGL program\");\n gl.attachShader(program, vertShader);\n gl.attachShader(program, fragShader);\n gl.linkProgram(program);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const info = gl.getProgramInfoLog(program);\n throw new Error(`Program linking error: ${info}`);\n }\n\n // Clean up individual shaders (linked into program)\n gl.deleteShader(vertShader);\n gl.deleteShader(fragShader);\n\n // Set up fullscreen quad (two triangles covering clip space)\n // prettier-ignore\n const positions = new Float32Array([\n -1, -1, 1, -1, -1, 1,\n -1, 1, 1, -1, 1, 1,\n ]);\n\n positionBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);\n\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n const aPosition = gl.getAttribLocation(program, \"a_position\");\n gl.enableVertexAttribArray(aPosition);\n gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);\n\n gl.bindVertexArray(null);\n\n startTime = performance.now();\n animating = true;\n animationLoop();\n },\n\n unmount() {\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n animating = false;\n\n if (gl) {\n if (vao) gl.deleteVertexArray(vao);\n if (positionBuffer) gl.deleteBuffer(positionBuffer);\n if (program) gl.deleteProgram(program);\n }\n\n if (canvasEl && container) {\n container.removeChild(canvasEl);\n }\n\n gl = null;\n program = null;\n vao = null;\n positionBuffer = null;\n canvasEl = null;\n container = null;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState };\n // Uniforms are rebound on the next frame\n if (!animating) {\n renderFrame();\n }\n },\n\n redraw() {\n renderFrame();\n },\n\n pause() {\n animating = false;\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n },\n\n resume() {\n if (!animating) {\n animating = true;\n animationLoop();\n }\n },\n\n get isAnimating() {\n return animating;\n },\n\n async captureFrame(options?: CaptureOptions): Promise<string> {\n if (!canvasEl) throw new Error(\"Sketch is not mounted\");\n const format = options?.format ?? \"png\";\n const quality = options?.quality ?? 1.0;\n const mimeType =\n format === \"jpeg\"\n ? \"image/jpeg\"\n : format === \"webp\"\n ? \"image/webp\"\n : \"image/png\";\n return canvasEl.toDataURL(mimeType, quality);\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!canvasEl || !gl) throw new Error(\"Sketch is not mounted\");\n\n const width = gl.drawingBufferWidth;\n const height = gl.drawingBufferHeight;\n const pixels = new Uint8Array(width * height * 4);\n gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);\n\n // WebGL pixels are bottom-up — flip vertically\n const flipped = new Uint8Array(width * height * 4);\n const rowSize = width * 4;\n for (let y = 0; y < height; y++) {\n const srcOffset = y * rowSize;\n const dstOffset = (height - 1 - y) * rowSize;\n flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);\n }\n\n return new ImageData(\n new Uint8ClampedArray(flipped.buffer),\n width,\n height,\n );\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n const el = document.createElement(\"div\");\n el.style.position = \"absolute\";\n el.style.left = \"-9999px\";\n document.body.appendChild(el);\n\n try {\n const instance = this.createInstance(compiled, state, canvas);\n instance.mount(el);\n\n // Wait for initial render\n await new Promise((resolve) => setTimeout(resolve, 50));\n\n const dataUrl = await instance.captureFrame(options);\n instance.dispose();\n\n const base64 = dataUrl.split(\",\")[1] ?? \"\";\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n } finally {\n document.body.removeChild(el);\n }\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const pixelDensity = sketch.canvas.pixelDensity ?? 1;\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n // Assemble full fragment source with component code injected\n const glslComponentCode = extractGLSLComponentCode(sketch.components);\n const fullAlgorithm = glslComponentCode\n ? injectGLSLSource(sketch.algorithm, glslComponentCode)\n : sketch.algorithm;\n\n // Extract uniforms from the full fragment shader for binding code\n const uniforms = extractUniforms(fullAlgorithm);\n const paramBindings = uniforms.params\n .map((u) => {\n const key = u.substring(2); // strip u_ prefix\n return ` { const loc = gl.getUniformLocation(program, \"${u}\"); if (loc && state.params[\"${key}\"] !== undefined) gl.uniform1f(loc, state.params[\"${key}\"]); }`;\n })\n .join(\"\\n\");\n\n const colorBindings = uniforms.colors\n .map((u) => {\n const idx = parseInt(u.replace(\"u_color\", \"\"), 10) - 1;\n return ` { const loc = gl.getUniformLocation(program, \"${u}\"); if (loc && state.colorPalette[${idx}]) { const c = state.colorPalette[${idx}].replace('#',''); gl.uniform3f(loc, parseInt(c.substring(0,2),16)/255, parseInt(c.substring(2,4),16)/255, parseInt(c.substring(4,6),16)/255); } }`;\n })\n .join(\"\\n\");\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #111; }\n canvas { display: block; max-width: 100vw; max-height: 100vh; }\n </style>\n</head>\n<body>\n <canvas id=\"canvas\" width=\"${width * pixelDensity}\" height=\"${height * pixelDensity}\" style=\"width:${width}px;height:${height}px;\"></canvas>\n <script>\n const state = ${stateJson};\n\n const canvas = document.getElementById('canvas');\n const gl = canvas.getContext('webgl2', { preserveDrawingBuffer: true });\n if (!gl) { document.body.textContent = 'WebGL2 not supported'; throw new Error('No WebGL2'); }\n\n // Vertex shader: fullscreen quad\n const vertSrc = \\`${FULLSCREEN_QUAD_VERTEX}\\`;\n\n // Fragment shader\n const fragSrc = \\`${fullAlgorithm.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\").replace(/\\$/g, \"\\\\$\")}\\`;\n\n function createShader(type, src) {\n const s = gl.createShader(type);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));\n return s;\n }\n\n const program = gl.createProgram();\n gl.attachShader(program, createShader(gl.VERTEX_SHADER, vertSrc));\n gl.attachShader(program, createShader(gl.FRAGMENT_SHADER, fragSrc));\n gl.linkProgram(program);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program));\n\n const positions = new Float32Array([-1,-1, 1,-1, -1,1, -1,1, 1,-1, 1,1]);\n const buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);\n const vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n const aPos = gl.getAttribLocation(program, 'a_position');\n gl.enableVertexAttribArray(aPos);\n gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);\n gl.bindVertexArray(null);\n\n const startTime = performance.now();\n function render() {\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.useProgram(program);\n\n // Built-in uniforms\n { const loc = gl.getUniformLocation(program, 'u_resolution'); if (loc) gl.uniform2f(loc, ${width}, ${height}); }\n { const loc = gl.getUniformLocation(program, 'u_seed'); if (loc) gl.uniform1f(loc, state.seed); }\n { const loc = gl.getUniformLocation(program, 'u_time'); if (loc) gl.uniform1f(loc, (performance.now() - startTime) / 1000); }\n\n // Parameter uniforms\n${paramBindings}\n\n // Color uniforms\n${colorBindings}\n\n gl.bindVertexArray(vao);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n gl.bindVertexArray(null);\n requestAnimationFrame(render);\n }\n render();\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `#version 300 es\nprecision highp float;\nuniform vec2 u_resolution;\nuniform float u_time;\nuniform float u_seed;\nuniform float u_noiseScale; // mapped from state.params.noiseScale\nuniform vec3 u_color1; // mapped from state.colorPalette[0]\nout vec4 fragColor;\nvoid main() {\n vec2 uv = gl_FragCoord.xy / u_resolution;\n fragColor = vec4(uv, 0.5 + 0.5 * sin(u_time), 1.0);\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n // GLSL runs on WebGL — no external CDN dependency\n return [];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type {\n RendererType,\n SketchState,\n CanvasSpec,\n SketchDefinition,\n} from \"@genart-dev/format\";\nimport type { ResolvedComponent } from \"@genart-dev/components\";\nimport type {\n RendererAdapter,\n ValidationResult,\n CompiledAlgorithm,\n SketchInstance,\n CaptureOptions,\n RuntimeDependency,\n} from \"../../types.js\";\nimport { extractComponentCode } from \"./component-utils.js\";\n\n/**\n * Compiled SVG algorithm — wraps the algorithm source string\n * and a factory function for creating SVG sketches.\n */\ninterface SVGCompiledAlgorithm {\n source: string;\n factory: (\n state: SketchState & { canvas: CanvasSpec },\n ) => Record<string, unknown>;\n}\n\n/**\n * SVG Renderer Adapter — full implementation.\n *\n * Validates algorithms for the `sketch(state)` function signature,\n * compiles them into executable factories, and creates live sketch instances.\n * SVG sketches are static — there is no animation loop.\n */\nexport class SVGRendererAdapter implements RendererAdapter {\n readonly type: RendererType = \"svg\";\n readonly displayName = \"SVG\";\n readonly algorithmLanguage = \"javascript\" as const;\n\n validate(algorithm: string): ValidationResult {\n if (!algorithm || algorithm.trim().length === 0) {\n return { valid: false, errors: [\"Algorithm source is empty\"] };\n }\n // Check for sketch function signature\n const hasSketchFn =\n /function\\s+sketch\\s*\\(\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*(?:function\\s*)?\\(\\s*state\\s*\\)/.test(algorithm) ||\n /(?:const|let|var)\\s+sketch\\s*=\\s*\\(\\s*state\\s*\\)\\s*=>/.test(algorithm);\n\n if (!hasSketchFn) {\n return {\n valid: false,\n errors: [\n \"SVG algorithms must export a function with signature: function sketch(state)\",\n ],\n };\n }\n return { valid: true, errors: [] };\n }\n\n async compile(algorithm: string, components?: ResolvedComponent[]): Promise<CompiledAlgorithm> {\n const validation = this.validate(algorithm);\n if (!validation.valid) {\n throw new Error(\n `SVG compilation failed: ${validation.errors.join(\"; \")}`,\n );\n }\n\n const componentCode = components?.map(c =>\n `// --- ${c.name} v${c.version} ---\\n${c.code}`\n ).join('\\n\\n') ?? '';\n\n const wrappedSource = `\n return (function() {\n ${componentCode}\n ${algorithm}\n return sketch;\n })();\n `;\n\n try {\n const factory = new Function(wrappedSource) as () => (\n state: SketchState & { canvas: CanvasSpec },\n ) => Record<string, unknown>;\n const compiled: SVGCompiledAlgorithm = {\n source: algorithm,\n factory: factory(),\n };\n return compiled;\n } catch (err) {\n throw new Error(\n `SVG compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n createInstance(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n ): SketchInstance {\n const { factory } = compiled as SVGCompiledAlgorithm;\n\n let container: HTMLElement | null = null;\n let currentState = { ...state, canvas };\n let sketchModule: Record<string, unknown> | null = null;\n\n function regenerate() {\n if (!container || !sketchModule) return;\n if (typeof sketchModule[\"generate\"] === \"function\") {\n const svgString = (sketchModule[\"generate\"] as () => string)();\n container.innerHTML = svgString;\n }\n }\n\n const instance: SketchInstance = {\n mount(el: HTMLElement) {\n container = el;\n sketchModule = factory(currentState);\n regenerate();\n },\n\n unmount() {\n if (container) {\n container.innerHTML = \"\";\n }\n container = null;\n sketchModule = null;\n },\n\n updateState(newState: SketchState) {\n currentState = { ...newState, canvas };\n // Recreate the sketch module with the new state\n sketchModule = factory(currentState);\n regenerate();\n },\n\n redraw() {\n regenerate();\n },\n\n pause() {\n // No-op: SVG is static\n },\n\n resume() {\n // No-op: SVG is static\n },\n\n get isAnimating() {\n return false;\n },\n\n async captureFrame(_options?: CaptureOptions): Promise<string> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const svgEl = container.querySelector(\"svg\");\n if (!svgEl) throw new Error(\"No SVG element found\");\n\n const serializer = new XMLSerializer();\n const svgString = serializer.serializeToString(svgEl);\n const base64 = btoa(unescape(encodeURIComponent(svgString)));\n return `data:image/svg+xml;base64,${base64}`;\n },\n\n async captureImageData(): Promise<ImageData> {\n if (!container) throw new Error(\"Sketch is not mounted\");\n const svgEl = container.querySelector(\"svg\");\n if (!svgEl) throw new Error(\"No SVG element found\");\n\n // Render SVG to an offscreen canvas via Image\n const serializer = new XMLSerializer();\n const svgString = serializer.serializeToString(svgEl);\n const blob = new Blob([svgString], { type: \"image/svg+xml\" });\n const url = URL.createObjectURL(blob);\n\n const img = new Image();\n await new Promise<void>((resolve, reject) => {\n img.onload = () => resolve();\n img.onerror = () => reject(new Error(\"Failed to load SVG as image\"));\n img.src = url;\n });\n\n const offscreen = document.createElement(\"canvas\");\n offscreen.width = canvas.width;\n offscreen.height = canvas.height;\n const ctx = offscreen.getContext(\"2d\");\n if (!ctx) throw new Error(\"Cannot get 2D context\");\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n URL.revokeObjectURL(url);\n\n return ctx.getImageData(0, 0, canvas.width, canvas.height);\n },\n\n dispose() {\n instance.unmount();\n },\n };\n\n return instance;\n }\n\n async renderOffscreen(\n compiled: CompiledAlgorithm,\n state: SketchState,\n canvas: CanvasSpec,\n _options?: CaptureOptions,\n ): Promise<Uint8Array | Blob> {\n const { factory } = compiled as SVGCompiledAlgorithm;\n const stateWithCanvas = { ...state, canvas };\n const module = factory(stateWithCanvas);\n\n let svgString: string;\n if (typeof module[\"generate\"] === \"function\") {\n svgString = (module[\"generate\"] as () => string)();\n } else {\n throw new Error(\"SVG sketch module must have a generate() method\");\n }\n\n // Encode SVG string as UTF-8 Uint8Array\n const encoder = new TextEncoder();\n return encoder.encode(svgString);\n }\n\n generateStandaloneHTML(sketch: SketchDefinition): string {\n const { width, height } = sketch.canvas;\n const stateJson = JSON.stringify(sketch.state, null, 2);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(sketch.title)}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #111; }\n #svg-container svg { display: block; width: 100%; height: auto; max-width: 100vw; max-height: 100vh; }\n </style>\n</head>\n<body>\n <div id=\"svg-container\"></div>\n <script>\n const state = ${stateJson};\n state.canvas = { width: ${width}, height: ${height} };\n\n ${extractComponentCode(sketch.components)}\n ${sketch.algorithm}\n\n const module = sketch(state);\n const svgString = module.generate ? module.generate() : module.initializeSystem();\n document.getElementById('svg-container').innerHTML = svgString;\n </script>\n</body>\n</html>`;\n }\n\n getAlgorithmTemplate(): string {\n return `function sketch(state) {\n const { width, height } = state.canvas;\n function generate() {\n return \\`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"\\${width}\" height=\"\\${height}\" viewBox=\"0 0 \\${width} \\${height}\">\n <!-- generated elements -->\n </svg>\\`;\n }\n return { generate, initializeSystem: generate };\n}`;\n }\n\n getRuntimeDependencies(): RuntimeDependency[] {\n // SVG has no external dependencies\n return [];\n }\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n","import type { RendererType } from \"@genart-dev/format\";\nimport type { RendererAdapter } from \"../types.js\";\nimport { P5RendererAdapter } from \"./adapters/p5.js\";\nimport { Canvas2DRendererAdapter } from \"./adapters/canvas2d.js\";\nimport { ThreeRendererAdapter } from \"./adapters/three.js\";\nimport { GLSLRendererAdapter } from \"./adapters/glsl.js\";\nimport { SVGRendererAdapter } from \"./adapters/svg.js\";\n\n/**\n * Registry for renderer adapters. Manages registration and lookup\n * of RendererAdapter implementations by renderer type.\n */\nexport class RendererRegistry {\n private readonly adapters = new Map<RendererType, RendererAdapter>();\n private defaultType: RendererType = \"p5\";\n\n /**\n * Register a renderer adapter. Replaces any existing adapter for the same type.\n */\n register(adapter: RendererAdapter): void {\n this.adapters.set(adapter.type, adapter);\n }\n\n /**\n * Resolve a renderer adapter by type.\n * If type is undefined, returns the default adapter (p5 — v1.0 compat).\n *\n * @throws Error if the type is not registered.\n */\n resolve(type?: RendererType): RendererAdapter {\n const resolvedType = type ?? this.defaultType;\n const adapter = this.adapters.get(resolvedType);\n if (!adapter) {\n const available = [...this.adapters.keys()].join(\", \");\n throw new Error(\n `Unknown renderer type \"${resolvedType}\". Registered types: ${available || \"(none)\"}`,\n );\n }\n return adapter;\n }\n\n /**\n * List all registered renderer types.\n */\n list(): RendererType[] {\n return [...this.adapters.keys()];\n }\n\n /**\n * Get the default renderer adapter (p5).\n */\n getDefault(): RendererAdapter {\n return this.resolve(this.defaultType);\n }\n\n /**\n * Check if a renderer type is registered.\n */\n has(type: RendererType): boolean {\n return this.adapters.has(type);\n }\n}\n\n/**\n * Create a RendererRegistry pre-loaded with all 5 renderer adapters.\n * This is the standard way to get a registry instance.\n */\nexport function createDefaultRegistry(): RendererRegistry {\n const registry = new RendererRegistry();\n registry.register(new P5RendererAdapter());\n registry.register(new Canvas2DRendererAdapter());\n registry.register(new ThreeRendererAdapter());\n registry.register(new GLSLRendererAdapter());\n registry.register(new SVGRendererAdapter());\n return registry;\n}\n","import type { SkillDefinition } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Composition Theory Skills (Arnheim, Wong)\n// ---------------------------------------------------------------------------\n\nexport const COMPOSITION_SKILLS: readonly SkillDefinition[] = [\n {\n id: \"golden-ratio\",\n name: \"Golden Ratio\",\n category: \"composition\",\n complexity: \"intermediate\",\n description:\n \"Use the golden ratio (1:1.618) to create naturally harmonious proportions and spiral compositions.\",\n theory: `The golden ratio (phi, approximately 1.618) appears throughout nature and has been used in art and architecture for millennia. In generative art, it provides a mathematical foundation for creating compositions that feel naturally balanced.\n\nThe golden rectangle can be recursively subdivided, creating a spiral that guides the viewer's eye. Elements placed along this spiral or at golden section points create visual harmony without the rigidity of symmetric layouts.\n\nKey applications in generative art:\n- Divide the canvas at golden ratio points (61.8% / 38.2%) for element placement\n- Use the golden spiral as a path for distributing elements\n- Scale recursive elements by phi for self-similar patterns\n- Apply phi to spacing, margins, and proportional relationships`,\n principles: [\n \"Divide compositions at 61.8% / 38.2% rather than halves\",\n \"Place focal elements at golden section intersections\",\n \"Use the golden spiral to guide element distribution\",\n \"Scale nested or recursive elements by phi (1.618) or 1/phi (0.618)\",\n \"Apply golden proportions to negative space as well as positive forms\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n { title: \"Principles of Form and Design\", author: \"Wucius Wong\", year: 1993 },\n ],\n suggestedParameters: [\n { key: \"phi\", label: \"Golden Ratio\", min: 1.0, max: 2.0, step: 0.001, default: 1.618 },\n { key: \"subdivisions\", label: \"Subdivisions\", min: 1, max: 12, step: 1, default: 6 },\n ],\n },\n {\n id: \"rule-of-thirds\",\n name: \"Rule of Thirds\",\n category: \"composition\",\n complexity: \"beginner\",\n description:\n \"Divide the canvas into a 3x3 grid and place key elements at intersection points for dynamic balance.\",\n theory: `The rule of thirds is one of the most fundamental composition techniques. By dividing the canvas into nine equal sections with two horizontal and two vertical lines, artists create four \"power points\" at the intersections where the viewer's eye naturally rests.\n\nIn generative art, this grid serves as an anchor system. Rather than centering elements (which creates static compositions), placing density clusters, color accents, or focal geometries at third-line intersections produces dynamic, engaging layouts.\n\nThis rule also applies to the distribution of visual weight: roughly two-thirds of the canvas can be one tone or density, with the remaining third providing contrast.`,\n principles: [\n \"Place primary focal elements at one of the four intersection points\",\n \"Align dominant lines (horizons, divisions) with the third lines, not center\",\n \"Distribute visual weight asymmetrically: 2/3 to 1/3 ratio\",\n \"Use the grid to create tension between filled and empty areas\",\n \"Multiple elements should occupy different intersection points\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n { title: \"Principles of Form and Design\", author: \"Wucius Wong\", year: 1993 },\n ],\n suggestedParameters: [\n { key: \"gridDivisions\", label: \"Grid Divisions\", min: 2, max: 8, step: 1, default: 3 },\n { key: \"focalStrength\", label: \"Focal Strength\", min: 0.1, max: 1.0, step: 0.1, default: 0.7 },\n ],\n },\n {\n id: \"visual-weight\",\n name: \"Visual Weight & Balance\",\n category: \"composition\",\n complexity: \"intermediate\",\n description:\n \"Create equilibrium through the distribution of visual weight — size, density, color intensity, and position.\",\n theory: `Every visual element carries \"weight\" determined by its size, color intensity, texture density, and position relative to the canvas center. Rudolf Arnheim's research showed that viewers perceive compositions as balanced or imbalanced based on this aggregate weight distribution.\n\nIn generative art, visual weight manifests through:\n- **Size**: Larger elements carry more weight\n- **Value contrast**: High-contrast elements are heavier than low-contrast ones\n- **Color saturation**: Saturated colors are heavier than muted ones\n- **Density**: Clusters of small elements can balance a single large one\n- **Position**: Elements farther from center exert more leverage (like a seesaw)\n\nBalance can be symmetrical (formal, stable), asymmetrical (dynamic, interesting), or radial (emanating from center).`,\n principles: [\n \"A small, high-contrast element can balance a large, low-contrast one\",\n \"Elements farther from the center carry more compositional weight\",\n \"Asymmetrical balance creates more visual interest than symmetry\",\n \"Distribute density gradients to create directional visual flow\",\n \"Empty space (negative space) has visual weight and must be balanced too\",\n \"Color saturation and value contribute independently to perceived weight\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n ],\n suggestedParameters: [\n { key: \"balancePoint\", label: \"Balance Point\", min: 0.2, max: 0.8, step: 0.05, default: 0.5 },\n { key: \"weightContrast\", label: \"Weight Contrast\", min: 0.1, max: 2.0, step: 0.1, default: 1.0 },\n ],\n },\n {\n id: \"gestalt-grouping\",\n name: \"Gestalt Grouping\",\n category: \"composition\",\n complexity: \"intermediate\",\n description:\n \"Apply Gestalt principles — proximity, similarity, closure, continuity — to organize elements into perceived wholes.\",\n theory: `Gestalt psychology reveals how humans perceive visual elements as organized groups rather than isolated parts. These principles are powerful tools for generative artists:\n\n- **Proximity**: Elements close together are perceived as a group. Control spacing to create clusters or separations.\n- **Similarity**: Elements sharing color, size, or shape are grouped. Use gradual variation to create sub-groups.\n- **Closure**: The mind completes incomplete shapes. Leave gaps in patterns — viewers will fill them in.\n- **Continuity**: Elements arranged along a line or curve are perceived as related. Use flow fields or parametric curves.\n- **Figure-Ground**: The relationship between foreground elements and background space defines the composition.\n\nIn generative art, these principles help create readable structure from potentially chaotic algorithms.`,\n principles: [\n \"Use proximity (spacing) as the primary grouping mechanism\",\n \"Vary one property (color, size) while keeping others constant to create similarity groups\",\n \"Leave intentional gaps for the viewer's mind to complete (closure)\",\n \"Arrange elements along implied lines or curves for continuity\",\n \"Ensure clear figure-ground separation at all parameter settings\",\n \"Layer multiple Gestalt principles for complex but readable compositions\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n { title: \"Principles of Form and Design\", author: \"Wucius Wong\", year: 1993 },\n ],\n suggestedParameters: [\n { key: \"groupSpacing\", label: \"Group Spacing\", min: 0.5, max: 5.0, step: 0.1, default: 2.0 },\n { key: \"similarity\", label: \"Similarity\", min: 0.0, max: 1.0, step: 0.05, default: 0.8 },\n { key: \"elementCount\", label: \"Element Count\", min: 10, max: 500, step: 10, default: 100 },\n ],\n },\n {\n id: \"figure-ground\",\n name: \"Figure-Ground Relationship\",\n category: \"composition\",\n complexity: \"beginner\",\n description:\n \"Control the interplay between positive forms (figure) and negative space (ground) for clarity and ambiguity.\",\n theory: `The figure-ground relationship is the most fundamental perceptual organization. Every composition consists of figures (perceived objects) and ground (the space around and between them).\n\nStrong figure-ground contrast creates clarity and focus. Deliberate ambiguity — where figure and ground are interchangeable — creates visual puzzles that engage viewers (as in M.C. Escher's tessellations).\n\nIn generative art, controlling figure-ground means managing:\n- Value contrast between elements and background\n- Edge definition (sharp vs. soft boundaries)\n- Density distribution (clustered elements read as figure)\n- Reversibility (can the viewer flip perception?)`,\n principles: [\n \"Maintain sufficient contrast between figure and ground for readability\",\n \"Use value (light/dark) as the primary figure-ground separator\",\n \"Create deliberate ambiguity for visual interest when appropriate\",\n \"Small enclosed areas tend to be perceived as figure; large areas as ground\",\n \"Convex shapes are more likely perceived as figure than concave ones\",\n ],\n references: [\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n ],\n suggestedParameters: [\n { key: \"contrast\", label: \"Figure-Ground Contrast\", min: 0.1, max: 1.0, step: 0.05, default: 0.7 },\n { key: \"density\", label: \"Figure Density\", min: 0.1, max: 0.9, step: 0.05, default: 0.4 },\n ],\n },\n {\n id: \"rhythm-movement\",\n name: \"Rhythm & Movement\",\n category: \"composition\",\n complexity: \"advanced\",\n description:\n \"Create visual rhythm through repetition, variation, and progression to guide the viewer's eye across the composition.\",\n theory: `Rhythm in visual art functions like rhythm in music — it creates patterns of emphasis and rest that move the viewer's eye through the composition. Wucius Wong identifies several types of visual rhythm:\n\n- **Regular rhythm**: Consistent repetition of identical elements at equal intervals. Creates order and predictability.\n- **Alternating rhythm**: Two or more elements or spacings alternate. Creates more complex patterns.\n- **Progressive rhythm**: Elements gradually change in size, color, spacing, or orientation. Creates directional movement.\n- **Flowing rhythm**: Elements follow organic, curving paths. Creates natural, fluid movement.\n- **Random rhythm**: Irregular repetition with controlled variation. Creates controlled chaos.\n\nIn generative art, rhythm emerges from the interplay between your algorithm's regularity and its stochastic variation. The seed controls the specific instance; the parameters control the type and intensity of rhythm.`,\n principles: [\n \"Establish a base rhythm through regular repetition before introducing variation\",\n \"Use progressive changes in size or spacing to create directional movement\",\n \"Alternate between tension (clustering) and release (spacing) zones\",\n \"Let flow fields or parametric curves create natural movement paths\",\n \"Control the ratio of regularity to randomness via parameters\",\n \"Use acceleration/deceleration in element distribution for energy\",\n ],\n references: [\n { title: \"Principles of Form and Design\", author: \"Wucius Wong\", year: 1993 },\n { title: \"Art and Visual Perception\", author: \"Rudolf Arnheim\", year: 1954 },\n ],\n suggestedParameters: [\n { key: \"frequency\", label: \"Rhythm Frequency\", min: 1, max: 20, step: 1, default: 8 },\n { key: \"variation\", label: \"Variation\", min: 0.0, max: 1.0, step: 0.05, default: 0.3 },\n { key: \"flow\", label: \"Flow Strength\", min: 0.0, max: 2.0, step: 0.1, default: 0.5 },\n ],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Color Theory Skills (Albers, Itten)\n// ---------------------------------------------------------------------------\n\nexport const COLOR_SKILLS: readonly SkillDefinition[] = [\n {\n id: \"color-harmony\",\n name: \"Color Harmony Systems\",\n category: \"color\",\n complexity: \"beginner\",\n description:\n \"Use systematic color relationships — complementary, analogous, triadic, split-complementary — for harmonious palettes.\",\n theory: `Color harmony describes combinations of colors that are aesthetically pleasing. Johannes Itten formalized these relationships using the color wheel:\n\n- **Complementary**: Colors opposite on the wheel (e.g., blue/orange). Maximum contrast, vibrant when juxtaposed.\n- **Analogous**: 2-4 adjacent colors on the wheel. Harmonious and calm, low contrast.\n- **Triadic**: Three colors equally spaced (120° apart). Balanced and vibrant.\n- **Split-complementary**: A color plus the two colors adjacent to its complement. High contrast with less tension.\n- **Tetradic**: Two pairs of complementary colors. Rich and complex.\n\nIn generative art, these systems provide algorithmic palette generation. Start with a base hue, then calculate harmonious companions using angular relationships on the HSL color wheel.`,\n principles: [\n \"Choose one dominant color and use harmonics as accents (60-30-10 rule)\",\n \"Complementary pairs create maximum vibrance — use for focal contrast\",\n \"Analogous schemes work well for atmospheric, mood-driven pieces\",\n \"Vary saturation and value within a harmonic scheme for depth\",\n \"Use triadic schemes when you need balanced variety without chaos\",\n ],\n references: [\n { title: \"The Art of Color\", author: \"Johannes Itten\", year: 1961 },\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n ],\n suggestedParameters: [\n { key: \"baseHue\", label: \"Base Hue\", min: 0, max: 360, step: 1, default: 200 },\n { key: \"harmonyAngle\", label: \"Harmony Angle\", min: 15, max: 180, step: 5, default: 120 },\n ],\n suggestedColors: [\n { key: \"base\", label: \"Base Color\", default: \"#2196f3\" },\n { key: \"accent\", label: \"Accent Color\", default: \"#ff9800\" },\n ],\n },\n {\n id: \"simultaneous-contrast\",\n name: \"Simultaneous Contrast\",\n category: \"color\",\n complexity: \"advanced\",\n description:\n \"Exploit how adjacent colors alter each other's perceived hue, value, and saturation — the core of Albers' teaching.\",\n theory: `Josef Albers spent decades demonstrating that color is the most relative medium in art. The same color appears dramatically different depending on its surroundings:\n\n- A gray square on a black background appears lighter than the same gray on white\n- A neutral color surrounded by red appears to shift toward green (and vice versa)\n- Small color areas are more affected by their surroundings than large ones\n\nThis phenomenon — simultaneous contrast — means that in generative art, you cannot choose colors in isolation. The same palette will look different depending on element sizes, spacing, and layering order.\n\nPractical implications:\n- Test colors in context, not in isolation\n- Adjacent complementary colors intensify each other\n- Adjacent similar colors reduce each other's saturation\n- Background color dramatically shifts perception of all foreground elements`,\n principles: [\n \"The same color will appear different depending on what surrounds it\",\n \"Adjacent complementary colors intensify each other (vibration effect)\",\n \"Small color areas are dominated by surrounding colors\",\n \"Background color shifts the perceived hue of all foreground elements\",\n \"Use simultaneous contrast deliberately to create optical effects\",\n \"Test palette choices at various element sizes — effects change with scale\",\n ],\n references: [\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n ],\n suggestedParameters: [\n { key: \"elementSize\", label: \"Element Size\", min: 2, max: 100, step: 1, default: 20 },\n { key: \"borderWidth\", label: \"Border Width\", min: 0, max: 10, step: 0.5, default: 0 },\n ],\n },\n {\n id: \"color-temperature\",\n name: \"Color Temperature\",\n category: \"color\",\n complexity: \"beginner\",\n description:\n \"Use warm (red/orange/yellow) and cool (blue/green/violet) color relationships to create depth and emotional tone.\",\n theory: `Color temperature divides the spectrum into warm colors (reds, oranges, yellows) and cool colors (blues, greens, violets). This division has profound perceptual and emotional effects:\n\n**Spatial effects**: Warm colors appear to advance (come toward the viewer) while cool colors recede. This creates an automatic sense of depth without perspective geometry.\n\n**Emotional associations**: Warm colors evoke energy, passion, urgency. Cool colors evoke calm, distance, contemplation.\n\n**Temperature contrast**: The tension between warm and cool areas creates visual energy. A predominantly cool composition with a warm accent immediately draws the eye to the accent.\n\nIn generative art, map temperature to depth layers: cool backgrounds, warm foregrounds. Or use temperature gradients across the composition to create directional flow.`,\n principles: [\n \"Warm colors advance, cool colors recede — use for spatial depth\",\n \"A small warm accent in a cool composition creates a strong focal point\",\n \"Temperature contrast is as important as value contrast for composition\",\n \"Map color temperature to z-depth or layering order\",\n \"Use temperature gradients to create directional energy flow\",\n ],\n references: [\n { title: \"The Art of Color\", author: \"Johannes Itten\", year: 1961 },\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n ],\n suggestedParameters: [\n { key: \"warmth\", label: \"Warmth\", min: 0.0, max: 1.0, step: 0.05, default: 0.5 },\n { key: \"temperatureRange\", label: \"Temperature Range\", min: 30, max: 180, step: 10, default: 90 },\n ],\n suggestedColors: [\n { key: \"warm\", label: \"Warm Tone\", default: \"#ff6b35\" },\n { key: \"cool\", label: \"Cool Tone\", default: \"#4a90d9\" },\n ],\n },\n {\n id: \"itten-contrasts\",\n name: \"Itten's Seven Contrasts\",\n category: \"color\",\n complexity: \"advanced\",\n description:\n \"Apply Itten's systematic framework of seven color contrasts to create specific visual effects.\",\n theory: `Johannes Itten identified seven fundamental types of color contrast, each producing distinct visual effects:\n\n1. **Contrast of Hue**: Pure hues side by side (red, blue, yellow). Maximum color variety.\n2. **Light-Dark Contrast**: Value differences. The strongest structural contrast.\n3. **Cold-Warm Contrast**: Temperature opposition. Creates spatial depth.\n4. **Complementary Contrast**: Opposite hues. Each intensifies the other.\n5. **Simultaneous Contrast**: Perceived color shift caused by adjacency.\n6. **Contrast of Saturation**: Pure vs. muted colors. Creates focus hierarchy.\n7. **Contrast of Extension**: Relative area sizes of colors. Balances visual weight.\n\nEach contrast type can be parameterized in generative art. A single piece might employ multiple contrasts simultaneously, with parameters controlling the intensity of each.`,\n principles: [\n \"Light-dark contrast provides the structural backbone of any composition\",\n \"Use saturation contrast to create hierarchy: saturated = focal, muted = ambient\",\n \"Complementary contrast creates energy; analogous reduces it\",\n \"Contrast of extension: balance area ratios to color intensity (bright colors need less area)\",\n \"Layer multiple contrast types for visual complexity\",\n \"Control contrast intensity through parameters for exploration\",\n ],\n references: [\n { title: \"The Art of Color\", author: \"Johannes Itten\", year: 1961 },\n ],\n suggestedParameters: [\n { key: \"hueContrast\", label: \"Hue Contrast\", min: 0.0, max: 1.0, step: 0.05, default: 0.5 },\n { key: \"valueContrast\", label: \"Value Contrast\", min: 0.1, max: 1.0, step: 0.05, default: 0.7 },\n { key: \"saturationContrast\", label: \"Saturation Contrast\", min: 0.0, max: 1.0, step: 0.05, default: 0.4 },\n ],\n },\n {\n id: \"value-structure\",\n name: \"Value Structure\",\n category: \"color\",\n complexity: \"intermediate\",\n description:\n \"Organize compositions through light-dark value patterns — the foundation that underlies all color decisions.\",\n theory: `Value (lightness/darkness) is the most important property of color for composition. A piece that works in grayscale will work in any palette; a piece that fails in grayscale cannot be saved by color alone.\n\nValue structure means planning the distribution of lights, mid-tones, and darks across the composition. Classic approaches include:\n\n- **High-key**: Predominantly light values. Airy, ethereal, optimistic.\n- **Low-key**: Predominantly dark values. Dramatic, mysterious, intense.\n- **Full-range**: Full spectrum from near-white to near-black. Maximum contrast and visual impact.\n- **Limited-range**: Narrow value band. Subtle, atmospheric, unified.\n\nIn generative art, map value to depth, density, or importance. Establish a value plan (the notan — simplified light/dark pattern) before adding color complexity.`,\n principles: [\n \"Squint at your output: if the value pattern is unclear, color won't help\",\n \"Limit your palette to 3-5 value steps for strong structure\",\n \"Reserve highest contrast for the focal area\",\n \"Use mid-tones for transitions and atmosphere\",\n \"Dark values carry more visual weight than light ones at equal size\",\n ],\n references: [\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n { title: \"The Art of Color\", author: \"Johannes Itten\", year: 1961 },\n ],\n suggestedParameters: [\n { key: \"valueRange\", label: \"Value Range\", min: 0.1, max: 1.0, step: 0.05, default: 0.8 },\n { key: \"keyValue\", label: \"Key Value\", min: 0.0, max: 1.0, step: 0.05, default: 0.3 },\n ],\n },\n {\n id: \"palette-generation\",\n name: \"Algorithmic Palette Generation\",\n category: \"color\",\n complexity: \"intermediate\",\n description:\n \"Generate cohesive color palettes algorithmically using perceptual color spaces and mathematical relationships.\",\n theory: `Traditional color theory works with the HSL/HSV color wheel, but perceptual uniformity is better achieved in modern color spaces like OKLCH (Oklab Lightness-Chroma-Hue).\n\nIn OKLCH:\n- **L** (lightness, 0-1): Perceptually uniform brightness steps\n- **C** (chroma, 0-0.4): Saturation/vibrancy\n- **H** (hue, 0-360): Hue angle\n\nAlgorithmic palette strategies:\n- **Fixed hue, varying L/C**: Monochromatic palette with perceptual uniformity\n- **Fixed L/C, varying H**: Evenly-spaced hues at consistent brightness (true equiluminant palette)\n- **Seed-based generation**: Use the sketch seed to derive a base hue, then calculate harmonics\n- **Gradient interpolation**: Interpolate between anchor colors in OKLCH for smooth transitions\n\nThe advantage of working in OKLCH over HSL is that equal mathematical steps produce equal perceptual steps — a gradient from dark blue to light blue will look evenly spaced rather than having a perceptual \"jump\" in the middle.`,\n principles: [\n \"Use OKLCH or Oklab for perceptually uniform color operations\",\n \"Generate palettes from seed + base hue for deterministic, explorable results\",\n \"Keep chroma (saturation) consistent across a palette for cohesion\",\n \"Vary lightness for value structure, hue for variety, chroma for energy\",\n \"Map parameter ranges to hue angles for intuitive color exploration\",\n \"Limit generated palettes to 3-7 colors for coherence\",\n ],\n references: [\n { title: \"Interaction of Color\", author: \"Josef Albers\", year: 1963 },\n ],\n suggestedParameters: [\n { key: \"baseHue\", label: \"Base Hue\", min: 0, max: 360, step: 1, default: 220 },\n { key: \"chroma\", label: \"Chroma\", min: 0.05, max: 0.35, step: 0.01, default: 0.15 },\n { key: \"paletteSize\", label: \"Palette Size\", min: 3, max: 7, step: 1, default: 5 },\n ],\n },\n];\n","import type { SkillDefinition } from \"../types.js\";\nimport { COMPOSITION_SKILLS, COLOR_SKILLS } from \"./skills.js\";\n\n/**\n * Registry for design knowledge skills.\n * Mirrors the RendererRegistry pattern.\n */\nexport class SkillRegistry {\n private readonly skills = new Map<string, SkillDefinition>();\n\n /** Register a skill definition. */\n register(skill: SkillDefinition): void {\n this.skills.set(skill.id, skill);\n }\n\n /** Resolve a skill by ID. Throws if not found. */\n resolve(id: string): SkillDefinition {\n const skill = this.skills.get(id);\n if (!skill) {\n throw new Error(`Unknown skill: '${id}'`);\n }\n return skill;\n }\n\n /** Get a skill by ID, or undefined if not found. */\n get(id: string): SkillDefinition | undefined {\n return this.skills.get(id);\n }\n\n /** List all skills, optionally filtered by category. */\n list(category?: string): SkillDefinition[] {\n const all = Array.from(this.skills.values());\n if (category) {\n return all.filter((s) => s.category === category);\n }\n return all;\n }\n\n /** Check if a skill ID is registered. */\n has(id: string): boolean {\n return this.skills.has(id);\n }\n\n /** Return unique categories across all registered skills. */\n categories(): string[] {\n const cats = new Set<string>();\n for (const skill of this.skills.values()) {\n cats.add(skill.category);\n }\n return Array.from(cats).sort();\n }\n}\n\n/**\n * Create a skill registry pre-loaded with all built-in skills.\n */\nexport function createDefaultSkillRegistry(): SkillRegistry {\n const registry = new SkillRegistry();\n for (const skill of [...COMPOSITION_SKILLS, ...COLOR_SKILLS]) {\n registry.register(skill);\n }\n return registry;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,0BAAc,+BAFd;AAKA,wBAOO;;;ACLA,SAAS,qBACd,YACQ;AACR,MAAI,CAAC,WAAY,QAAO;AAExB,QAAM,SAAmB,CAAC;AAC1B,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,UAAU,GAAG;AACtD,QAAI,OAAO,UAAU,SAAU;AAC/B,QAAI,MAAM,MAAM;AACd,YAAM,MAAM,MAAM,UAAU,KAAK,MAAM,OAAO,KAAK;AACnD,aAAO,KAAK,UAAU,IAAI,GAAG,GAAG;AAAA,EAAS,MAAM,IAAI,EAAE;AAAA,IACvD;AAAA,EACF;AACA,SAAO,OAAO,KAAK,MAAM;AAC3B;;;ACJA,IAAM,iBAAiB;AACvB,IAAM,aAAa,gDAAgD,cAAc;AAiB1E,IAAM,oBAAN,MAAmD;AAAA,EAC/C,OA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