File size: 15,685 Bytes
f638bf2 d82af83 f638bf2 3aacba8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SpawnGen Studio</title>
<base href="/" />
<link rel="icon" href="data:," />
<link rel="stylesheet" href="css/app.css" />
</head>
<body>
<div id="app">
<div class="boot">Loading SpawnGen Studio...</div>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="." class="reload">Reload</a>
<span class="dismiss">x</span>
</div>
<script>
// Lets files be dropped on the editor: they go to the page (OnFileDropped) as bytes.
window.spawngenEnableDrop = function (dotnetRef, selector) {
const el = document.querySelector(selector);
el.addEventListener("dragover", e => e.preventDefault());
el.addEventListener("drop", async e => {
e.preventDefault();
const node = e.dataTransfer.getData("text/spawngen-node");
if (node) { const r = el.getBoundingClientRect(); await dotnetRef.invokeMethodAsync("OnNodeDropped", node, e.clientX - r.left, e.clientY - r.top); return; }
for (const f of e.dataTransfer.files)
await dotnetRef.invokeMethodAsync("OnFileDropped", f.name, new Uint8Array(await f.arrayBuffer()));
});
};
// A node dragged out of the library carries its class name.
document.addEventListener("dragstart", e => {
const n = e.target.closest && e.target.closest("[data-node]");
if (n) { e.dataTransfer.setData("text/spawngen-node", n.dataset.node); e.dataTransfer.effectAllowed = "copy"; }
});
// The mask editor: paint over a picture, get it back as a PNG whose painted pixels are transparent (what Load Image turns into its mask).
// Resolves with the PNG bytes, or null when cancelled or the picture cannot be read.
window.spawngenMaskEditor = function (imageUrl) {
return new Promise(async resolve => {
const img = new Image();
img.src = imageUrl;
try { await img.decode(); } catch (e) { resolve(null); return; }
const w = img.naturalWidth, h = img.naturalHeight;
if (!w || !h) { resolve(null); return; }
const root = document.createElement("div");
root.className = "maskeditor";
root.innerHTML = '<div class="me-bar"><span>Mask editor</span>' +
'<label>Brush <input class="me-size" type="range" min="2" max="200" value="40"></label>' +
'<button class="me-mode" data-mode="paint">Paint</button><button class="me-mode" data-mode="erase">Erase</button>' +
'<button class="me-clear">Clear</button><button class="me-invert">Invert</button>' +
'<span class="me-spacer"></span><button class="me-cancel">Cancel</button><button class="me-save">Save</button></div>' +
'<div class="me-stage"><div class="me-stack"><canvas class="me-base"></canvas><canvas class="me-mask"></canvas></div></div>';
document.body.appendChild(root);
const base = root.querySelector(".me-base"), mask = root.querySelector(".me-mask");
base.width = mask.width = w; base.height = mask.height = h;
const bctx = base.getContext("2d"), mctx = mask.getContext("2d");
bctx.drawImage(img, 0, 0);
// An existing mask (transparent pixels of the picture) comes back as paint.
const pix = bctx.getImageData(0, 0, w, h);
const init = mctx.createImageData(w, h);
for (let i = 0; i < pix.data.length; i += 4) {
if (pix.data[i + 3] < 128) { init.data[i] = 255; init.data[i + 1] = 59; init.data[i + 2] = 59; init.data[i + 3] = 255; }
pix.data[i + 3] = 255;
}
bctx.putImageData(pix, 0, 0);
mctx.putImageData(init, 0, 0);
let mode = "paint", drawing = false, last = null;
const modes = root.querySelectorAll(".me-mode");
const setMode = m => { mode = m; modes.forEach(b => b.classList.toggle("on", b.dataset.mode === m)); };
setMode("paint");
modes.forEach(b => b.onclick = () => setMode(b.dataset.mode));
const size = root.querySelector(".me-size");
const at = e => { const r = mask.getBoundingClientRect(); return { x: (e.clientX - r.left) * w / r.width, y: (e.clientY - r.top) * h / r.height }; };
const stroke = (a, b) => {
mctx.globalCompositeOperation = mode === "erase" ? "destination-out" : "source-over";
mctx.strokeStyle = "#ff3b3b"; mctx.fillStyle = "#ff3b3b";
mctx.lineWidth = +size.value; mctx.lineCap = "round"; mctx.lineJoin = "round";
mctx.beginPath(); mctx.moveTo(a.x, a.y); mctx.lineTo(b.x + 0.01, b.y); mctx.stroke();
};
mask.onpointerdown = e => { drawing = true; mask.setPointerCapture(e.pointerId); last = at(e); stroke(last, last); };
mask.onpointermove = e => { if (!drawing) return; const p = at(e); stroke(last, p); last = p; };
mask.onpointerup = mask.onpointercancel = () => { drawing = false; };
root.querySelector(".me-clear").onclick = () => mctx.clearRect(0, 0, w, h);
root.querySelector(".me-invert").onclick = () => {
const d = mctx.getImageData(0, 0, w, h);
for (let i = 0; i < d.data.length; i += 4) { const on = d.data[i + 3] > 127; d.data[i] = 255; d.data[i + 1] = 59; d.data[i + 2] = 59; d.data[i + 3] = on ? 0 : 255; }
mctx.putImageData(d, 0, 0);
};
const finish = result => { document.removeEventListener("keydown", onKey); root.remove(); resolve(result); };
const onKey = e => { if (e.key === "Escape") { e.preventDefault(); finish(null); } };
document.addEventListener("keydown", onKey);
root.querySelector(".me-cancel").onclick = () => finish(null);
root.querySelector(".me-save").onclick = async () => {
const out = document.createElement("canvas"); out.width = w; out.height = h;
const octx = out.getContext("2d");
octx.drawImage(base, 0, 0);
octx.globalCompositeOperation = "destination-out";
// Anything painted by more than half counts as masked: the soft edge of a stroke is not a half-transparent hole.
const d = mctx.getImageData(0, 0, w, h);
for (let i = 0; i < d.data.length; i += 4) d.data[i + 3] = d.data[i + 3] > 127 ? 255 : 0;
const tmp = document.createElement("canvas"); tmp.width = w; tmp.height = h;
tmp.getContext("2d").putImageData(d, 0, 0);
octx.drawImage(tmp, 0, 0);
out.toBlob(async blob => finish(blob ? new Uint8Array(await blob.arrayBuffer()) : null), "image/png");
};
});
};
// Browser storage for the open workflows (tabs, autosave). It can be missing or full: every call is allowed to fail quietly.
window.spawngenStoreGet = function (key) { try { return localStorage.getItem(key); } catch (e) { return null; } };
window.spawngenSetTheme = function (id) { document.documentElement.dataset.theme = id === 'light' ? 'light' : 'dark'; };
// Applied before the app boots, so a light page does not flash dark first.
try { window.spawngenSetTheme(JSON.parse(localStorage.getItem('spawngen.settings') || '{}').Palette); } catch (e) { }
window.spawngenStoreSet = function (key, value) { try { localStorage.setItem(key, value); return true; } catch (e) { return false; } };
// The workflow library when no server serves the Studio: files in IndexedDB (database spawngen-userdata, store files, {path, text, modified,
// created}). Each call is one transaction; results are strings ("done", "exists", "missing") or JSON text.
window.spawngenFiles = (function () {
let db = null;
function open() {
return db ??= new Promise((resolve, reject) => {
const r = indexedDB.open("spawngen-userdata", 1);
r.onupgradeneeded = () => r.result.createObjectStore("files", { keyPath: "path" });
r.onsuccess = () => resolve(r.result);
r.onerror = () => { db = null; reject(r.error); };
});
}
async function run(mode, body) {
const store = (await open()).transaction("files", mode).objectStore("files");
return new Promise((resolve, reject) => {
store.transaction.onerror = () => reject(store.transaction.error);
body(store, resolve);
});
}
const get = (store, path, then) => { const r = store.get(path); r.onsuccess = () => then(r.result ?? null); };
return {
list: () => run("readonly", (s, done) => {
const r = s.getAll();
r.onsuccess = () => done(JSON.stringify(r.result.map(f => ({ path: f.path, size: new Blob([f.text]).size, modified: f.modified }))));
}),
read: path => run("readonly", (s, done) => get(s, path, f => done(f ? f.text : null))),
write: (path, text, overwrite) => run("readwrite", (s, done) => get(s, path, old => {
if (old && !overwrite) { done("exists"); return; }
const now = Date.now();
s.put({ path, text, modified: now, created: old ? old.created : now }).onsuccess = () => done("done");
})),
move: (from, to, overwrite) => run("readwrite", (s, done) => get(s, from, f => {
if (!f) { done("missing"); return; }
if (from === to) { done("done"); return; }
get(s, to, old => {
if (old && !overwrite) { done("exists"); return; }
s.put({ ...f, path: to });
s.delete(from).onsuccess = () => done("done");
});
})),
remove: path => run("readwrite", (s, done) => get(s, path, f => {
if (!f) { done("missing"); return; }
s.delete(path).onsuccess = () => done("done");
})),
};
})();
// Ctrl+O: the toolbar's Open file picker (called while the key press still counts as the user's action).
window.spawngenOpenWorkflowFile = function () {
const input = document.querySelector('.toolbar input[type=file][accept=".json,.png"]');
if (input) input.click();
};
// Plays an animated picture (Save Animated WEBP / PNG, a GIF) on a canvas of its own, which the node canvas draws every frame: a canvas
// drawImage of an animated <img> shows only its first frame (the HTML spec's rule; TJ 2026-11-19: the LTX example's WEBP sat still).
// WebCodecs' ImageDecoder decodes one frame at a time, so only one frame is held. Returns null where ImageDecoder is missing; the canvas
// stays 0 x 0 for a still picture or a type the browser cannot decode (the caller then shows the <img> as before).
window.spawngenAnimate = function (url) {
if (typeof ImageDecoder === "undefined") return null;
const canvas = document.createElement("canvas");
canvas.width = 0; canvas.height = 0;
(async () => {
const blob = await (await fetch(url)).blob();
if (!blob.type || !(await ImageDecoder.isTypeSupported(blob.type))) return;
const decoder = new ImageDecoder({ data: blob.stream(), type: blob.type });
try {
await decoder.tracks.ready;
const track = decoder.tracks.selectedTrack;
if (!track || !track.animated) return;
await decoder.completed;
const ctx = canvas.getContext("2d");
for (let index = 0; !canvas.spawngenStop; index = (index + 1) % track.frameCount) {
const frame = (await decoder.decode({ frameIndex: index })).image;
if (canvas.width !== frame.displayWidth || canvas.height !== frame.displayHeight) { canvas.width = frame.displayWidth; canvas.height = frame.displayHeight; }
ctx.drawImage(frame, 0, 0);
const ms = frame.duration ? frame.duration / 1000 : 100;
frame.close();
await new Promise(r => setTimeout(r, Math.max(16, ms)));
}
} finally { decoder.close(); }
})().catch(e => console.warn("spawngenAnimate", e));
return canvas;
};
window.spawngenAnimateStop = function (canvas) { if (canvas) canvas.spawngenStop = true; };
// Saves a picture (a data, blob or same-origin URL) as a file download.
window.spawngenDownloadUrl = function (name, url) {
const a = document.createElement("a");
a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove();
};
// Saves text as a file download (the workflow JSON).
window.spawngenDownload = function (name, text) {
const url = URL.createObjectURL(new Blob([text], { type: "application/json" }));
const a = document.createElement("a");
a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
};
</script>
<script src="js/glbviewer.js"></script>
<script src="_framework/blazor.webassembly.js" autostart="false"></script>
<script>
// GitHub Pages serves files exactly as stored: off localhost every boot resource except the JS modules is fetched as its precompressed .gz copy
// and inflated by the browser's own DecompressionStream. The AOT runtime (dotnet.native.wasm) is over 100 MB raw and about 3.5x smaller this way.
Blazor.start({
loadBootResource: function (type, name, defaultUri, integrity) {
if (type === 'dotnetjs' || type === 'configuration' || type === 'manifest' || location.hostname === 'localhost' || typeof DecompressionStream === 'undefined')
return null;
return (async function () {
const r = await fetch(defaultUri + '.gz');
if (!r.ok) return fetch(defaultUri); // no compressed copy: the original
const contentType = type === 'dotnetwasm' ? 'application/wasm' : 'application/octet-stream';
// a server that already sent it with Content-Encoding: gzip had the browser inflate it
const body = r.headers.get('content-encoding') ? r.body : r.body.pipeThrough(new DecompressionStream('gzip'));
return new Response(body, { headers: { 'content-type': contentType } });
})();
}
});
</script>
</body>
</html>
|