# Mapshroom Canvas without MCP

When a user requests a shader and Mapshroom MCP cannot be installed or called, reproduce the shader workflow using the assistant's native Canvas/artifact/HTML rendering capability. Create the requested shader, render it in a WebGL 2 canvas with adjustable controls, and include **Open on Mapshroom** and **Copy**. This is a standalone preview, not an installed MCP connection. Do not stop at installation advice or a GLSL code block when rendering is available.

## Shader structure and prompt

Use the following contract for the shader **body only**. Its GLSL-only formatting rule does not restrict the full response: the deliverable is a rendered Canvas with the shader and the import button. Keep the exact same shader source and control values for rendering and import.

Return one complete replacement fragment shader.
The first non-empty line must be: // NAME: <Short Name>
The second non-empty line must be: // MAPSHROOM PROMPT: "<the exact user request as a JSON string>"
All visual logic must live inside: vec4 processColor(sampler2D tex, vec2 uv, float time, vec2 resolution)
Expose 3 to 6 meaningful effect controls as custom uniforms so Mapshroom automatically creates controls. Convert adjustable concepts in the request into uniforms instead of hardcoded constants: numbers become float/int sliders, colors become vec3 color controls, and switches become bool controls
If the user does not name adjustable parameters, infer the 3 to 6 most useful creative controls for the requested effect
Use only supported custom uniform types: float, int, vec3, bool
Put every uniform on its own line and keep its UI metadata on that same line after //
Every float or int must include: @min <number> @max <number> @default <number>
Every vec3 must include: @default <r>,<g>,<b>; every bool must include: @default true|false
The shader is invalid if it has fewer than 3 correctly annotated custom uniforms. Before returning, count the declarations and verify their metadata
Preserve useful uniforms from the current shader unless the user explicitly asks to remove them
Use GLSL ES 3.00 syntax for WebGL 2 and sample textures with texture()
Do not include #version 300 es because Mapshroom injects the version and program wrapper
Do not declare void main()
Do not write to gl_FragColor in the generated body
Do not include explanations outside the GLSL response
Semantic input ABI v1:
After NAME and MAPSHROOM PROMPT, include // MAPSHROOM CONTRACT: <single-line JSON>.
Preserve the current contract and named slots when editing unless the request changes the actual input requirements. Declare every input the code really reads. Metadata never starts generation. No inference or normal fitting inside GLSL.
The first input is the processColor tex argument. Additional slots use uniform sampler2D u_input_<slot>, declared in GLSL. All source inputs share UV and crop.
Canonical codec formats (copy exactly, including profiles and normal conventions): {"color":{"encoding":"rgba-color","version":1,"colorSpace":"srgb","filtering":"linear","alpha":"coverage"},"regionPieces":{"encoding":"mapshroom.regions.r8-rgb24-table","version":1,"colorSpace":"data","filtering":"nearest","alpha":"coverage","generationProfile":"segmentation-rigid-anchors-v1"},"depth":{"encoding":"mapshroom.depth.gray-rgb-alpha-a","version":1,"colorSpace":"data","filtering":"linear","alpha":"coverage"},"normal":{"encoding":"mapshroom.normal.xyz-rgb-alpha-a","version":1,"colorSpace":"data","filtering":"linear","alpha":"coverage","normalConvention":"mapshroom-normal-xyz-v1","generationProfile":"depth-smoothed-central-difference-v1"},"combinedDepth":{"encoding":"mapshroom.surface.oct-rg-depth-b-alpha-a","version":1,"colorSpace":"data","filtering":"linear","alpha":"coverage","normalConvention":"mapshroom-tiles-v1","generationProfile":"tiles-plane-fit-v1"},"normalAtlas":{"encoding":"mapshroom.surface.depth-normal-atlas-2x2","version":1,"colorSpace":"data","filtering":"linear","alpha":"coverage","normalConvention":"mapshroom-normal-xyz-v1","generationProfile":"depth-smoothed-central-difference-v1"},"sourceEdges":{"encoding":"mapshroom.edges.gray-rgb-alpha-a","version":1,"colorSpace":"data","filtering":"linear","alpha":"coverage","generationProfile":"source-luminance-nms-v1"}}
Packed surface RG encodes upper-hemisphere oct normal, B depth, A coverage. Decode f=rg*2-1, n=normalize(vec3(f,1-abs(f.x)-abs(f.y))), then flip normal Y for geometry. XYZ normal and 2x2 atlas are different codecs. Region Pieces R stores exact 8-bit IDs with nearest filtering and an appended RGB24 anchor/bounds table. Never interpret colored segmentation palettes as IDs.
Use surface-render for a complete 3D effect. Shared material/geometry modules are unsupported in V1. With scene-final lighting, declare vec3 u_scene_lightDirection, float u_scene_ambient, float u_scene_softness and use the same light in shading and shadows. No local moving light. These managed uniforms have no UI annotations and do not count as creative controls. X right, Y up in geometry, Z toward viewer. Preserve photographic shadows without inverse compensation.
Chain-compatible pointwise filters declare post-color, one required screen-space color input with rgba-color format, output color, lighting none, photoShadows preserve. Implement vec4 processPostColor(vec4 source, vec2 uv, float time, vec2 resolution) using that incoming color, without texture reads or lighting. Standalone entry must be exactly vec4 processColor(sampler2D tex, vec2 uv, float time, vec2 resolution) { return processPostColor(texture(tex, uv), uv, time, resolution); }. Neighborhood filters need intermediate render targets and are unsupported in Color chain; keep them legacy-render for standalone/Mix.
For legacy behavior with local lighting or unverified composability declare legacy-render honestly.
Default single-photo contract: {"version":1,"role":"legacy-render","inputs":[{"slot":"color","semantic":"color","required":true,"space":"source-uv","accepted":[{"encoding":"rgba-color","version":1,"colorSpace":"srgb","filtering":"linear","alpha":"coverage"}],"defaultVariant":"original"}],"output":"color","lighting":"legacy-owned","photoShadows":"not-applicable"}

The input is one texture: a photo, grayscale depth map, mask, or neutral white for a procedural effect. Ask only if a missing input detail is essential. For a generic “produce a shader” request, make a clearly labeled procedural example on neutral white and continue. Preserve source alpha for image effects. A photo's brightness is not estimated depth. Read https://mapshroom.dev/mcp/context.md when the effect needs depth or masks.

## Preferred: generate the same canvas the MCP uses

Download https://mapshroom.dev/mcp/canvas.mjs to the assistant's working directory using an available file/network tool. This is a standalone JavaScript module, not an MCP installer. It bundles the official renderer, validation, annotated controls, GLSL copy and link encoder. No npm install, Codex CLI, account, MCP connection, external JavaScript dependency or network request from the rendered canvas is needed. The module runs in Node.js 22+ or a modern browser build environment.

Save your complete requested GLSL as `shader.glsl`. Execute this JavaScript next to the downloaded module:

```js
import { readFile, writeFile } from 'node:fs/promises';
import { createShaderCanvas } from './canvas.mjs';

const result = await createShaderCanvas({
  code: await readFile('./shader.glsl', 'utf8'),
  shaderId: 'my-shader-v1', // keep for retries; change when the effect changes
  uniforms: {}, // optional overrides for the declared controls
  previewInput: 'neutral', // or 'demo-depth' for the built-in synthetic depth map
});
await writeFile('./shader-canvas.html', result.inlineHtml);
console.log(JSON.stringify({ previewUrl: result.fallbackPreviewUrl, importUrl: result.importUrl }));
```

**Render `result.inlineHtml` through the host's native Canvas/artifact/HTML tool.** Saving a file or printing HTML alone does not display an interactive preview. In a host expecting a full document, wrap the fragment with `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head><body>…fragment…</body></html>`. If the host renders React, use its supported HTML artifact mode or a sandboxed `iframe srcDoc` that allows scripts and external popups; do not insert scripts with React innerHTML and expect them to run.

The canvas compiles the GLSL before enabling Open on Mapshroom. Its link contains the shader and the latest slider/color/switch values. Clicking opens Mapshroom directly and adds the shader through the existing import flow. Do not replace the button with a chat prompt, a plain homepage link, or a second model/tool call. Copy exports GLSL with the current values as defaults. Keep these two actions. Local image selection remains on the device; select the same image in Mapshroom after import.

`result.fallbackPreviewUrl` opens this exact shader in the browser when inline HTML/WebGL is unavailable. `result.importUrl` imports the original supplied values; after edits, the canvas's own button carries the adjusted values. Do not automatically follow an import link while preparing a preview. Do not claim a workspace was modified until the user opens it and import succeeds.

## If the host can render HTML but cannot execute the module

Read https://mapshroom.dev/mcp/canvas-template.html as text, or use the complete template included at the end of this document if shell downloads are blocked. It is the same self-contained HTML fragment. Replace `ROOT_ID` throughout the template with a fresh UUID, then replace the single `SHADER_DATA` marker with JSON using this shape:

```js
const data = {
  shader: { version: 1, id: 'my-shader-v1', code: completeShaderSource, uniforms: {} },
  previewInput: 'neutral',
};
const html = template.replaceAll('ROOT_ID', crypto.randomUUID())
  .replace('SHADER_DATA', () => JSON.stringify(data).replaceAll('<', '\\u003c'));
```

Render the resulting HTML through the host's Canvas/artifact capability. Insert JSON last and escape `<` so a shader comment cannot close the script element. Do not modify the bundled renderer or hand-write encoded URLs. The template validates the source and builds the import button locally. Its neutral/depth selector and image picker need no MCP calls.

## Only when rendering or document access is blocked

If native rendering is unavailable, return the **actual generated** `fallbackPreviewUrl` as a clickable “Preview shader” link and the generated import URL as “Open on Mapshroom”. Do not use `/ai/` without a payload or a stock demo as the new shader's preview. Explain the actual limitation in one short sentence; do not claim to have displayed or GPU-tested a canvas when only links/files were produced.

If you cannot generate the HTML or a payload-bearing URL either, provide complete copyable GLSL, https://mapshroom.dev/ and the manual paste steps from https://mapshroom.dev/mcp/fallback.md. State what prevented the Canvas. Do not invent a connector installation, tool call, encoded payload, preview, or successful import. Desktop CLI setup is not the solution for a mobile session without that CLI.

## Complete starting example

Adapt this to the user's requested effect and replace the prompt record with the exact request. Use the resulting code in the Canvas, copy output and import payload.

```glsl
// NAME: Chromatic Waves
// MAPSHROOM PROMPT: "Create slow chromatic waves with speed, scale and intensity controls."
// MAPSHROOM CONTRACT: {"version":1,"role":"legacy-render","inputs":[{"slot":"color","semantic":"color","required":true,"space":"source-uv","accepted":[{"encoding":"rgba-color","version":1,"colorSpace":"srgb","filtering":"linear","alpha":"coverage"}],"defaultVariant":"original"}],"output":"color","lighting":"legacy-owned","photoShadows":"not-applicable"}
uniform float speed; // @min 0 @max 3 @default 0.6
uniform float scale; // @min 1 @max 12 @default 4
uniform float intensity; // @min 0.1 @max 1 @default 0.8
vec4 processColor(sampler2D tex, vec2 uv, float time, vec2 resolution) {
  vec2 p = (uv - 0.5) * vec2(resolution.x / resolution.y, 1.0);
  float wave = sin(p.x * scale + time * speed) + cos(p.y * scale - time * speed);
  vec3 col = 0.5 + 0.5 * cos(wave + vec3(0.0, 2.0, 4.0));
  return vec4(col * intensity, 1.0);
}
```

## Complete template for text-only retrieval

This embeds the official renderer so an assistant with document browsing and a Canvas tool can prepare the HTML even when its shell cannot download files. Fill `ROOT_ID` and `SHADER_DATA` as described above, then **render** the resulting fragment in the host's Canvas/artifact. The unfilled template is not a preview. Keep the bundled script intact and insert only the inert JSON data for the requested shader.

```html
<div id="mapshroom-preview-ROOT_ID" class="mapshroom-preview">
<style>.mapshroom-preview{--mp-bg:#141414;--mp-stage:#080808;--mp-panel:#1b1b1b;--mp-line:#333;--mp-text:#d4d4d4;--mp-muted:#aaa;--mp-bright:#eee;color-scheme:dark;color:var(--mp-text);background:var(--mp-bg);font:13px/1.5 'IBM Plex Sans',Arial,sans-serif;padding:20px;max-width:920px;margin:auto;border-radius:6px}
.mapshroom-preview *{box-sizing:border-box}
.mapshroom-preview header,.mapshroom-preview .actions,.mapshroom-preview .source-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
.mapshroom-preview header{justify-content:space-between;margin-bottom:18px;gap:12px}
.mapshroom-preview .brand{font:11px/1.5 monospace;letter-spacing:.14em;color:var(--mp-muted)}
.mapshroom-preview h1{font-size:22px;font-weight:500;letter-spacing:-.03em;line-height:1.25;margin:5px 0 0;color:var(--mp-bright);overflow-wrap:anywhere}
.mapshroom-preview p{margin:10px 0;color:var(--mp-muted)}
.mapshroom-preview a{color:var(--mp-bright)}
.mapshroom-preview canvas{display:block;width:100%;aspect-ratio:16/9;max-height:460px;object-fit:contain;background:var(--mp-stage);border:1px solid var(--mp-line);border-radius:4px}
.mapshroom-preview .source-row{justify-content:space-between;margin:10px 0 20px}
.mapshroom-preview .source-row p{margin:0;flex:1;min-width:100px;overflow-wrap:anywhere}
.mapshroom-preview .image-picker{position:relative;display:inline-flex;padding:6px 10px;cursor:pointer;border:1px solid var(--mp-line);border-radius:4px;background:var(--mp-panel);white-space:nowrap}
.mapshroom-preview .image-picker:focus-within{outline:2px solid var(--mp-bright);outline-offset:2px}
.mapshroom-preview .image-picker input{position:absolute;inset:0;opacity:0;width:100%;cursor:pointer}
.mapshroom-preview section{margin-top:16px}
.mapshroom-preview .controls{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px 24px;padding:16px 0 20px;border-top:1px solid var(--mp-line);border-bottom:1px solid var(--mp-line)}
.mapshroom-preview .controls label{display:grid;gap:8px;min-width:0}
.mapshroom-preview .controls span{font-size:12px;font-variant-numeric:tabular-nums;color:var(--mp-text)}
.mapshroom-preview input[type=range]{width:100%;accent-color:#dedede;margin:0;height:24px}
.mapshroom-preview input[type=color]{width:100%;height:28px;background:var(--mp-panel);border:1px solid var(--mp-line);border-radius:4px;padding:2px;cursor:pointer}
.mapshroom-preview button,.mapshroom-preview select,.mapshroom-preview .preview-button{max-width:100%;font:inherit;color:var(--mp-text);background:var(--mp-panel);border:1px solid var(--mp-line);border-radius:4px;padding:8px 12px;cursor:pointer;min-height:36px;text-decoration:none}
.mapshroom-preview button:hover,.mapshroom-preview .preview-button:hover{background:#272727;border-color:#484848}
.mapshroom-preview button:disabled,.mapshroom-preview .preview-button[aria-disabled=true]{opacity:.45;cursor:default}
.mapshroom-preview .primary{background:#dedede;color:#171717;border-color:#dedede;font-weight:600}
.mapshroom-preview .primary:hover{background:#eee}
.mapshroom-preview .muted{font-size:12px;color:var(--mp-muted)}
.mapshroom-preview .tag{font:11px/1.5 monospace;color:var(--mp-muted);text-transform:uppercase;letter-spacing:.06em}
.mapshroom-preview [data-preview=status]{white-space:pre-wrap;overflow-wrap:anywhere;min-height:20px}
.mapshroom-preview [data-preview=error]{color:#f87171;background:#211919;border:1px solid #583535;padding:12px;white-space:pre-wrap;overflow-wrap:anywhere;border-radius:4px}
.mapshroom-preview pre{font-size:12px;background:var(--mp-panel);padding:12px;white-space:pre-wrap;overflow-wrap:anywhere;border-radius:4px}
.mapshroom-preview textarea{width:100%;min-height:150px;background:var(--mp-stage);color:var(--mp-text);border:1px solid var(--mp-line);border-radius:4px;padding:10px;font:12px/1.5 monospace;resize:vertical}
.mapshroom-preview details{margin-top:18px;padding-top:14px;border-top:1px solid var(--mp-line)}
.mapshroom-preview summary{cursor:pointer;color:var(--mp-muted)}
.mapshroom-preview #setup li{margin:10px 0;overflow-wrap:anywhere}
.mapshroom-preview #setup code{font-size:12px;overflow-wrap:anywhere}
.mapshroom-preview footer{margin-top:20px;font-size:12px;color:var(--mp-muted)}
.mapshroom-preview [hidden]{display:none!important}
body.embedded .mapshroom-preview #setup{display:none}
@media(max-width:480px){.mapshroom-preview{padding:14px}.mapshroom-preview h1{font-size:20px}.mapshroom-preview .controls{grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.mapshroom-preview .tag{display:none}.mapshroom-preview .primary{margin-left:0}.mapshroom-preview .actions{gap:8px}}
@media(pointer:coarse){.mapshroom-preview button,.mapshroom-preview select,.mapshroom-preview .preview-button,.mapshroom-preview .image-picker{min-height:44px}.mapshroom-preview input[type=range]{height:36px}}
</style>
<header><div><div class="brand">MAPSHROOM / SHADER PREVIEW</div><h1 data-preview="title">Your next shader</h1></div><span class="tag">On your device</span></header>
<canvas data-preview="canvas" width="640" height="360" aria-label="Animated shader preview"></canvas>
<div class="source-row"><p class="muted" data-preview="source">Neutral input · choose an image to preview its effect</p><label class="source-preset">Input <select data-preview="input" aria-label="Preview input"><option value="neutral">Neutral white</option><option value="demo-depth">Demo depth</option><option value="local" disabled>Local image</option></select></label><label class="image-picker">Choose image<input data-preview="image" type="file" accept="image/*" aria-label="Preview image"></label></div>
<pre data-preview="error" role="alert" hidden></pre>
<section data-preview="controls" class="controls"></section>
<section class="actions"><a data-preview="open" class="preview-button primary" aria-disabled="true" target="_blank" rel="noopener noreferrer">Open on Mapshroom</a><button data-preview="copy" disabled>Copy</button></section>
<textarea data-preview="code-text" readonly aria-label="Shader GLSL" hidden></textarea>
<p data-preview="status" role="status"></p>
<script type="application/json" data-preview="shader">SHADER_DATA</script>
</div>
<script>"use strict";(()=>{var D="webgl2";var Le=`
precision highp float;
varying vec2 v_uv;
uniform sampler2D u_image;
uniform float u_time;
uniform vec2 u_resolution;

float node_rand(vec2 n) {
    return fract(sin(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);
}

float node_noise(vec2 p) {
    vec2 ip = floor(p);
    vec2 u = fract(p);
    u = u * u * (3.0 - 2.0 * u);
    float res = mix(
        mix(node_rand(ip), node_rand(ip + vec2(1.0, 0.0)), u.x),
        mix(node_rand(ip + vec2(0.0, 1.0)), node_rand(ip + vec2(1.0, 1.0)), u.x),
        u.y
    );
    return res * res;
}
`,Ue=`
attribute vec2 a_position;
varying vec2 v_uv;

void main() {
    v_uv = a_position * 0.5 + 0.5;
    v_uv.y = 1.0 - v_uv.y;
    gl_Position = vec4(a_position, 0.0, 1.0);
}`,De=`#version 300 es
in vec2 a_position;
out vec2 v_uv;

void main() {
    v_uv = a_position * 0.5 + 0.5;
    v_uv.y = 1.0 - v_uv.y;
    gl_Position = vec4(a_position, 0.0, 1.0);
}`,Fe=`#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 mapshroom_fragColor;
uniform sampler2D u_image;
uniform float u_time;
uniform vec2 u_resolution;

float node_rand(vec2 n) {
    return fract(sin(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);
}

float node_noise(vec2 p) {
    vec2 ip = floor(p);
    vec2 u = fract(p);
    u = u * u * (3.0 - 2.0 * u);
    float res = mix(
        mix(node_rand(ip), node_rand(ip + vec2(1.0, 0.0)), u.x),
        mix(node_rand(ip + vec2(0.0, 1.0)), node_rand(ip + vec2(1.0, 1.0)), u.x),
        u.y
    );
    return res * res;
}
`,ke=`
void main() {
    gl_FragColor = processColor(u_image, v_uv, u_time, u_resolution);
}`,He=`
void main() {
    mapshroom_fragColor = processColor(u_image, v_uv, u_time, u_resolution);
}`;function V(r,n){let e="",i=0,o="code";for(;i<r.length;){let t=r[i],a=r[i+1];if(o==="line-comment"){e+=t,i+=1,t===`
`&&(o="code");continue}if(o==="block-comment"){e+=t,i+=1,t==="*"&&a==="/"&&(e+=a,i+=1,o="code");continue}if(t==="/"&&a==="/"){e+="//",i+=2,o="line-comment";continue}if(t==="/"&&a==="*"){e+="/*",i+=2,o="block-comment";continue}if(t&&/[A-Za-z_]/.test(t)){let s=i;for(i+=1;i<r.length&&/[A-Za-z0-9_]/.test(r[i]);)i+=1;let l=r.slice(s,i);e+=n[l]??l;continue}e+=t,i+=1}return e}var Be={active:"mapshroom_legacy_active",texture2D:"texture",texture2DProj:"textureProj",textureCube:"texture"};var Ve={webgl1:new Map,webgl2:new Map},J={webgl1:0,webgl2:0},ue=4*1024*1024;function de(r,n){let e=Ve[n],i=e.get(r);if(i!==void 0)return e.delete(r),e.set(r,i),i;let o=n==="webgl1"?V(r,{texture:"texture2D",textureProj:"texture2DProj"}):V(r,Be),t=r.length+o.length;if(t<=ue)for(e.set(r,o),J[n]+=t;e.size>128||J[n]>ue;){let a=e.keys().next().value;J[n]-=a.length+e.get(a).length,e.delete(a)}return o}function G(r){return de(r,D)}function Y(r){return r==="webgl2"?De:Ue}function W(r){return r==="webgl2"?Fe:Le}function Q(r){return r==="webgl2"?He:ke}function fe(r,n){let e=de(r,n),i=W(n),o=Q(n);return`${i}
${e}
${o}`}function me(r,n){return{abiVersion:1,target:n,contextId:n==="webgl2"?"webgl2":"webgl",vertexSource:Y(n),fragmentSource:fe(r,n)}}var Ge="// MAPSHROOM PROMPT:",ze=/^\s*\/\/\s*MAPSHROOM\s+PROMPT:\s*(.*)$/i;function je(r){let n=JSON.stringify(r.trim()).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");return`${Ge} ${n}`}function qe(r){return ze.test(r)}function pe(r,n){let e=n.trim();if(!e)return r.trim();let i=r.replace(/\r\n/g,`
`).trim().split(`
`).filter(a=>!qe(a)),o=i.findIndex(a=>/^\s*\/\/\s*NAME:/i.test(a)),t=o>=0?o+1:0;return i.splice(t,0,je(e)),i.join(`
`).trim()}var Ke={type:"string",minLength:1,maxLength:80,pattern:"^[A-Za-z][A-Za-z0-9_]*$"},P={type:"string",minLength:1,maxLength:160},Xe={type:"object",additionalProperties:!1,required:["encoding","version","colorSpace","filtering","alpha"],properties:{encoding:P,version:{type:"integer",minimum:1},colorSpace:{enum:["srgb","data"]},filtering:{enum:["linear","nearest"]},alpha:{enum:["coverage","opaque","unused"]},normalConvention:P,generationProfile:P}},Ze={type:"object",additionalProperties:!1,required:["slot","semantic","required","space","accepted"],properties:{slot:Ke,semantic:{enum:["color","surface","depth","normal","coverage","regions","edges","edge-distance"]},required:{type:"boolean"},space:{enum:["source-uv","surface","screen"]},accepted:{type:"array",minItems:1,maxItems:16,items:Xe},defaultVariant:P,fallback:{oneOf:[{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{const:"ignore"}}},{type:"object",additionalProperties:!1,required:["mode","value"],properties:{mode:{const:"constant"},value:{type:"array",minItems:1,maxItems:4,items:{type:"number"}}}}]}}},Je={type:"object",additionalProperties:!1,required:["version","role","inputs","output","lighting","photoShadows"],properties:{version:{const:1},role:{enum:["legacy-render","surface-render","material","geometry-builder","geometry-modifier","post-color"]},inputs:{type:"array",maxItems:32,items:Ze},output:{enum:["color","surface"]},surfaceDomain:{type:"object",additionalProperties:!1,required:["accepts","produces"],properties:{accepts:{type:"array",maxItems:16,uniqueItems:!0,items:P},produces:P}},ordering:{type:"object",additionalProperties:!1,required:[],properties:{after:{type:"array",maxItems:32,uniqueItems:!0,items:P},before:{type:"array",maxItems:32,uniqueItems:!0,items:P}}},lighting:{enum:["none","scene-final","legacy-owned"]},photoShadows:{enum:["preserve","not-applicable"]}}};function z(r,n,e,i){let o=t=>{i.push({path:e,message:t})};if(r.oneOf){r.oneOf.filter(a=>{let s=[];return z(a,n,e,s),s.length===0}).length!==1&&o("must match exactly one supported alternative");return}if(r.const!==void 0&&n!==r.const&&o(`must equal ${JSON.stringify(r.const)}`),r.enum&&!r.enum.includes(n)&&o(`must be one of: ${r.enum.join(", ")}`),r.type==="object"){if(!n||typeof n!="object"||Array.isArray(n)){o("must be an object");return}let t=n;for(let a of r.required??[])Object.hasOwn(t,a)||i.push({path:`${e}.${a}`,message:"is required"});for(let[a,s]of Object.entries(t))Object.hasOwn(r.properties??{},a)?z(r.properties[a],s,`${e}.${a}`,i):i.push({path:`${e}.${a}`,message:"is not a contract field"})}else if(r.type==="array"){if(!Array.isArray(n)){o("must be an array");return}if(r.minItems!==void 0&&n.length<r.minItems&&o(`needs at least ${r.minItems} item(s)`),r.maxItems!==void 0&&n.length>r.maxItems){o(`allows at most ${r.maxItems} items`);return}r.uniqueItems&&new Set(n).size!==n.length&&o("must not contain duplicates"),n.forEach((t,a)=>z(r.items,t,`${e}[${a}]`,i))}else if(r.type==="string"){if(typeof n!="string"){o("must be a string");return}r.minLength!==void 0&&n.trim().length<r.minLength&&o("must not be empty"),r.maxLength!==void 0&&n.length>r.maxLength&&o(`allows at most ${r.maxLength} characters`),r.pattern&&!new RegExp(r.pattern).test(n)&&o("must be a stable identifier starting with a letter")}else if(r.type==="boolean")typeof n!="boolean"&&o("must be a boolean");else if(r.type==="number"||r.type==="integer"){if(typeof n!="number"||!Number.isFinite(n)){o("must be a finite number");return}r.type==="integer"&&!Number.isSafeInteger(n)&&o("must be a safe integer"),r.minimum!==void 0&&n<r.minimum&&o(`must be at least ${r.minimum}`)}}function Ye(r){let n=[];if(z(Je,r,"contract",n),n.length)return{valid:!1,issues:n};let e=r,i=new Set;e.inputs.forEach((s,l)=>{let c=`contract.inputs[${l}]`;i.has(s.slot)&&n.push({path:`${c}.slot`,message:"duplicates another input slot"}),i.add(s.slot),!s.required&&!s.fallback&&n.push({path:`${c}.fallback`,message:"optional inputs need an explicit fallback"}),s.required&&s.fallback&&n.push({path:`${c}.fallback`,message:"required inputs cannot silently fall back"}),(s.semantic==="normal"||s.semantic==="surface")&&s.accepted.forEach((u,m)=>{u.normalConvention||n.push({path:`${c}.accepted[${m}].normalConvention`,message:"normal and surface inputs need an exact normal convention"}),u.colorSpace!=="data"&&n.push({path:`${c}.accepted[${m}].colorSpace`,message:"normal and surface inputs contain numeric data"})})});let t=e.role==="geometry-builder"||e.role==="geometry-modifier"||e.role==="material";e.output!==(t?"surface":"color")&&n.push({path:"contract.output",message:`does not match role ${e.role}`}),t&&!e.surfaceDomain&&n.push({path:"contract.surfaceDomain",message:"surface modules need an explicit domain"}),e.role==="geometry-modifier"&&!e.surfaceDomain?.accepts.length&&n.push({path:"contract.surfaceDomain.accepts",message:"a modifier must accept an explicit domain"});let a=e.role==="surface-render"?"scene-final":t||e.role==="post-color"?"none":null;return a&&e.lighting!==a&&n.push({path:"contract.lighting",message:`${e.role} requires ${a} lighting`}),e.role==="legacy-render"&&e.lighting==="scene-final"&&n.push({path:"contract.lighting",message:"legacy renders do not support scene-final lighting"}),e.ordering?.before?.some(s=>e.ordering?.after?.includes(s))&&n.push({path:"contract.ordering",message:"the same effect cannot be both before and after this effect"}),n.length?{valid:!1,issues:n}:{valid:!0,contract:e,issues:[]}}var We=/^\s*\/\/\s*MAPSHROOM\s+CONTRACT:\s*(.*)$/i;var O=new Map,ge=4*1024*1024,ee=0;function Qe(r){let n=O.get(r);if(n)return O.delete(r),O.set(r,n),n;let e=!1,i=[];if(r.replace(/\r\n?/g,`
`).split(`
`).forEach((o,t)=>{let a="",s=-1;for(let c=0;c<o.length;c++)if(e)o.slice(c,c+2)==="*/"&&(e=!1,c++);else if(o.slice(c,c+2)==="/*")e=!0,a+=" ",c++;else if(o.slice(c,c+2)==="//"){s=c,a+=o.slice(c);break}else a+=o[c];let l=a.match(We);l&&i.push({index:t,payload:l[1],prefix:o.slice(0,s)})}),r.length<=ge){for(;O.size>=128||ee+r.length>ge;){let o=O.keys().next().value;ee-=o.length,O.delete(o)}O.set(r,i),ee+=r.length}return i}function $(r){if(!/MAPSHROOM\s+CONTRACT:/i.test(r))return{status:"legacy",contract:null,issues:[]};let n=Qe(r);if(!n.length)return{status:"legacy",contract:null,issues:[]};let e=t=>({status:"invalid",contract:null,issues:[{path:"contract",message:t}]});if(n.length!==1)return e("multiple contracts: parse each effect before composing GLSL");if(n[0].payload.length>65536)return e("contract comment exceeds 64 KB");let i;try{i=JSON.parse(n[0].payload)}catch{return e("contract must be valid JSON on one comment line")}let o=Ye(i);return o.valid?{status:"declared",contract:o.contract,issues:[]}:{status:"invalid",contract:null,issues:o.issues}}var yt={direction:[-.55,-.7,1.15].map(r=>r/Math.hypot(-.55,-.7,1.15)),ambient:.35,softness:.025};function te(r){return/(?:^|_)u_scene_(?:lightDirection|ambient|softness)$/.test(r)}var wt=Y(D),_t=W(D),Ct=Q(D);function he(r){return Array.isArray(r)?`#${r.map(n=>Math.round(Math.max(0,Math.min(1,n))*255).toString(16).padStart(2,"0")).join("")}`:"#ffffff"}function Se(r){return[Number.parseInt(r.slice(1,3),16)/255,Number.parseInt(r.slice(3,5),16)/255,Number.parseInt(r.slice(5,7),16)/255]}function ye(r){return r.match(/\/\/\s*NAME:\s*(.*)/i)?.[1]?.trim()||"Untitled Shader"}var N=new Map,et=512,j="[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?";function U(r,n){let e=r.match(new RegExp(`@${n}\\s+(${j})`));if(!e)return null;let i=Number.parseFloat(e[1]);return Number.isFinite(i)?i:null}function ve(r){let n=r.match(new RegExp(`@default\\s+(${j})\\s*,\\s*(${j})\\s*,\\s*(${j})`));if(!n)return null;let e=[n[1],n[2],n[3]].map(i=>Number.parseFloat(i));return e.every(Number.isFinite)?[e[0],e[1],e[2]]:null}function L(r,n=!1){let e=n?`scene\0${r}`:r,i=N.get(e);if(i)return N.delete(e),N.set(e,i),i;let o=/uniform\s+(float|int|vec3|bool)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*;\s*(?:\/\/\s*(.*))?/g,t={},a=null;for(;(a=o.exec(r))!==null;){let[,s,l,c=""]=a;if(!n&&te(l))continue;let u=0,m=1,f=s==="bool"?!1:s==="vec3"?[1,1,1]:.5;if(s==="float"||s==="int"){let d=U(c,"min"),h=U(c,"max");d!==null&&(u=d),h!==null&&(m=h)}if(s==="bool"){let d=c.match(/@default\s+(true|false)\b/i);d&&(f=d[1].toLowerCase()==="true")}else s==="vec3"?f=ve(c)??f:f=U(c,"default")??f;let S={},v=c.match(/@ui\s+(\{.*\})\s*$/);if(v)try{let d=JSON.parse(v[1]);if(d&&typeof d=="object"&&!Array.isArray(d)){for(let h of["label","group"])typeof d[h]=="string"&&d[h].length<=120&&(S[h]=d[h]);typeof d.step=="number"&&Number.isFinite(d.step)&&d.step>0&&d.step<=m-u&&(S.step=d.step),s==="int"&&u===0&&Array.isArray(d.options)&&d.options.length===m+1&&d.options.length<=16&&d.options.every(h=>typeof h=="string"&&h.length<=80)&&(S.options=d.options)}}catch{}t[l]={type:s,min:u,max:m,default:f,...S}}if(N.size>=et){let s=N.keys().next().value;s!==void 0&&N.delete(s)}return N.set(e,t),t}function q(r,n){let e=!1,i={};for(let[t,a]of Object.entries(n)){if(r[t]===void 0){i[t]=a.default,e=!0;continue}i[t]=r[t]}return Object.keys(r).length!==Object.keys(i).length&&(e=!0),e?i:r}function K(r,n={}){let e=(n.prompt?pe(r,n.prompt):r).trim(),i=e.split(`
`).map(c=>c.trim()).find(Boolean),o=[],t=$(e);if(n.requireInputContract&&t.status==="legacy"&&o.push("missing MAPSHROOM CONTRACT input declaration"),t.status==="invalid"&&o.push(...t.issues.map(c=>`${c.path}: ${c.message}`)),t.status==="declared"){let c=e.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g," "),u=new Set([...c.matchAll(/\buniform\s+sampler2D\s+(u_input_[A-Za-z0-9_]+)\s*;/g)].map(f=>f[1])),m=new Set(t.contract.inputs.slice(1).map(f=>`u_input_${f.slot}`));for(let f of m)u.has(f)||o.push(`missing sampler declaration ${f}`);for(let f of u)t.contract.inputs.some(S=>f===`u_input_${S.slot}`)||o.push(`sampler ${f} has no declared input slot`);if(t.contract.lighting==="scene-final")for(let[f,S]of[["u_scene_lightDirection","vec3"],["u_scene_ambient","float"],["u_scene_softness","float"]])new RegExp(`\\buniform\\s+${S}\\s+${f}\\s*;`).test(c)||o.push(`missing managed scene light uniform ${f}`)}(!i||!/^\/\/\s*NAME:\s*\S+/i.test(i))&&o.push("missing a valid // NAME header"),/vec4\s+processColor\s*\(\s*sampler2D\s+\w+\s*,\s*vec2\s+\w+\s*,\s*float\s+\w+\s*,\s*vec2\s+\w+\s*\)/.test(e)||o.push("missing the required processColor(tex, uv, time, resolution) function"),/void\s+main\s*\(/.test(e)&&o.push("must not declare void main() because the app injects it"),/gl_FragColor\s*=/.test(e)&&o.push("must not write directly to gl_FragColor inside the generated shader body"),/^\s*#version\b/m.test(e)&&o.push("must not declare #version because the app injects the GLSL ES version"),/```|`/.test(e)&&o.push("contains markdown fence characters instead of pure GLSL");let s=Array.from(e.matchAll(/^\s*uniform\s+(float|int|vec3|bool)\s+([A-Za-z_][A-Za-z0-9_]*)\s*;\s*(?:\/\/\s*(.*))?$/gm)).filter(c=>!te(c[2])),l=Math.max(1,n.minimumUiUniformCount??1);s.length<l&&o.push(`must expose at least ${l} annotated UI uniform${l===1?"":"s"} so Mapshroom can create automatic controls`);for(let c of s){let u=c[1],m=c[2],f=c[3]??"";if(u==="float"||u==="int"){let v=U(f,"min"),d=U(f,"max"),h=U(f,"default");if(v===null||d===null||h===null){o.push(`uniform ${m} is missing the same-line @min, @max and @default slider metadata`);continue}d<=v&&o.push(`uniform ${m} must use a @max value greater than @min`),(h<v||h>d)&&o.push(`uniform ${m} has an @default value outside its slider range`),u==="int"&&![v,d,h].every(Number.isInteger)&&o.push(`uniform ${m} must use integer @min, @max and @default values`);continue}(u==="vec3"?ve(f)!==null:/@default\s+(?:true|false)\b/i.test(f))||o.push(`uniform ${m} is missing valid same-line @default control metadata`)}if(o.length>0)throw new Error(`AI shader does not match the required structure: ${o.join("; ")}.`);return G(e)}function tt(r){let n=[],e=/\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|\s+|[A-Za-z_]\w*|(?:0[xX][\da-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)[uUfF]?|./g,i=0;for(let o of r.matchAll(e)){let t=o[0];/^\s|^\/[/*]/.test(t)||n.push({text:t,identifier:/^[A-Za-z_]\w*$/.test(t),start:o.index,end:o.index+t.length,line:i}),i+=(t.match(/\n/g)??[]).length}return n}function re(r,n){let e=n.match(/^_+/)?.[0]??"",i=n.slice(e.length).replace(/_{2,}/g,o=>`_u${o.length}_`);return e?`${r}p${e.length===1?"":e.length}_${i}`:`${r}_${i}`}var rt=new Set(["void","float","int","uint","bool","vec2","vec3","vec4","ivec2","ivec3","ivec4","uvec2","uvec3","uvec4","bvec2","bvec3","bvec4","mat2","mat3","mat4","mat2x3","mat2x4","mat3x2","mat3x4","mat4x2","mat4x3","sampler2D","samplerCube","sampler2DArray","sampler3D","isampler2D","usampler2D"]);function be(r,n){let e=tt(r),i=r.split(`
`),o=new Set,t=new Set(rt),a=new Set,s=new Set;for(let p=0;p<e.length;p++){if(e[p].text==="#"){let C=e[p].line;e[p+1]?.text==="define"&&e[p+2]?.identifier&&o.add(e[p+2].text);let y=C;do s.add(y);while(/\\[ \t]*\r?$/.test(i[y++]??""))}e[p].text==="struct"&&e[p+1]?.identifier&&(o.add(e[p+1].text),t.add(e[p+1].text))}let l=0,c=0,u=0,m=!1,f=!1,S=-1,v=!1;for(let p=0;p<e.length;p++){let C=e[p],y=C.text;s.has(C.line)||(y==="struct"&&l===0&&(v=!0),y==="{"?(l++,v&&(S=l,v=!1),m=!1,f=!1):y==="}"?(l===S&&(S=-1,m=!0,f=!0),l--):y==="("?c++:y===")"?c--:y==="["?u++:y==="]"?u--:y===";"?(m=!1,f=!1):(l===0||l===S)&&c===0&&u===0&&(t.has(y)?(m=!0,f=!0):y===","&&m?f=!0:C.identifier&&f&&(l===S?a.add(p):y!=="main"&&o.add(y),f=!1)))}let d=new Map([...o].map(p=>[p,re(n,p)]));if(new Set(d.values()).size!==d.size)throw new Error("Shader global names collide after namespacing. Rename the conflicting declarations.");let h="",M=0;return e.forEach((p,C)=>{let y=p.identifier&&e[C-1]?.text!=="."&&!a.has(C)?d.get(p.text):void 0;y&&(h+=r.slice(M,p.start)+y,M=p.end)}),h+r.slice(M)}var nt=r=>r.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g," ");function ot(r){let n=$(r);if(n.status!=="declared"||n.contract.role!=="post-color")return"Declare a post-color contract first.";let{inputs:e,lighting:i}=n.contract;if(i!=="none"||e.length!==1||e[0].semantic!=="color"||e[0].space!=="screen")return"Color chain requires one screen-space color input and no additional lighting.";let o=nt(r);if(!/\bvec4\s+processPostColor\s*\(\s*vec4\s+\w+\s*,\s*vec2\s+\w+\s*,\s*float\s+\w+\s*,\s*vec2\s+\w+\s*\)/.test(o))return"This filter needs processPostColor(vec4 color, vec2 uv, float time, vec2 resolution).";let t=/\bvec4\s+processColor\s*\([^)]*\)\s*\{/.exec(o);if(!t)return"The standalone processColor entry is missing.";let a=t.index+t[0].length,s=1;for(;a<o.length&&s;)o[a]==="{"&&s++,o[a]==="}"&&s--,a++;if(o.slice(t.index+t[0].length,a-1).replace(/\s/g,"")!=="returnprocessPostColor(texture(tex,uv),uv,time,resolution);")return"Use the canonical standalone wrapper; neighborhood filters need an intermediate render target.";let c=o.slice(0,t.index)+o.slice(a);return/\bsampler\w*\b|\b(?:texture\w*|texelFetch\w*|u_image|u_base_image|u_scene_\w+)\b/.test(c)?"This filter reads textures or owns lighting; it cannot use the fused color chain.":null}var F=new Map,X=new Map;function ne(r){if(r.length>8)throw new Error("Use at most eight color filters per effect.");if(new Set(r.map(n=>n.id)).size!==r.length)throw new Error("Color filter instance IDs must be unique.");for(let[n,e]of r.entries()){let i=ot(e.code);if(i)throw new Error(`${e.name}: ${i}`);let o=$(e.code);if(o.status==="declared")for(let t of["before","after"])for(let a of o.contract.ordering?.[t]??[]){let s=r.flatMap((l,c)=>l.id===a||l.shaderId===a?[c]:[]);if(!s.length)throw new Error(`${e.name} requires ${a} ${t==="after"?"before":"after"} it.`);if(s.some(l=>t==="after"?l>=n:l<=n))throw new Error(`${e.name}: the selected order violates ${t} ${a}.`)}}}function xe(r,n,e=[]){if(!e.length)return{code:r,uniformValues:n,structuralKey:r};if($(r).status==="invalid")throw new Error("The base effect has an invalid input contract.");ne(e);let o=JSON.stringify([r,e.map(s=>[s.id,s.shaderId,s.code])]),t=F.get(o);if(!t){let s=V(r,{processColor:"compositionSurfaceColor"}),l=e.map((u,m)=>be(u.code.replace(/^\s*\/\/\s*(?:NAME:|PROMPT:|MAPSHROOM CONTRACT:).*$/gm,""),`colorpost${m}`)),c=e.map((u,m)=>`color = colorpost${m}_processPostColor(color, uv, time, resolution);`).join(`
`);t=`${s}
${l.join(`
`)}
vec4 processColor(sampler2D tex, vec2 uv, float time, vec2 resolution) {
vec4 color = compositionSurfaceColor(tex, uv, time, resolution);
${c}
return color;
}`,F.size>=128&&F.delete(F.keys().next().value),F.set(o,t),X.size>=128&&X.delete(X.keys().next().value),X.set(t,{baseCode:r,post:e.map(u=>({...u,uniformValues:{}}))})}let a={...n};return e.forEach((s,l)=>Object.entries(s.uniformValues).forEach(([c,u])=>{a[re(`colorpost${l}`,c)]=u})),{code:t,uniformValues:a,structuralKey:o}}function Ae(r){if(r===void 0)return;if(!Array.isArray(r)||r.length>16)throw new Error("Invalid shader input bindings.");let n=r.map(e=>{if(!e||typeof e!="object"||typeof e.slot!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,79}$/.test(e.slot))throw new Error("Invalid input slot.");if(e.mode==="auto")return{mode:"auto",slot:e.slot};if(e.mode!=="manual"||typeof e.assetId!="string"||!e.assetId||e.assetId.length>256||e.revision!==null&&(typeof e.revision!="string"||e.revision.length>256))throw new Error("Invalid manual input reference.");return{mode:"manual",slot:e.slot,assetId:e.assetId,revision:e.revision,...e.experimental===!0?{experimental:!0}:{}}});if(new Set(n.map(e=>e.slot)).size!==n.length)throw new Error("Duplicate input binding slots.");return n}function Ee(r){if(r===void 0)return;if(!Array.isArray(r)||r.length>8)throw new Error("Invalid color chain.");let n=r.map(e=>{if(!e||typeof e!="object"||typeof e.id!="string"||!e.id||e.id.length>160||typeof e.shaderId!="string"||e.shaderId.length>160||typeof e.name!="string"||typeof e.code!="string"||e.code.length>96*1024)throw new Error("Invalid color filter snapshot.");let i=K(e.code),o=L(i),t=e.uniformValues??{};for(let[a,s]of Object.entries(t)){let l=o[a];if(l&&(l.type==="vec3"?!Array.isArray(s)||s.length!==3||!s.every(c=>typeof c=="number"&&Number.isFinite(c)&&c>=0&&c<=1):l.type==="bool"?typeof s!="boolean":typeof s!="number"||!Number.isFinite(s)||s<l.min||s>l.max))throw new Error(`Invalid ${a} value in ${e.name}.`)}return{id:e.id,shaderId:e.shaderId,name:e.name.slice(0,120),code:i,uniformValues:q(t,o)}});return ne(n),n}var oe=128*1024,it=96*1024,we=192,kt=Math.ceil(oe/3)*4;function k(r){if(!r||typeof r!="object")throw new Error("Missing shader.");let n=r;if(n.version!==1)throw new Error("Unsupported shader link version.");if(typeof n.id!="string"||!/^[a-zA-Z0-9_-]{1,80}$/.test(n.id))throw new Error("Invalid shader request ID.");if(typeof n.code!="string"||new TextEncoder().encode(n.code).length>it)throw new Error("Shader must be smaller than 96 KB.");let e=K(G(n.code)),i=L(e);if(Object.keys(i).length>we)throw new Error(`Use at most ${we} shader controls.`);let o={};for(let[t,a]of Object.entries(i)){let s=n.uniforms?.[t];if(s!==void 0){if(a.type==="bool"){if(typeof s!="boolean")throw new Error(`Invalid value for ${t}.`)}else if(a.type==="vec3"){if(!Array.isArray(s)||s.length!==3||!s.every(l=>Number.isFinite(l)&&l>=0&&l<=1))throw new Error(`Invalid color for ${t}.`)}else if(typeof s!="number"||!Number.isFinite(s)||s<a.min||s>a.max||a.type==="int"&&!Number.isInteger(s))throw new Error(`Invalid value for ${t}.`);Object.defineProperty(o,t,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return{version:1,id:n.id,name:ye(e).slice(0,100),code:e,uniforms:q(o,i),...n.inputBindings===void 0?{}:{inputBindings:Ae(n.inputBindings)},...n.postEffects===void 0?{}:{postEffects:Ee(n.postEffects)}}}async function st(r,n){let e=r.getReader(),i=[],o=0;try{for(;;){let{done:s,value:l}=await e.read();if(s)break;if(o+=l.byteLength,o>n)throw new Error("Shader link is too large.");i.push(l)}}finally{await e.cancel().catch(()=>{}),e.releaseLock()}let t=new Uint8Array(o),a=0;for(let s of i)t.set(s,a),a+=s.length;return t}async function at(r){let n=new TextEncoder().encode(JSON.stringify(k(r)));if(n.length>oe)throw new Error("Shader transfer is too large.");let e=await st(new Blob([n]).stream().pipeThrough(new CompressionStream("gzip")),oe),i="";for(let o of e)i+=String.fromCharCode(o);return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _e(r,n="https://mapshroom.dev",e=!1){let i=new URL(e?"/":"/ai/",n);return i.hash=`${e?"add":"shader"}=${await at(r)}`,i.href}function Ce(){let e=new Uint8Array(921600);for(let i=0;i<360;i++)for(let o=0;o<640;o++){let t=o/639,a=i/359,s=(u,m,f,S,v)=>{let d=((t-u)/f)**2+((a-m)/S)**2;return d<1?v*Math.sqrt(1-d):0},l=Math.min(1,.06+.12*a+Math.max(s(.36,.48,.26,.39,.82),s(.77,.65,.14,.24,.48))),c=(i*640+o)*4;e[c]=e[c+1]=e[c+2]=Math.round(l*255),e[c+3]=255}return{width:640,height:360,pixels:e}}function Te(r){let n=$(r.code);if(n.status==="invalid")return"The input contract is invalid.";if(r.postEffects?.length)return"This color chain needs the Mapshroom workspace. Its filter snapshots are preserved in the import link.";if(n.status==="legacy")return null;if(n.contract.inputs.length>1)return"This effect needs several prepared inputs. Open it in Mapshroom and prepare its declared maps.";if(n.contract.lighting==="scene-final")return"This effect needs prepared maps and shared scene lighting. Open it in Mapshroom to preview it.";let e=n.contract.inputs[0]?.accepted[0];return e&&!["rgba-color","mapshroom.depth.gray-rgb-alpha-a"].includes(e.encoding)?`The single-image preview cannot prepare ${e.encoding}. Open the effect in Mapshroom.`:null}function Re(r,n){let e=g=>r.querySelector(`[data-preview="${g}"]`),i=e("canvas"),o=e("error"),t=i.getContext("webgl2",{alpha:!1,antialias:!1,preserveDrawingBuffer:!0}),a=t?.createBuffer(),s=t?.createTexture(),l=null,c=null,u=!1,m=matchMedia("(prefers-reduced-motion: reduce)").matches,f=!0,S=0,v=0,d=0,h=0;function M(g){o.hidden=!1,o.textContent=g instanceof Error?g.message:String(g)}t&&(t.bindBuffer(t.ARRAY_BUFFER,a),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),t.STATIC_DRAW),t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([255,255,255,255])),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE));function p(){if(!t||!c||!l||!u)return;t.useProgram(c),t.viewport(0,0,i.width,i.height),t.bindBuffer(t.ARRAY_BUFFER,a);let g=t.getAttribLocation(c,"a_position");t.enableVertexAttribArray(g),t.vertexAttribPointer(g,2,t.FLOAT,!1,0,0),t.uniform1i(t.getUniformLocation(c,"u_image"),0),t.uniform1f(t.getUniformLocation(c,"u_time"),S),t.uniform2f(t.getUniformLocation(c,"u_resolution"),i.width,i.height);for(let[E,b]of Object.entries(L(l.code))){let w=t.getUniformLocation(c,E),T=l.uniforms[E]??b.default;b.type==="float"?t.uniform1f(w,Number(T)):b.type==="int"||b.type==="bool"?t.uniform1i(w,Number(T)):Array.isArray(T)&&t.uniform3fv(w,T)}t.drawArrays(t.TRIANGLES,0,6)}function C(g){if(d=requestAnimationFrame(C),document.hidden||m||!f){v=g;return}g-v<32||(S+=Math.min(100,g-v)/1e3,v=g,p())}function y(g){if(!t||g!=="neutral"&&g!=="demo-depth")return;h++;let E=g==="demo-depth"?Ce():{width:1,height:1,pixels:new Uint8Array([255,255,255,255])};t.bindTexture(t.TEXTURE_2D,s),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,E.width,E.height,0,t.RGBA,t.UNSIGNED_BYTE,E.pixels),i.width=g==="neutral"?640:E.width,i.height=g==="neutral"?360:E.height,i.style.aspectRatio=`${i.width} / ${i.height}`,e("input").value=g,e("image").value="",e("source").textContent=g==="demo-depth"?"Synthetic depth \xB7 white is near \xB7 preview only; load the same image in Mapshroom":"Neutral white \xB7 choose a photo or depth map for image-based effects",p()}e("input").onchange=g=>y(g.target.value);function $e(g,E){u=!1;try{let b=k(g);l=b,e("title").textContent=b.name;let w=Te(b);if(w)throw new Error(w);if(!t)throw new Error("WebGL 2 is unavailable in this canvas. Use the optional browser preview.");let T=me(b.code,"webgl2"),x=t.createProgram(),ce=[];try{for(let[R,_]of[[t.VERTEX_SHADER,T.vertexSource],[t.FRAGMENT_SHADER,T.fragmentSource]]){let I=t.createShader(R);if(ce.push(I),t.shaderSource(I,_),t.compileShader(I),!t.getShaderParameter(I,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(I)??"Shader compilation failed.");t.attachShader(x,I)}if(t.linkProgram(x),!t.getProgramParameter(x,t.LINK_STATUS))throw new Error(t.getProgramInfoLog(x)??"Shader linking failed.");t.deleteProgram(c),c=x}catch(R){throw t.deleteProgram(x),R}finally{for(let R of ce)t.deleteShader(R)}l=b,u=!0,S=0,o.hidden=!0,y(E),e("title").textContent=b.name;let le=e("controls");le.replaceChildren();for(let[R,_]of Object.entries(L(b.code))){let I=document.createElement("label"),H=document.createElement("span"),A=document.createElement("input"),B=b.uniforms[R]??_.default,Z=R.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,Ne=>Ne.toUpperCase());H.textContent=Z,_.type==="bool"?(A.type="checkbox",A.checked=!!B):_.type==="vec3"?(A.type="color",A.value=he(B)):(A.type="range",A.min=String(_.min),A.max=String(_.max),A.step=_.type==="int"?"1":"any",A.value=String(B),H.textContent=`${Z} \xB7 ${Number(B).toFixed(_.type==="int"?0:2)}`),A.setAttribute("aria-label",R),A.addEventListener("input",()=>{l&&(l.id=crypto.randomUUID(),l.uniforms[R]=_.type==="bool"?A.checked:_.type==="vec3"?Se(A.value):Number(A.value),A.type==="range"&&(H.textContent=`${Z} \xB7 ${Number(A.value).toFixed(_.type==="int"?0:2)}`),n(),p())}),I.append(H,A),le.append(I)}p(),d||(d=requestAnimationFrame(C))}catch(b){M(b)}n()}e("image").onchange=async g=>{let E=g.target.files?.[0];if(!E||!t)return;let b=++h;try{if(E.size>32*1024*1024)throw new Error("Choose an image smaller than 32 MB.");let w=await createImageBitmap(E);try{if(b!==h)return;let T=Math.min(1,960/Math.max(w.width,w.height)),x=document.createElement("canvas");x.width=Math.max(1,Math.round(w.width*T)),x.height=Math.max(1,Math.round(w.height*T)),x.getContext("2d").drawImage(w,0,0,x.width,x.height),t.bindTexture(t.TEXTURE_2D,s),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,x),i.width=x.width,i.height=x.height,i.style.aspectRatio=`${x.width} / ${x.height}`,e("source").textContent=`${E.name} \xB7 local preview only`,e("input").value="local",o.hidden=!0,p()}finally{w.close()}}catch(w){M(w)}},i.addEventListener("webglcontextlost",g=>{g.preventDefault(),u=!1,m=!0,n(),M(new Error("GPU context lost. Reopen the preview to continue."))});let ae=new IntersectionObserver(g=>{f=g[0].isIntersecting});ae.observe(i);function Oe(){h++,cancelAnimationFrame(d),ae.disconnect(),t?.deleteProgram(c),t?.deleteBuffer(a),t?.deleteTexture(s)}return{show:$e,draw:p,report:M,destroy:Oe,get draft(){return l},get ready(){return u}}}function Ie(r){let n=k(r),e=xe(n.code,n.uniforms,n.postEffects),i="[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?",o=new RegExp(`@default\\s+(?:true|false|${i}(?:\\s*,\\s*${i}){0,2})`,"i");return e.code.replace(/(uniform\s+(?:float|int|bool|vec3)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*;[^\r\n]*)/g,(t,a,s)=>{let l=e.uniformValues[s];if(l===void 0)return t;let c=Array.isArray(l)?l.join(","):String(l);return t.replace(o,`@default ${c}`)})}function Me(r,n,e){let i=u=>r.querySelector(`[data-preview="${u}"]`),o=i("open"),t=i("copy"),a=i("code-text"),s=i("status"),l=0;async function c(){let u=++l;if(o.removeAttribute("href"),o.setAttribute("aria-disabled","true"),t.disabled=!n.ready,a.hidden=!0,s.textContent=n.ready?"Preparing your shader link\u2026":"This shader cannot be opened. Ask your assistant to fix it.",!(!n.ready||!n.draft))try{let m=await _e(structuredClone(n.draft),"https://mapshroom.dev",!0);if(u!==l)return;o.href=m,o.removeAttribute("aria-disabled"),s.textContent=""}catch(m){u===l&&n.report(m)}}return o.onclick=u=>{if(!n.ready||!o.hasAttribute("href")){u.preventDefault();return}e&&(u.preventDefault(),e(o.href).catch(n.report))},t.onclick=async()=>{if(!n.ready||!n.draft)return;let u=Ie(n.draft);try{await navigator.clipboard.writeText(u),a.hidden=!0,s.textContent="Copied."}catch{a.value=u,a.hidden=!1,a.focus(),a.select(),s.textContent="Clipboard access is unavailable. Copy the selected shader code."}},{update:c}}var ie=document.getElementById("mapshroom-preview-ROOT_ID"),se=Re(ie,()=>{ct.update()}),ct=Me(ie,se),Pe=JSON.parse(ie.querySelector('[data-preview="shader"]').textContent);se.show(Pe.shader,Pe.previewInput);window.addEventListener("pagehide",se.destroy,{once:!0});})();
</script>

```
