Skip to content

Commit 38bdbd7

Browse files
committed
count arcs' curves while a path is read and lines when it is flattened, and read a path once a render
1 parent 3afdd73 commit 38bdbd7

2 files changed

Lines changed: 52 additions & 20 deletions

File tree

‎src/render/svg.ts‎

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ export function render(source: string | Uint8Array, mode: 'scale' | 'width' | 'h
201201
filterWorkLeft = MAX_FILTER_WORK + FILTER_WORK_PER_PIXEL * outWidth * outHeight;
202202
paintLeft = MAX_PAINT + PAINT_PER_PIXEL * outWidth * outHeight;
203203
pointsLeft = MAX_POINTS + POINTS_PER_PIXEL * outWidth * outHeight;
204+
const previousPaths = parsedPaths;
205+
parsedPaths = new Map();
204206
try {
205207
const canvas = new Layer(outWidth, outHeight);
206208
// (a transform on the root element (SVG 2) applies before the viewBox mapping)
@@ -212,6 +214,7 @@ export function render(source: string | Uint8Array, mode: 'scale' | 'width' | 'h
212214
filterWorkLeft = previousFilterWork;
213215
paintLeft = previousPaint;
214216
pointsLeft = previousPoints;
217+
parsedPaths = previousPaths;
215218
}
216219
}
217220

@@ -3304,8 +3307,13 @@ function shapePath(node: XNode, viewport: Viewport, fontSize: number): PathComma
33043307
const length = (name: string, axis: 'x' | 'y' | 'diagonal', fallback = 0): number => node.attrs[name] === undefined ? fallback : parseLength(node.attrs[name], viewport, fontSize, axis);
33053308

33063309
switch (node.name) {
3307-
case 'path':
3308-
return parsePath(node.attrs.d || '');
3310+
case 'path': {
3311+
// (read once a render: a path drawn through <use> was read again for each copy; the commands aren't changed)
3312+
const d = node.attrs.d || '';
3313+
let path = parsedPaths?.get(d);
3314+
if (!path) parsedPaths?.set(d, path = parsePath(d));
3315+
return path ?? parsePath(d);
3316+
}
33093317

33103318
case 'rect': {
33113319
const x = length('x', 'x'), y = length('y', 'y');
@@ -3372,8 +3380,29 @@ function shapePath(node: XNode, viewport: Viewport, fontSize: number): PathComma
33723380
return null;
33733381
}
33743382

3383+
// the most points paths may be made of and flattened to in one render: 2^25 and 4 per pixel of the output (a curve
3384+
// gets up to 512, an arc up to 64 curves a turn, and a path drawn through <use> is read and flattened again for each
3385+
// copy, so huge curves far outside the image took gigabytes, and lines drawn without paint minutes), and 2^21 in one
3386+
// path (its points are in memory at once). What is left of it in the render that runs
3387+
const MAX_POINTS = 2 ** 25, POINTS_PER_PIXEL = 4, MAX_PATH_POINTS = 2 ** 21;
3388+
let pointsLeft = Infinity;
3389+
// the paths read in the render that runs, by their path data
3390+
let parsedPaths: Map<string, PathCommand[]> | null = null;
3391+
3392+
/** counts the points of one path against the render's budget and the limit of a path */
3393+
function pointCounter(): (points: number) => void {
3394+
let pathPoints = 0;
3395+
return points => {
3396+
pathPoints += points;
3397+
if ((pointsLeft -= points) < 0 || pathPoints > MAX_PATH_POINTS)
3398+
throw new LimitError(`SVG too complex: its paths are made of more points than a render of this size allows (${MAX_PATH_POINTS} in a path, ${MAX_POINTS} and ${POINTS_PER_PIXEL} per output pixel in all)`);
3399+
};
3400+
}
3401+
33753402
function parsePath(d: string): PathCommand[] {
33763403
const path: PathCommand[] = [];
3404+
// (the curves of arcs count, before they are made: an arc between far-apart ends was 1024 curves a turn)
3405+
const count = pointCounter();
33773406
// numbers stay strings so compact arc flags can be split later
33783407
const items: Array<string | { command: string }> = [];
33793408
// (anything but separators between the tokens ends the path data there)
@@ -3482,7 +3511,7 @@ function parsePath(d: string): PathCommand[] {
34823511
const large = flag(), sweep = flag();
34833512
const nx = number() + ox, ny = number() + oy;
34843513
if ([rx, ry, rotation, large, sweep, nx, ny].some(isNaN)) return path;
3485-
arcToCubics(path, x, y, rx, ry, rotation, large, sweep, nx, ny);
3514+
arcToCubics(path, x, y, rx, ry, rotation, large, sweep, nx, ny, count);
34863515
x = nx;
34873516
y = ny;
34883517
} else return path;
@@ -3494,7 +3523,7 @@ function parsePath(d: string): PathCommand[] {
34943523
}
34953524

34963525
// SVG implementation notes F.6.5: endpoint to center parameterization, split into <= 90 degree cubic segments
3497-
function arcToCubics(path: PathCommand[], x1: number, y1: number, rx: number, ry: number, rotation: number, large: number, sweep: number, x2: number, y2: number): void {
3526+
function arcToCubics(path: PathCommand[], x1: number, y1: number, rx: number, ry: number, rotation: number, large: number, sweep: number, x2: number, y2: number, count: (points: number) => void = () => {}): void {
34983527
if (x1 === x2 && y1 === y2) return;
34993528
rx = Math.abs(rx);
35003529
ry = Math.abs(ry);
@@ -3534,10 +3563,12 @@ function arcToCubics(path: PathCommand[], x1: number, y1: number, rx: number, ry
35343563
else if (sweep && delta < 0) delta += 2 * Math.PI;
35353564

35363565
// as many cubics as kurbo makes for usvg (at a tolerance of 0.1), which places mid markers at their ends
3537-
// (at most 1024 a turn, from a radius of about 1e17: an arc between far-apart ends gets a radius of half their
3538-
// distance, and the count grew with it without a limit)
3539-
const perTurn = Math.min(Math.max(Math.pow(1.1163 * Math.max(rx, ry) / 0.1, 1 / 6), 3.999999), 1024);
3566+
// (at most 64 a turn, from a radius of about 6e9, more than any output resolves: an arc between far-apart ends gets
3567+
// a radius of half their distance, and the count grew with it without a limit)
3568+
const perTurn = Math.min(Math.max(Math.pow(1.1163 * Math.max(rx, ry) / 0.1, 1 / 6), 3.999999), 64);
35403569
const segments = Math.max(1, Math.ceil(perTurn * Math.abs(delta) / (2 * Math.PI)));
3570+
// (a curve's command takes the memory of about 4 points)
3571+
count(4 * segments);
35413572
const step = delta / segments;
35423573
const k = 4 / 3 * Math.tan(step / 4);
35433574

@@ -3554,19 +3585,9 @@ function arcToCubics(path: PathCommand[], x1: number, y1: number, rx: number, ry
35543585
}
35553586
}
35563587

3557-
// the most points paths may be flattened to in one render: 2^25 and 4 per pixel of the output (a curve gets up to 512,
3558-
// so huge curves far outside the image took gigabytes), and 2^22 in one path (its points are in memory at once)
3559-
const MAX_POINTS = 2 ** 25, POINTS_PER_PIXEL = 4, MAX_PATH_POINTS = 2 ** 22;
3560-
let pointsLeft = Infinity;
3561-
35623588
// flattens path commands into polylines: [{points: [x, y, ...], closed}]
35633589
function flatten(path: PathCommand[], tolerance: number): Subpath[] {
3564-
let pathPoints = 0;
3565-
const count = (points: number): void => {
3566-
pathPoints += points;
3567-
if ((pointsLeft -= points) < 0 || pathPoints > MAX_PATH_POINTS)
3568-
throw new LimitError(`SVG too complex: its paths flatten to more points than a render of this size allows (${MAX_PATH_POINTS} in a path, ${MAX_POINTS} and ${POINTS_PER_PIXEL} per output pixel in all)`);
3569-
};
3590+
const count = pointCounter();
35703591
const subpaths: Subpath[] = [];
35713592
let current: Subpath | null = null;
35723593
let x = 0, y = 0, sx = 0, sy = 0;
@@ -3582,9 +3603,11 @@ function flatten(path: PathCommand[], tolerance: number): Subpath[] {
35823603
case 'M':
35833604
x = sx = command[1];
35843605
y = sy = command[2];
3606+
count(1);
35853607
current = start(x, y);
35863608
break;
35873609
case 'L':
3610+
count(1);
35883611
if (!current) current = start(x, y);
35893612
x = command[1];
35903613
y = command[2];

‎tests/svg-arcs.js‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,16 @@ const cases = {
2323
'arc from 1e300': svg('<path d="M 1e300 100 A 40 30 20 1 1 160 100" fill="none" stroke="gray"/>'),
2424
'arc of radius 1e300': svg('<path d="M 10 10 A 1e300 1e300 0 1 1 20 20" fill="none" stroke="gray"/>'),
2525
'1000 arcs between 1e12 and -1e12': svg(`<path d="${many}" fill="none" stroke="red"/>`),
26-
'circle of radius 1e30': svg('<circle cx="100" cy="100" r="1e30" fill="none" stroke="red"/>')
26+
'circle of radius 1e30': svg('<circle cx="100" cy="100" r="1e30" fill="none" stroke="red"/>'),
27+
// many such arcs in one path: their curves were made while the path was read, before any budget counted them
28+
'20000 arcs between 1e30 and -1e30': svg(`<path d="M -1e30 100${Array.from({length: 20000}, (_, i) => i & 1 ? 'A1 1 0 1 1-1e30 100' : 'A1 1 0 1 1 1e30 100').join('')}"/>`),
29+
'100000 arcs between 1e12 and -1e12': svg(`<path d="M -1e12 100${Array.from({length: 100000}, (_, i) => i & 1 ? 'A1 1 0 1 1-1e12 100' : 'A1 1 0 1 1 1e12 100').join('')}" fill="none" stroke="red"/>`),
30+
// a path of lines only, drawn 90000 times through <use> without painting anything: no budget counted its points
31+
'lines through use': (() => {
32+
let defs = `<path id="g0" d="M0 0${'h1h-1'.repeat(50000)}" fill="none"/>`;
33+
for (let i = 1; i <= 4; i++) defs += `<g id="g${i}">${`<use href="#g${i - 1}"/>`.repeat(10)}</g>`;
34+
return `<svg viewBox="0 0 10 10" width="10" height="10" ${NS}><defs>${defs}</defs>${'<use href="#g4"/>'.repeat(9)}</svg>`;
35+
})()
2736
};
2837
const [command, ...flags] = typeof Deno !== 'undefined' ? [process.execPath, 'run', '-A', '--v8-flags=--max-old-space-size=1024'] : [process.execPath, ...(process.versions.bun ? [] : ['--max-old-space-size=1024'])];
2938
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'svg-arcs-'));
@@ -34,7 +43,7 @@ try {
3443
const begin = Date.now();
3544
let output;
3645
try {
37-
output = JSON.parse(child_process.execFileSync(command, [...flags, './tests/util/render-svg.js', file], {timeout: 60000, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']}).trim());
46+
output = JSON.parse(child_process.execFileSync(command, [...flags, './tests/util/render-svg.js', file], {timeout: 60000, maxBuffer: 1 << 24, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']}).trim());
3847
} catch (error) {
3948
panic(`${name}: ${error.signal === 'SIGTERM' ? 'hung for 60 s' : `crashed (${error.signal || `exit ${error.status}`})`}`);
4049
}

0 commit comments

Comments
 (0)