-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvg-clip-baker-simple.js
More file actions
429 lines (375 loc) · 15.6 KB
/
svg-clip-baker-simple.js
File metadata and controls
429 lines (375 loc) · 15.6 KB
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env node
/**
* svg-clip-baker-simple.js
*
* Flatten simple clip-path groups into real geometry, preserve visual style,
* bake transforms (optional), keep z‑order, and export a clean SVG suitable
* for Blender. Written for Node + Paper.js + jsdom.
*
* Features
* - Flattens groups with `clip-path` (no nested clips support by design).
* - Unions multiple shapes inside a single <clipPath>.
* - Applies global transforms to geometry (opt‑out via --apply-transforms=false).
* - Optionally expands strokes to fills before boolean ops (--expand-stroke=true).
* - Maintains paint (z) order within each baked group.
* - Removes empty groups and redundant canvas-sized clipPaths.
* - Ensures proper width/height/viewBox on output.
* - Unwraps up to two top-level <g> wrappers (after <defs>) for Blender.
*
* Assumptions (aligned with your v3 rules)
* - Each “unit” looks like:
* <g id="clip-*">
* [base shape(s) outside the clipped subgroup]
* <clipPath id="...">...</clipPath>
* <g clip-path="url(#...)"> ...subjects to bake... </g>
* </g>
* - <clipPath> content uses userSpaceOnUse; no objectBoundingBox.
* - AD2 exports strokes already expanded → expandStroke defaults to false.
*
* CLI
* node bake-clips.js input.svg \
* --out output.svg \
* --apply-transforms=true \
* --expand-stroke=false \
* --simplify=0 \
* --verbose
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createCanvas } from "canvas";
import paper from "paper";
import { JSDOM } from "jsdom";
import formatXML from "xml-formatter";
// -----------------------------------------------------------------------------
// Environment bootstrap (Paper.js expects window/document/self/DOMParser etc.)
// -----------------------------------------------------------------------------
const { window } = new JSDOM(`<!doctype html><html><body></body></html>`, {
contentType: "text/html",
});
globalThis.window = window;
globalThis.document = window.document;
globalThis.self = window;
globalThis.DOMParser = window.DOMParser;
globalThis.XMLSerializer = window.XMLSerializer;
// -----------------------------------------------------------------------------
// Path + CLI parsing
// -----------------------------------------------------------------------------
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function parseArgs(argv) {
const args = { _: [] };
for (let i = 2; i < argv.length; i++) {
const token = argv[i];
if (!token.startsWith("--")) { args._.push(token); continue; }
const [k, raw] = token.slice(2).split("=");
let v = raw;
if (v === undefined) {
const next = argv[i + 1];
if (next && !next.startsWith("--")) { v = next; i++; } else { v = true; }
}
if (typeof v === "string" && /^(true|false)$/i.test(v)) v = v.toLowerCase() === "true";
args[k] = v;
}
return args;
}
const args = parseArgs(process.argv);
if (args._.length === 0) {
console.error("Usage: node bake-clips.js input.svg [--out out.svg] [--apply-transforms=true] [--expand-stroke=false] [--simplify=0] [--verbose]");
process.exit(1);
}
const inPath = args._[0];
if (!fs.existsSync(inPath)) {
console.error("Input file not found:", inPath);
process.exit(1);
}
const outPath = args.out || inPath.replace(/\.svg$/i, ".baked.svg");
const APPLY_TRANSFORMS = args["apply-transforms"] !== false;
const EXPAND_STROKE = args["expand-stroke"] === true;
const VERBOSE = !!args["verbose"];
const SIMPLIFY = Math.max(0, parseFloat(args.simplify ?? "0")) || 0;
const vlog = (...m) => { if (VERBOSE) console.log("[bake]", ...m); };
// -----------------------------------------------------------------------------
// Read SVG + viewBox
// -----------------------------------------------------------------------------
const svgText = fs.readFileSync(inPath, "utf8");
const parser = new window.DOMParser();
const svgDoc = parser.parseFromString(svgText, "image/svg+xml");
const svgEl = svgDoc.documentElement;
// Canvas/view fallback if no viewBox
let viewW = 1024, viewH = 768;
const vb = svgEl.getAttribute("viewBox");
if (vb) {
const parts = vb.trim().split(/[ ,]+/).map(Number);
if (parts.length === 4 && parts.every(Number.isFinite)) {
viewW = Math.max(1, parts[2]);
viewH = Math.max(1, parts[3]);
}
}
// -----------------------------------------------------------------------------
// Paper.js setup
// -----------------------------------------------------------------------------
paper.setup(new createCanvas(viewW, viewH)); // sets a default Project + View
paper.view.viewSize = new paper.Size(viewW, viewH); // be explicit
// Create a fresh project for our work; ensure its view matches too
const project = new paper.Project();
project.view.viewSize = new paper.Size(viewW, viewH);
// Import parsed DOM node (not raw string) → keeps defs/ids intact
const root = project.importSVG(svgEl, { expandShapes: true });
/** Helpers: type checks / conversion */
const isPathLike = it => it instanceof paper.Path || it instanceof paper.CompoundPath;
const hasToPath = it => typeof it?.toPath === "function";
/** Create a path clone from any vector item (non-inserted). */
function toPathClone(item) {
if (isPathLike(item)) return item.clone({ insert: false });
if (hasToPath(item)) {
const p = item.toPath(true); // returns new Path
p.remove(); // ensure not inserted
return p;
}
return null;
}
/** Bake global transform into geometry (returns a new non-inserted path). */
function bakeGlobalTransform(pathLike, sourceItem) {
if (!APPLY_TRANSFORMS) return pathLike;
const baked = pathLike.clone({ insert: false });
baked.transform(sourceItem.globalMatrix);
baked.matrix.reset(); // clear residual transform
return baked;
}
/** Expand stroke to fill if requested (best-effort for Path). */
function expandStrokeIfNeeded(item) {
if (!EXPAND_STROKE) return null;
if (item instanceof paper.Path && item.strokeColor && item.strokeWidth) {
try {
const outline = item.expand(item.strokeWidth, {
join: item.strokeJoin,
cap: item.strokeCap,
miterLimit: item.miterLimit,
});
outline.fillColor = item.strokeColor;
outline.strokeColor = null;
outline.remove(); // keep non-inserted until we need it
return outline;
} catch { /* fall through */ }
}
return null;
}
/** Copy relevant visual style props one by one (avoid shared refs). */
function copyVisualStyle(from, to) {
to.fillColor = from.fillColor;
to.strokeColor = from.strokeColor;
to.strokeWidth = from.strokeWidth;
to.strokeJoin = from.strokeJoin;
to.strokeCap = from.strokeCap;
to.miterLimit = from.miterLimit;
to.dashArray = from.dashArray;
to.dashOffset = from.dashOffset;
to.opacity = from.opacity;
to.blendMode = from.blendMode;
to.windingRule = from.windingRule; // evenodd / nonzero
}
/** Union an array of non-inserted paths (returns one non-inserted path). */
function unionMany(paths) {
if (!paths.length) return null;
return paths.slice(1).reduce(
(acc, p) => acc.unite(p, { insert: false }),
paths[0].clone({ insert: false })
);
}
/** DFS collection of paintable (vector/convertible) descendants (z‑order safe). */
function collectPaintItemsDFS(node) {
const out = [];
(function visit(n) {
if (n.clipMask) return; // skip clip shapes here
if (isPathLike(n) || hasToPath(n)) out.push(n);
if (n.children?.length) n.children.forEach(visit);
})(node);
return out;
}
/** Build a single baked (transform‑applied) path for a subject item. */
function subjectToBakedPath(subject) {
// Try stroke expansion first if requested
const expanded = expandStrokeIfNeeded(subject);
if (expanded) return bakeGlobalTransform(expanded, subject);
const p = toPathClone(subject);
if (!p) return null;
return bakeGlobalTransform(p, subject);
}
// -----------------------------------------------------------------------------
// Core: bake a single clipped group
// -----------------------------------------------------------------------------
function bakeClippedGroup(group) {
const clipItems = group.getItems({ recursive: true, match: it => it.clipMask === true });
if (!clipItems.length) {
vlog("No clipMask children under a clipped group; removing clip:", group.name);
group.clipped = false;
return;
}
// Build unioned clip region (toPath + bake transforms)
const clipPieces = clipItems
.map(cm => toPathClone(cm))
.filter(Boolean)
.map(p => bakeGlobalTransform(p, /** source */ p._owner || p)); // _owner may be undefined; p was cloned
const clipRegion = unionMany(clipPieces);
if (!clipRegion) {
vlog("Clip region empty; removing clip.");
group.clipped = false;
clipItems.forEach(it => it.remove());
return;
}
// Subjects in paint order (excluding clip masks)
const subjects = collectPaintItemsDFS(group);
// Intersect each subject with the final clip
for (const subj of subjects) {
const geom = subjectToBakedPath(subj);
if (!geom) { subj.remove(); continue; }
let cut = null;
try {
cut = geom.intersect(clipRegion, { insert: true });
} catch (e) {
vlog("Intersection failed for item:", subj.name || subj.type, e?.message || e);
continue;
}
if (!cut || cut.isEmpty()) {
subj.remove();
continue;
}
copyVisualStyle(subj, cut);
cut.matrix.reset();
// Reinsert above original to preserve local z‑order
try {
subj.parent.addChild(cut);
cut.index = subj.index + 1;
subj.remove();
} catch {
// If parent is gone, leave on active layer as last resort
}
}
// Remove clip shapes + clear flag
clipItems.forEach(it => it.remove());
group.clipped = false;
}
// -----------------------------------------------------------------------------
// Process all clipped groups (deepest-first)
// -----------------------------------------------------------------------------
function processAllClippedGroups(rootNode) {
const clipped = rootNode.getItems({
recursive: true,
match: it => it instanceof paper.Group && it.clipped === true,
});
clipped.reverse().forEach(bakeClippedGroup); // deepest first
}
processAllClippedGroups(root);
// -----------------------------------------------------------------------------
// Cleanup: prune empty groups (post-order)
// -----------------------------------------------------------------------------
function pruneEmptyGroups(node) {
if (!node?.children) return;
node.children.slice().forEach(pruneEmptyGroups);
if (node instanceof paper.Group && node.children.length === 0) node.remove();
}
pruneEmptyGroups(root);
// -----------------------------------------------------------------------------
// Optional geometry simplify (per-path tolerance, non-inserted safe)
// -----------------------------------------------------------------------------
if (SIMPLIFY > 0) {
const items = project.activeLayer.getItems({
recursive: true,
match: it => it instanceof paper.Path || it instanceof paper.CompoundPath,
});
for (const p of items) { try { p.simplify(SIMPLIFY); } catch {} }
}
// -----------------------------------------------------------------------------
// Export as DOM node + post-process
// -----------------------------------------------------------------------------
const bounds = project.activeLayer.bounds;
const sceneW = bounds.width;
const sceneH = bounds.height;
// Normalize 0..1 → px (common after some upstreams)
const targetW = 1080, targetH = 1920;
const isNormalized = sceneW <= 1.01 && sceneH <= 1.01;
if (isNormalized) {
project.activeLayer.translate(new paper.Point(-bounds.x, -bounds.y));
project.activeLayer.scale(targetW, targetH, new paper.Point(0, 0));
}
// Export SVG tree (keep groups; bounds "view" avoids accidental crop)
const outNode = project.exportSVG({ asString: false, bounds: "view" });
// ---- DOM helpers (jsdom) ----
const ELEM = 1;
function walk(node, fn) {
if (!node) return;
if (node.nodeType === ELEM) fn(node);
for (const ch of Array.from(node.childNodes || [])) walk(ch, fn);
}
/** Remove clipPaths that are exact canvas guards (rect == viewport, no transform) and drop their usages. */
function removeRedundantCanvasClips(svgRoot, finalW, finalH) {
const toRemove = new Set();
const clipPaths = [];
walk(svgRoot, n => { if (n.tagName?.toLowerCase() === "clippath") clipPaths.push(n); });
for (const cp of clipPaths) {
const id = cp.getAttribute("id"); if (!id) continue;
const kids = Array.from(cp.childNodes || []).filter(n => n.nodeType === ELEM);
if (kids.length !== 1 || kids[0].tagName?.toLowerCase() !== "rect") continue;
const rect = kids[0];
const x = parseFloat(rect.getAttribute("x") ?? "0");
const y = parseFloat(rect.getAttribute("y") ?? "0");
const w = parseFloat(rect.getAttribute("width") ?? "0");
const h = parseFloat(rect.getAttribute("height") ?? "0");
if (!rect.hasAttribute("transform") && x === 0 && y === 0 && w === finalW && h === finalH) {
toRemove.add(id);
cp.parentNode?.removeChild(cp);
}
}
if (!toRemove.size) return;
walk(svgRoot, node => {
const val = node.getAttribute?.("clip-path");
if (!val) return;
const m = val.match(/^url\(#([^)]+)\)$/);
if (m && toRemove.has(m[1])) node.removeAttribute("clip-path");
});
}
/** Ensure unique ids across the document. */
function dedupeIds(svgRoot) {
const seen = new Map();
walk(svgRoot, node => {
if (!node.hasAttribute?.("id")) return;
const id = node.getAttribute("id"); if (!id) return;
if (!seen.has(id)) { seen.set(id, node); return; }
let base = id.endsWith("-shape") ? id : id + "-shape";
let i = 1, next = base;
while (seen.has(next)) next = `${base}-${i++}`;
node.setAttribute("id", next);
seen.set(next, node);
});
}
/** Unwrap up to `times` top-level <g> wrappers after optional <defs>. */
function unwrapTopGroups(svgRoot, times = 2) {
for (let i = 0; i < times; i++) {
let node = svgRoot.firstElementChild;
if (node?.tagName?.toLowerCase() === "defs") node = node.nextElementSibling;
if (!node || node.tagName?.toLowerCase() !== "g") break;
while (node.firstChild) svgRoot.insertBefore(node.firstChild, node);
svgRoot.removeChild(node);
}
}
// Final size (after potential normalization)
const finalW = isNormalized ? targetW : Math.max(1, Math.round(project.activeLayer.bounds.width));
const finalH = isNormalized ? targetH : Math.max(1, Math.round(project.activeLayer.bounds.height));
// Post-process DOM tree
removeRedundantCanvasClips(outNode, finalW, finalH);
dedupeIds(outNode);
unwrapTopGroups(outNode, 2);
// Enforce viewport on <svg>
outNode.setAttribute("width", String(finalW));
outNode.setAttribute("height", String(finalH));
outNode.setAttribute("viewBox", `0 0 ${finalW} ${finalH}`);
// Serialize + pretty print
const rawXml = new window.XMLSerializer().serializeToString(outNode);
const prettyXml = formatXML(rawXml, { indentation: " ", collapseContent: true });
fs.writeFileSync(outPath, prettyXml, "utf8");
console.log("Baked →", outPath);
if (VERBOSE) {
console.log("Scene:", { sceneW, sceneH, isNormalized, finalW, finalH });
console.log("Options:", { APPLY_TRANSFORMS, EXPAND_STROKE, SIMPLIFY });
}