imagescript 4.0.0-rc.3 → 4.0.0-rc.4
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/README.md +9 -0
- package/dist/animation-encoder.d.ts +13 -6
- package/dist/animation-encoder.js +9 -7
- package/dist/animation.d.ts +46 -6
- package/dist/animation.js +50 -18
- package/dist/codecs/gif.js +16 -5
- package/dist/codecs/jpeg.js +2 -0
- package/dist/codecs/jxl/frame.js +4 -1
- package/dist/codecs/png.js +46 -20
- package/dist/codecs/quantize.js +3 -5
- package/dist/codecs/tiff.js +7 -0
- package/dist/codecs/webp.js +19 -18
- package/dist/colors.js +25 -17
- package/dist/frame.d.ts +18 -5
- package/dist/gainmap.d.ts +39 -13
- package/dist/gainmap.js +4 -1
- package/dist/image.d.ts +363 -117
- package/dist/image.js +42 -35
- package/dist/metadata.d.ts +8 -2
- package/dist/package.json +1 -1
- package/dist/render/svg.js +133 -49
- package/dist/text-layout.d.ts +11 -5
- package/dist/util/limits.d.ts +5 -0
- package/dist/util/limits.js +4 -0
- package/dist/util/options.js +31 -5
- package/dist/util/rotate.js +43 -0
- package/package.json +1 -2
package/dist/image.js
CHANGED
|
@@ -26,15 +26,17 @@ import { encode as utf8 } from "./util/utf8.js";
|
|
|
26
26
|
import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
|
|
27
27
|
import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
|
|
28
28
|
import { Colors, wrapHue, hue2rgb } from "./colors.js";
|
|
29
|
-
import { isOptions, checkOptions, finite, oneOf, pixelLimit, checkThreads, gainMapScale, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
|
|
30
|
-
import { MAX_PIXELS, LimitError, decoding } from "./util/limits.js";
|
|
29
|
+
import { isOptions, checkOptions, finite, nonNegative, positive, unitInterval, oneOf, pixelLimit, checkThreads, gainMapScale, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
|
|
30
|
+
import { MAX_PIXELS, LimitError, decoding, checkGrowth } from "./util/limits.js";
|
|
31
31
|
import { GainMap } from "./gainmap.js";
|
|
32
32
|
import * as gain from "./util/gain.js";
|
|
33
33
|
import { multiply, invert } from "./util/matrix.js";
|
|
34
34
|
import { sampleAffine } from "./util/affine.js";
|
|
35
|
+
import { rotateBilinear } from "./util/rotate.js";
|
|
35
36
|
import * as gainMapCodec from "./codecs/gainmap.js";
|
|
36
37
|
const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
|
|
37
38
|
const RESIZE_FITS = ['fill', 'inside', 'contain', 'cover'];
|
|
39
|
+
const CIRCLE_FITS = ['contain', 'cover'];
|
|
38
40
|
const SUBSAMPLINGS = ['4:4:4', '4:2:0'];
|
|
39
41
|
export const TONE_MAPPINGS = ['reinhard', 'clamp'];
|
|
40
42
|
export const FLIP_DIRECTIONS = ['horizontal', 'vertical'];
|
|
@@ -79,7 +81,7 @@ export class Image {
|
|
|
79
81
|
set gainMap(gainMap) {
|
|
80
82
|
if (gainMap !== null && !(gainMap instanceof GainMap))
|
|
81
83
|
throw new TypeError('The gain map has to be a GainMap or null');
|
|
82
|
-
this.__gain_map__ = gainMap;
|
|
84
|
+
this.__gain_map__ = gainMap?.clone() ?? null;
|
|
83
85
|
}
|
|
84
86
|
get bitmap() {
|
|
85
87
|
return this.__bitmap__;
|
|
@@ -186,10 +188,12 @@ export class Image {
|
|
|
186
188
|
if (typeof color !== 'function')
|
|
187
189
|
color = checkColor(color);
|
|
188
190
|
if (typeof color === 'function') {
|
|
191
|
+
const pixels = new Uint8ClampedArray(this.bitmap.length), out = new DataView(pixels.buffer);
|
|
189
192
|
let offset = 0;
|
|
190
193
|
for (let y = 0; y < this.height; y++)
|
|
191
194
|
for (let x = 0; x < this.width; x++, offset += 4)
|
|
192
|
-
|
|
195
|
+
out.setUint32(offset, checkColor(color(x, y)), false);
|
|
196
|
+
this.bitmap.set(pixels);
|
|
193
197
|
}
|
|
194
198
|
else {
|
|
195
199
|
view.setUint32(0, color, false);
|
|
@@ -211,6 +215,7 @@ export class Image {
|
|
|
211
215
|
scale(factor, options) {
|
|
212
216
|
checkOptions(options, 'scale(factor, { mode: \'area\' })');
|
|
213
217
|
const { mode } = resizeOptions(options);
|
|
218
|
+
finite(factor, 'scale factor');
|
|
214
219
|
const image = this.__scale__(factor, mode);
|
|
215
220
|
this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
|
|
216
221
|
this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
|
|
@@ -270,9 +275,10 @@ export class Image {
|
|
|
270
275
|
if (resizeOpts.mode !== 'nearest-neighbor' && width >= 1 && height >= 1) {
|
|
271
276
|
const region = { x: ~~((resizedWidth - width) / 2), y: ~~((resizedHeight - height) / 2), width, height };
|
|
272
277
|
const fx = resizedWidth / this.width, fy = resizedHeight / this.height;
|
|
278
|
+
const resized = this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, region);
|
|
273
279
|
this.__gain_map__?.__transform__(this.width, this.height, width, height, (X, Y) => [(X + region.x) / fx, (Y + region.y) / fy], Math.min(fx, fy));
|
|
274
280
|
this.__moved__?.(fx, fy, region.x, region.y);
|
|
275
|
-
return this.__apply__(
|
|
281
|
+
return this.__apply__(resized);
|
|
276
282
|
}
|
|
277
283
|
this.resize(resizedWidth, resizedHeight, resizeOpts);
|
|
278
284
|
return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height);
|
|
@@ -354,6 +360,7 @@ export class Image {
|
|
|
354
360
|
return this.__apply__(this.__crop__(...bounds));
|
|
355
361
|
}
|
|
356
362
|
__trim_bounds__(color, { tolerance = 0 }) {
|
|
363
|
+
finite(tolerance, 'tolerance');
|
|
357
364
|
if (!(tolerance >= 0 && tolerance <= 1))
|
|
358
365
|
throw new RangeError('Invalid tolerance, it has to be between 0 and 1');
|
|
359
366
|
const bitmap = this.bitmap;
|
|
@@ -407,12 +414,11 @@ export class Image {
|
|
|
407
414
|
return image;
|
|
408
415
|
}
|
|
409
416
|
cropCircle(options = {}) {
|
|
410
|
-
checkOptions(options, 'cropCircle({
|
|
411
|
-
const {
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
const radius = (size === 'cover' ? Math.max : Math.min)(this.width, this.height) / 2;
|
|
417
|
+
checkOptions(options, 'cropCircle({ fit: \'cover\' })');
|
|
418
|
+
const { fit = 'contain', feathering = 0 } = options;
|
|
419
|
+
unitInterval(feathering, 'feathering');
|
|
420
|
+
oneOf(fit, CIRCLE_FITS, 'fit');
|
|
421
|
+
const radius = (fit === 'cover' ? Math.max : Math.min)(this.width, this.height) / 2;
|
|
416
422
|
const cx = this.width / 2, cy = this.height / 2;
|
|
417
423
|
const band = Math.min(1, Math.max(0, feathering)) * radius;
|
|
418
424
|
for (let y = 0; y < this.height; y++) {
|
|
@@ -514,12 +520,9 @@ export class Image {
|
|
|
514
520
|
checkOptions(options, 'composite(source, { x: 10, y: 20 })');
|
|
515
521
|
if (!(source instanceof Image))
|
|
516
522
|
throw new TypeError('composite() takes an Image as its source, like image.composite(logo, { x: 10, y: 20 })');
|
|
517
|
-
const { opacity = 1, mode = 'normal' } = options;
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
y = Math.trunc(finite(y, 'y'));
|
|
521
|
-
if (isNaN(opacity) || opacity < 0 || opacity > 1)
|
|
522
|
-
throw new RangeError('Invalid composite opacity');
|
|
523
|
+
const { opacity = 1, mode = 'normal', x: givenX = 0, y: givenY = 0 } = options;
|
|
524
|
+
const x = Math.trunc(finite(givenX, 'x')), y = Math.trunc(finite(givenY, 'y'));
|
|
525
|
+
unitInterval(opacity, 'opacity');
|
|
523
526
|
const blend = BLEND_MODES[oneOf(mode, Object.keys(BLEND_MODES), 'blend mode')];
|
|
524
527
|
if (opacity === 0)
|
|
525
528
|
return this;
|
|
@@ -731,8 +734,7 @@ export class Image {
|
|
|
731
734
|
return this;
|
|
732
735
|
}
|
|
733
736
|
blur(radius) {
|
|
734
|
-
|
|
735
|
-
throw new RangeError('Invalid blur radius');
|
|
737
|
+
nonNegative(radius, 'blur radius');
|
|
736
738
|
const map = this.__gain_map__;
|
|
737
739
|
if (map && radius * map.width / this.width >= 0.5)
|
|
738
740
|
map.image = map.image.clone().blur(radius * map.width / this.width);
|
|
@@ -913,6 +915,7 @@ export class Image {
|
|
|
913
915
|
: { left: 0, top: 0, right: 0, bottom: 0 });
|
|
914
916
|
}
|
|
915
917
|
__shape_layer__(margin) {
|
|
918
|
+
checkGrowth(this.width + 2 * margin, this.height + 2 * margin, 'The shadow or outline');
|
|
916
919
|
const layer = new Image(this.width + 2 * margin, this.height + 2 * margin);
|
|
917
920
|
for (let y = 0; y < this.height; y++)
|
|
918
921
|
for (let x = 0; x < this.width; x++)
|
|
@@ -922,6 +925,7 @@ export class Image {
|
|
|
922
925
|
__under__(layer, layerX, layerY, grow) {
|
|
923
926
|
const { left, top, right, bottom } = grow;
|
|
924
927
|
const width = this.width + left + right, height = this.height + top + bottom;
|
|
928
|
+
checkGrowth(width, height, 'The shadow or outline');
|
|
925
929
|
const result = new Image(width, height);
|
|
926
930
|
result.composite(layer, { x: layerX + left, y: layerY + top });
|
|
927
931
|
const map = this.__gain_map__;
|
|
@@ -938,11 +942,8 @@ export class Image {
|
|
|
938
942
|
}
|
|
939
943
|
sharpen(options = {}) {
|
|
940
944
|
checkOptions(options, 'sharpen({ amount: 0.5 })');
|
|
941
|
-
const { amount = 1, radius = 1 } = options;
|
|
942
|
-
|
|
943
|
-
throw new RangeError('Invalid sharpen amount');
|
|
944
|
-
if (!Number.isFinite(radius) || radius <= 0)
|
|
945
|
-
throw new RangeError('Invalid sharpen radius');
|
|
945
|
+
const { amount: givenAmount = 1, radius: givenRadius = 1 } = options;
|
|
946
|
+
const amount = nonNegative(givenAmount, 'sharpen amount'), radius = positive(givenRadius, 'sharpen radius');
|
|
946
947
|
const blurred = premultiply(this.bitmap);
|
|
947
948
|
gaussianBlur(blurred, this.width, this.height, radius);
|
|
948
949
|
const bitmap = this.bitmap;
|
|
@@ -1005,6 +1006,8 @@ export class Image {
|
|
|
1005
1006
|
checkOptions(options, 'colorToAlpha({ color: 0xffffffff })');
|
|
1006
1007
|
const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = options;
|
|
1007
1008
|
let color = colorOption;
|
|
1009
|
+
finite(transparencyThreshold, 'transparencyThreshold');
|
|
1010
|
+
finite(opacityThreshold, 'opacityThreshold');
|
|
1008
1011
|
if (!(transparencyThreshold >= 0 && opacityThreshold <= 1 && transparencyThreshold < opacityThreshold))
|
|
1009
1012
|
throw new RangeError('Invalid thresholds, they have to satisfy 0 <= transparencyThreshold < opacityThreshold <= 1');
|
|
1010
1013
|
const bitmap = this.bitmap;
|
|
@@ -1111,6 +1114,10 @@ export class Image {
|
|
|
1111
1114
|
const outHeight = expand ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height;
|
|
1112
1115
|
const out = new Image(outWidth, outHeight);
|
|
1113
1116
|
rotateGainMap(outWidth, outHeight);
|
|
1117
|
+
if (mode === 'bilinear' && rotateBilinear(this.bitmap, width, height, out.bitmap, outWidth, outHeight, sin, cos)) {
|
|
1118
|
+
this.__moved__?.(1, 1, (width - outWidth) / 2, (height - outHeight) / 2);
|
|
1119
|
+
return this.__apply__(out);
|
|
1120
|
+
}
|
|
1114
1121
|
const inverse = [cos, sin, -sin, cos,
|
|
1115
1122
|
width / 2 - cos * outWidth / 2 + sin * outHeight / 2, height / 2 - sin * outWidth / 2 - cos * outHeight / 2];
|
|
1116
1123
|
sampleAffine(this.bitmap, width, height, out.bitmap, outWidth, outHeight, inverse, 0, 0, mode);
|
|
@@ -1176,9 +1183,9 @@ export class Image {
|
|
|
1176
1183
|
}
|
|
1177
1184
|
roundCorners(options = {}) {
|
|
1178
1185
|
checkOptions(options, 'roundCorners({ radius: 10 })');
|
|
1179
|
-
|
|
1180
|
-
radius =
|
|
1181
|
-
radius = Math.
|
|
1186
|
+
const { radius: givenRadius = Math.min(this.width, this.height) / 4 } = options;
|
|
1187
|
+
let radius = nonNegative(givenRadius, 'radius');
|
|
1188
|
+
radius = Math.min(radius, this.width / 2, this.height / 2);
|
|
1182
1189
|
const size = Math.ceil(radius);
|
|
1183
1190
|
for (let y = 0; y < size; y++) {
|
|
1184
1191
|
for (let x = 0; x < size; x++) {
|
|
@@ -1194,7 +1201,7 @@ export class Image {
|
|
|
1194
1201
|
}
|
|
1195
1202
|
fisheye(options = {}) {
|
|
1196
1203
|
checkOptions(options, 'fisheye({ strength: 3 })');
|
|
1197
|
-
const strength =
|
|
1204
|
+
const strength = positive(options.strength === undefined ? 2 : options.strength, 'strength');
|
|
1198
1205
|
const r = new Image(this.width, this.height);
|
|
1199
1206
|
const w = this.width;
|
|
1200
1207
|
const h = this.height;
|
|
@@ -1396,6 +1403,8 @@ export class Image {
|
|
|
1396
1403
|
const { icc, cicp, colorSpace } = decoded;
|
|
1397
1404
|
(icc ? profileTransform(icc) : cicp ? cicpTransform(...cicp) : colorSpace ? colorSpaceTransform(colorSpace.xy, colorSpace.curve) : null)?.(decoded.pixels);
|
|
1398
1405
|
}
|
|
1406
|
+
if (!(decoded.width >= 1 && decoded.height >= 1) || decoded.pixels.length !== decoded.width * decoded.height * 4)
|
|
1407
|
+
throw new Error('Image: damaged or truncated image data');
|
|
1399
1408
|
const image = new Image(decoded.width, decoded.height);
|
|
1400
1409
|
image.bitmap = alignedPixels(decoded.pixels);
|
|
1401
1410
|
if (gainMap && ImageType.isJPEG(dataView)) {
|
|
@@ -1479,7 +1488,7 @@ export class Image {
|
|
|
1479
1488
|
checkOptions(options, 'renderSVG(svg, { width: 512 })');
|
|
1480
1489
|
const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, font: fonts = [], images: givenImages = {} } = options;
|
|
1481
1490
|
pixelLimit(maxPixels);
|
|
1482
|
-
const { maxLayerPixels = 4 *
|
|
1491
|
+
const { maxLayerPixels = 4 * maxPixels, maxImagePixels = maxPixels } = options;
|
|
1483
1492
|
pixelLimit(maxLayerPixels, 'maxLayerPixels');
|
|
1484
1493
|
pixelLimit(maxImagePixels, 'maxImagePixels');
|
|
1485
1494
|
const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
|
|
@@ -1503,7 +1512,7 @@ export class Image {
|
|
|
1503
1512
|
const source = typeof svg === 'string' ? svg : view(svg);
|
|
1504
1513
|
const images = new Map();
|
|
1505
1514
|
const shown = (href) => JSON.stringify(href.length > 100 ? `${href.slice(0, 100)}...` : href);
|
|
1506
|
-
let imagePixels =
|
|
1515
|
+
let imagePixels = maxImagePixels;
|
|
1507
1516
|
for (const { href, data } of svgRenderer.imageReferences(source)) {
|
|
1508
1517
|
const value = given.get(href) ?? data;
|
|
1509
1518
|
if (!value)
|
|
@@ -1534,7 +1543,7 @@ export class Image {
|
|
|
1534
1543
|
images.set(href, { error: err instanceof LimitError ? tooLarge(err) : new Error(`SVG: the image ${shown(href)} can't be decoded`, { cause: err }) });
|
|
1535
1544
|
}
|
|
1536
1545
|
}
|
|
1537
|
-
const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)),
|
|
1546
|
+
const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), maxPixels, maxLayerPixels);
|
|
1538
1547
|
const image = new Image(width, height);
|
|
1539
1548
|
image.bitmap.set(pixels);
|
|
1540
1549
|
return image;
|
|
@@ -1549,9 +1558,7 @@ export class Image {
|
|
|
1549
1558
|
const { width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign } = options;
|
|
1550
1559
|
const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign });
|
|
1551
1560
|
const axes = textRenderer.axisValues(variations);
|
|
1552
|
-
const size =
|
|
1553
|
-
if (size < 0)
|
|
1554
|
-
throw new RangeError(`Invalid font size: ${size}`);
|
|
1561
|
+
const size = positive(options.size, 'font size');
|
|
1555
1562
|
if (finite(strokeWidth, 'stroke width') < 0)
|
|
1556
1563
|
throw new RangeError('Invalid stroke width');
|
|
1557
1564
|
const fonts = Array.isArray(font) ? font : [font];
|
|
@@ -1567,7 +1574,7 @@ export class Image {
|
|
|
1567
1574
|
layout.width -= 2 * pad;
|
|
1568
1575
|
if (layout.height !== undefined)
|
|
1569
1576
|
layout.height -= 2 * pad;
|
|
1570
|
-
const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes,
|
|
1577
|
+
const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes, maxPixels, pad);
|
|
1571
1578
|
const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
|
|
1572
1579
|
const coverage = new Uint8Array(width * height);
|
|
1573
1580
|
for (let y = 0; y < rendered.height; y++)
|
package/dist/metadata.d.ts
CHANGED
|
@@ -21,9 +21,15 @@ export interface Metadata {
|
|
|
21
21
|
description?: string;
|
|
22
22
|
/** The image's copyright info */
|
|
23
23
|
copyright?: string;
|
|
24
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* The image's creation time
|
|
26
|
+
* @defaultValue None (`null` leaves it out, too)
|
|
27
|
+
*/
|
|
25
28
|
creationTime?: string | number | Date | null;
|
|
26
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* The software used to create the image
|
|
31
|
+
* @defaultValue `'ImageScript'` (without a version), `null` leaves it out
|
|
32
|
+
*/
|
|
27
33
|
software?: string | null;
|
|
28
34
|
/** A disclaimer for the image */
|
|
29
35
|
disclaimer?: string;
|
package/dist/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module"}
|
|
1
|
+
{"type":"module","sideEffects":false}
|
package/dist/render/svg.js
CHANGED
|
@@ -21,7 +21,7 @@ import { fontFace, layOutText, parseFontFamilies, parseVariationSettings, pathLe
|
|
|
21
21
|
import { rasterizeGlyph } from "./text.js";
|
|
22
22
|
import { renderPaintGlyph } from "./colr.js";
|
|
23
23
|
import { decodeSync as decodePNG } from "../codecs/png.js";
|
|
24
|
-
import { MAX_PIXELS, LimitError
|
|
24
|
+
import { MAX_PIXELS, LimitError } from "../util/limits.js";
|
|
25
25
|
const UNSUPPORTED = new Set(['filter', 'pattern', 'marker', 'foreignObject', 'script', 'style', 'title', 'desc', 'metadata',
|
|
26
26
|
'defs', 'clipPath', 'mask', 'linearGradient', 'radialGradient', 'stop', 'symbol', 'font', 'font-face', 'animate', 'animateTransform', 'animateMotion', 'set']);
|
|
27
27
|
const INHERITED = new Set(['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-opacity', 'stroke-linecap', 'stroke-linejoin',
|
|
@@ -82,9 +82,11 @@ export function render(source, mode, size, images = new Map(), fonts = [], maxPi
|
|
|
82
82
|
outHeight = Math.max(1, outHeight);
|
|
83
83
|
if (!Number.isSafeInteger(outWidth) || !Number.isSafeInteger(outHeight))
|
|
84
84
|
throw new RangeError(`SVG output dimensions are too large: ${outWidth}x${outHeight}`);
|
|
85
|
-
|
|
86
|
-
|
|
85
|
+
if (!(outWidth * outHeight <= maxPixels))
|
|
86
|
+
throw new LimitError(`SVG too large to render: ${outWidth}x${outHeight} pixels exceed the limit of ${maxPixels} (the render options' maxPixels)`);
|
|
87
|
+
const previous = layerBudget, previousCrossings = crossingsLeft;
|
|
87
88
|
layerBudget = { left: maxLayerPixels, limit: maxLayerPixels };
|
|
89
|
+
crossingsLeft = MAX_CROSSINGS;
|
|
88
90
|
try {
|
|
89
91
|
const canvas = new Layer(outWidth, outHeight);
|
|
90
92
|
doc.renderRoot([outWidth / width, 0, 0, outHeight / height, 0, 0], canvas, 0);
|
|
@@ -92,6 +94,7 @@ export function render(source, mode, size, images = new Map(), fonts = [], maxPi
|
|
|
92
94
|
}
|
|
93
95
|
finally {
|
|
94
96
|
layerBudget = previous;
|
|
97
|
+
crossingsLeft = previousCrossings;
|
|
95
98
|
}
|
|
96
99
|
}
|
|
97
100
|
let layerBudget = null;
|
|
@@ -557,8 +560,21 @@ function validProperty(name, value) {
|
|
|
557
560
|
}
|
|
558
561
|
const MAX_INSTANCES = 100000;
|
|
559
562
|
const MAX_OCTAVES = 24;
|
|
563
|
+
const DASH_BATCH = 20000;
|
|
564
|
+
function take(iterator, n) {
|
|
565
|
+
const items = [];
|
|
566
|
+
while (items.length < n) {
|
|
567
|
+
const next = iterator.next();
|
|
568
|
+
if (next.done)
|
|
569
|
+
break;
|
|
570
|
+
items.push(next.value);
|
|
571
|
+
}
|
|
572
|
+
return items;
|
|
573
|
+
}
|
|
560
574
|
const MAX_NESTED = 2 ** 26, MIN_NESTED = 2 ** 16;
|
|
561
575
|
const MAX_DASHES = 1000000;
|
|
576
|
+
const MAX_CROSSINGS = 2 ** 27;
|
|
577
|
+
let crossingsLeft = Infinity;
|
|
562
578
|
const MAX_TILE = 4096 * 1024;
|
|
563
579
|
class Document {
|
|
564
580
|
budget = { instances: 0, nested: 0, nesting: 0 };
|
|
@@ -1380,16 +1396,51 @@ class Document {
|
|
|
1380
1396
|
const strokeWidth = parseLength(style['stroke-width'], ctx.viewport, 16, 'diagonal');
|
|
1381
1397
|
if (!stroke || !(strokeWidth > 0))
|
|
1382
1398
|
return;
|
|
1383
|
-
|
|
1399
|
+
const lines = subpaths;
|
|
1384
1400
|
const fontSize = parseNumber(style['font-size'], 16);
|
|
1385
1401
|
const dashes = parseDashArray(style['stroke-dasharray'], ctx.viewport, fontSize);
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1402
|
+
const miterLimit = Math.max(1, parseNumber(style['stroke-miterlimit'], 4));
|
|
1403
|
+
if (dashes) {
|
|
1404
|
+
const reach = strokeWidth / 2 * Math.max(miterLimit, Math.SQRT2) * Math.hypot(matrix[0], matrix[1], matrix[2], matrix[3]) + 1;
|
|
1405
|
+
const visible = (points) => {
|
|
1406
|
+
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
|
|
1407
|
+
for (let i = 0; i < points.length; i += 2) {
|
|
1408
|
+
const x = matrix[0] * points[i] + matrix[2] * points[i + 1] + matrix[4], y = matrix[1] * points[i] + matrix[3] * points[i + 1] + matrix[5];
|
|
1409
|
+
x0 = Math.min(x0, x);
|
|
1410
|
+
x1 = Math.max(x1, x);
|
|
1411
|
+
y0 = Math.min(y0, y);
|
|
1412
|
+
y1 = Math.max(y1, y);
|
|
1413
|
+
}
|
|
1414
|
+
return !(x1 + reach <= 0 || x0 - reach >= layer.width || y1 + reach <= 0 || y0 - reach >= layer.height);
|
|
1415
|
+
};
|
|
1416
|
+
const generated = dash(subpaths, dashes, parseLength(style['stroke-dashoffset'], ctx.viewport, fontSize, 'diagonal'), visible);
|
|
1417
|
+
let total = null;
|
|
1418
|
+
for (let batch = take(generated, DASH_BATCH); batch.length; batch = take(generated, DASH_BATCH)) {
|
|
1419
|
+
const coverage = this.strokeCoverage(batch, strokeWidth, miterLimit, tolerance, ctx);
|
|
1420
|
+
if (!coverage)
|
|
1421
|
+
continue;
|
|
1422
|
+
if (batch.length < DASH_BATCH && !total) {
|
|
1423
|
+
total = coverage;
|
|
1424
|
+
break;
|
|
1425
|
+
}
|
|
1426
|
+
total ??= { x0: 0, y0: 0, w: layer.width, h: layer.height, data: new Float32Array(layer.width * layer.height) };
|
|
1427
|
+
for (let y = 0; y < coverage.h; y++)
|
|
1428
|
+
for (let x = 0, o = y * coverage.w, t = (coverage.y0 + y) * total.w + coverage.x0; x < coverage.w; x++)
|
|
1429
|
+
total.data[t + x] = Math.min(1, total.data[t + x] + coverage.data[o + x]);
|
|
1430
|
+
}
|
|
1431
|
+
if (total)
|
|
1432
|
+
layer.fill(crisp(total, style), stroke);
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
const coverage = this.strokeCoverage(lines, strokeWidth, miterLimit, tolerance, ctx);
|
|
1390
1436
|
if (coverage)
|
|
1391
1437
|
layer.fill(crisp(coverage, style), stroke);
|
|
1392
1438
|
}
|
|
1439
|
+
strokeCoverage(lines, strokeWidth, miterLimit, tolerance, ctx) {
|
|
1440
|
+
const style = ctx.style;
|
|
1441
|
+
const polygons = strokePolygons(lines, strokeWidth / 2, style['stroke-linecap'], style['stroke-linejoin'], miterLimit, tolerance).map(points => transformPoints(points, ctx.matrix));
|
|
1442
|
+
return rasterize(polygons, false, ctx.layer.width, ctx.layer.height);
|
|
1443
|
+
}
|
|
1393
1444
|
renderMarkers(path, bbox, node, ctx) {
|
|
1394
1445
|
const style = ctx.style;
|
|
1395
1446
|
for (let p = node.parent; p; p = p.parent)
|
|
@@ -2772,6 +2823,20 @@ function rasterize(polygons, evenOdd, width, height) {
|
|
|
2772
2823
|
const n = points.length >> 1;
|
|
2773
2824
|
if (n < 2)
|
|
2774
2825
|
continue;
|
|
2826
|
+
let px0 = Infinity, py0 = Infinity, px1 = -Infinity, py1 = -Infinity;
|
|
2827
|
+
for (let i = 0; i < n; i++) {
|
|
2828
|
+
const x = points[i * 2], y = points[i * 2 + 1];
|
|
2829
|
+
if (x < px0)
|
|
2830
|
+
px0 = x;
|
|
2831
|
+
if (x > px1)
|
|
2832
|
+
px1 = x;
|
|
2833
|
+
if (y < py0)
|
|
2834
|
+
py0 = y;
|
|
2835
|
+
if (y > py1)
|
|
2836
|
+
py1 = y;
|
|
2837
|
+
}
|
|
2838
|
+
if (px1 <= 0 || px0 >= width || py1 <= 0 || py0 >= height)
|
|
2839
|
+
continue;
|
|
2775
2840
|
for (let i = 0; i < n; i++) {
|
|
2776
2841
|
const ax = points[i * 2], ay = points[i * 2 + 1];
|
|
2777
2842
|
const j = (i + 1) % n;
|
|
@@ -2816,7 +2881,6 @@ function rasterize(polygons, evenOdd, width, height) {
|
|
|
2816
2881
|
order[placed[startRow(e)]++] = e;
|
|
2817
2882
|
let numActive = 0;
|
|
2818
2883
|
const active = scratch.i32(4, numEdges), keys = scratch.f64(4, numEdges), firsts = scratch.i32(5, numEdges), lasts = scratch.i32(6, numEdges);
|
|
2819
|
-
const counts = new Int32Array(SAMPLES), starts = new Int32Array(SAMPLES), ends = new Int32Array(SAMPLES);
|
|
2820
2884
|
const span = (a, b) => {
|
|
2821
2885
|
a = Math.max(a, x0) - x0;
|
|
2822
2886
|
b = Math.min(b, x1) - x0;
|
|
@@ -2840,11 +2904,10 @@ function rasterize(polygons, evenOdd, width, height) {
|
|
|
2840
2904
|
if (bottoms[active[k]] > py)
|
|
2841
2905
|
active[kept++] = active[k];
|
|
2842
2906
|
numActive = kept;
|
|
2843
|
-
for (let k = rowStarts[py - y0]; k < rowStarts[py - y0 + 1]; k++)
|
|
2844
|
-
active[numActive++] = order[k];
|
|
2845
2907
|
const mid = py + 0.5;
|
|
2846
|
-
|
|
2847
|
-
|
|
2908
|
+
const keyOf = (e) => xs[e] + (Math.min(Math.max(mid, tops[e]), bottoms[e]) - tops[e]) * slopes[e];
|
|
2909
|
+
for (let k = 0; k < kept; k++) {
|
|
2910
|
+
const e = active[k], key = keyOf(e);
|
|
2848
2911
|
let j = k - 1;
|
|
2849
2912
|
for (; j >= 0 && keys[j] > key; j--) {
|
|
2850
2913
|
keys[j + 1] = keys[j];
|
|
@@ -2853,8 +2916,28 @@ function rasterize(polygons, evenOdd, width, height) {
|
|
|
2853
2916
|
keys[j + 1] = key;
|
|
2854
2917
|
active[j + 1] = e;
|
|
2855
2918
|
}
|
|
2856
|
-
|
|
2857
|
-
|
|
2919
|
+
const added = rowStarts[py - y0 + 1] - rowStarts[py - y0];
|
|
2920
|
+
if (added) {
|
|
2921
|
+
const first = rowStarts[py - y0];
|
|
2922
|
+
const newKeys = scratch.f64(6, added), ranks = scratch.i32(7, added).subarray(0, added);
|
|
2923
|
+
for (let n = 0; n < added; n++) {
|
|
2924
|
+
newKeys[n] = keyOf(order[first + n]);
|
|
2925
|
+
ranks[n] = n;
|
|
2926
|
+
}
|
|
2927
|
+
ranks.sort((a, b) => newKeys[a] - newKeys[b]);
|
|
2928
|
+
let i = kept - 1, n = added - 1, out = kept + added - 1;
|
|
2929
|
+
while (n >= 0) {
|
|
2930
|
+
if (i >= 0 && keys[i] > newKeys[ranks[n]]) {
|
|
2931
|
+
keys[out] = keys[i];
|
|
2932
|
+
active[out--] = active[i--];
|
|
2933
|
+
}
|
|
2934
|
+
else {
|
|
2935
|
+
keys[out] = newKeys[ranks[n]];
|
|
2936
|
+
active[out--] = order[first + ranks[n--]];
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
numActive += added;
|
|
2940
|
+
}
|
|
2858
2941
|
for (let k = 0; k < numActive; k++) {
|
|
2859
2942
|
const e = active[k], top = tops[e], bottom = bottoms[e];
|
|
2860
2943
|
let s0 = Math.max(0, Math.ceil((top - py) * SAMPLES - 0.5)), s1 = Math.min(SAMPLES - 1, Math.ceil((bottom - py) * SAMPLES - 0.5) - 1);
|
|
@@ -2868,34 +2951,26 @@ function rasterize(polygons, evenOdd, width, height) {
|
|
|
2868
2951
|
s1--;
|
|
2869
2952
|
firsts[k] = s0;
|
|
2870
2953
|
lasts[k] = Math.max(-1, s1);
|
|
2871
|
-
for (let s = s0; s <= s1; s++)
|
|
2872
|
-
counts[s]++;
|
|
2873
|
-
if (s1 >= s0)
|
|
2874
|
-
total += s1 - s0 + 1;
|
|
2875
|
-
}
|
|
2876
|
-
const crossings = scratch.f64(5, 2 * total);
|
|
2877
|
-
for (let s = 0, at = 0; s < SAMPLES; s++) {
|
|
2878
|
-
starts[s] = at;
|
|
2879
|
-
at += 2 * counts[s];
|
|
2880
|
-
}
|
|
2881
|
-
for (let s = 0; s < SAMPLES; s++)
|
|
2882
|
-
ends[s] = starts[s];
|
|
2883
|
-
for (let k = 0; k < numActive; k++) {
|
|
2884
|
-
const e = active[k];
|
|
2885
|
-
for (let s = firsts[k]; s <= lasts[k]; s++) {
|
|
2886
|
-
const sy = py + OFFSETS[s];
|
|
2887
|
-
crossings[ends[s]++] = xs[e] + (sy - tops[e]) * slopes[e];
|
|
2888
|
-
crossings[ends[s]++] = dirs[e];
|
|
2889
|
-
}
|
|
2890
2954
|
}
|
|
2955
|
+
const crossings = scratch.f64(5, 2 * numActive);
|
|
2891
2956
|
for (let s = 0; s < SAMPLES; s++) {
|
|
2892
|
-
const
|
|
2893
|
-
|
|
2957
|
+
const sy = py + OFFSETS[s];
|
|
2958
|
+
let end = 0;
|
|
2959
|
+
for (let k = 0; k < numActive; k++) {
|
|
2960
|
+
if (s < firsts[k] || s > lasts[k])
|
|
2961
|
+
continue;
|
|
2962
|
+
const e = active[k];
|
|
2963
|
+
crossings[end++] = xs[e] + (sy - tops[e]) * slopes[e];
|
|
2964
|
+
crossings[end++] = dirs[e];
|
|
2965
|
+
}
|
|
2966
|
+
if (end < 4)
|
|
2894
2967
|
continue;
|
|
2895
|
-
|
|
2968
|
+
if ((crossingsLeft -= end >> 1) < 0)
|
|
2969
|
+
throw new LimitError(`SVG too complex: its shapes' edges cross the rows of the image more than ${MAX_CROSSINGS} times (many large overlapping strokes or shapes)`);
|
|
2970
|
+
for (let i = 2; i < end; i += 2) {
|
|
2896
2971
|
const x = crossings[i], dir = crossings[i + 1];
|
|
2897
2972
|
let j = i - 2;
|
|
2898
|
-
for (; j >=
|
|
2973
|
+
for (; j >= 0 && crossings[j] > x; j -= 2) {
|
|
2899
2974
|
crossings[j + 2] = crossings[j];
|
|
2900
2975
|
crossings[j + 3] = crossings[j + 1];
|
|
2901
2976
|
}
|
|
@@ -2903,7 +2978,7 @@ function rasterize(polygons, evenOdd, width, height) {
|
|
|
2903
2978
|
crossings[j + 3] = dir;
|
|
2904
2979
|
}
|
|
2905
2980
|
let winding = 0;
|
|
2906
|
-
for (let i =
|
|
2981
|
+
for (let i = 0; i < end - 2; i += 2) {
|
|
2907
2982
|
winding += crossings[i + 1];
|
|
2908
2983
|
if (evenOdd ? winding & 1 : winding !== 0)
|
|
2909
2984
|
span(crossings[i], crossings[i + 2]);
|
|
@@ -3261,17 +3336,18 @@ function transformPoints(points, m) {
|
|
|
3261
3336
|
}
|
|
3262
3337
|
return out;
|
|
3263
3338
|
}
|
|
3264
|
-
function dash(subpaths, pattern, offset) {
|
|
3339
|
+
function* dash(subpaths, pattern, offset, visible = () => true) {
|
|
3265
3340
|
const total = pattern.reduce((a, b) => a + b, 0);
|
|
3266
|
-
const result = [];
|
|
3267
3341
|
let length = 0;
|
|
3268
3342
|
for (const { points, closed } of subpaths) {
|
|
3269
3343
|
const pts = closed ? [...points, points[0], points[1]] : points;
|
|
3270
3344
|
for (let i = 0; i + 3 < pts.length; i += 2)
|
|
3271
3345
|
length += Math.hypot(pts[i + 2] - pts[i], pts[i + 3] - pts[i + 1]);
|
|
3272
3346
|
}
|
|
3273
|
-
if (!(length / total * pattern.length <= MAX_DASHES))
|
|
3274
|
-
|
|
3347
|
+
if (!(length / total * pattern.length <= MAX_DASHES)) {
|
|
3348
|
+
yield* subpaths;
|
|
3349
|
+
return;
|
|
3350
|
+
}
|
|
3275
3351
|
for (const { points, closed } of subpaths) {
|
|
3276
3352
|
const pts = closed ? [...points, points[0], points[1]] : points;
|
|
3277
3353
|
let index = 0;
|
|
@@ -3300,7 +3376,8 @@ function dash(subpaths, pattern, offset) {
|
|
|
3300
3376
|
if (on) {
|
|
3301
3377
|
if (current) {
|
|
3302
3378
|
current.push(mx, my);
|
|
3303
|
-
|
|
3379
|
+
if (visible(current))
|
|
3380
|
+
yield { points: current, closed: false, direction: [(bx - ax) / length, (by - ay) / length] };
|
|
3304
3381
|
}
|
|
3305
3382
|
current = null;
|
|
3306
3383
|
}
|
|
@@ -3315,10 +3392,9 @@ function dash(subpaths, pattern, offset) {
|
|
|
3315
3392
|
}
|
|
3316
3393
|
}
|
|
3317
3394
|
}
|
|
3318
|
-
if (on && current && current.length >= 4)
|
|
3319
|
-
|
|
3395
|
+
if (on && current && current.length >= 4 && visible(current))
|
|
3396
|
+
yield { points: current, closed: false };
|
|
3320
3397
|
}
|
|
3321
|
-
return result;
|
|
3322
3398
|
}
|
|
3323
3399
|
function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
|
|
3324
3400
|
const polygons = [];
|
|
@@ -3381,11 +3457,19 @@ function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
|
|
|
3381
3457
|
const dot = prev[0] * next[0] + prev[1] * next[1];
|
|
3382
3458
|
if (Math.abs(cross) < 1e-9 && dot > 0)
|
|
3383
3459
|
continue;
|
|
3460
|
+
const side = cross > 0 ? -1 : 1;
|
|
3384
3461
|
if (join === 'round') {
|
|
3385
|
-
|
|
3462
|
+
const turn = Math.acos(Math.max(-1, Math.min(1, dot)));
|
|
3463
|
+
const steps = Math.max(1, Math.ceil(turn / (2 * Math.PI / circleSegments)));
|
|
3464
|
+
const start = Math.atan2(side * prev[0], side * -prev[1]), sweep = side === -1 ? turn : -turn;
|
|
3465
|
+
const wedge = [vx, vy];
|
|
3466
|
+
for (let k = 0; k <= steps; k++) {
|
|
3467
|
+
const a = start + sweep * k / steps;
|
|
3468
|
+
wedge.push(vx + Math.cos(a) * halfWidth, vy + Math.sin(a) * halfWidth);
|
|
3469
|
+
}
|
|
3470
|
+
add(wedge);
|
|
3386
3471
|
continue;
|
|
3387
3472
|
}
|
|
3388
|
-
const side = cross > 0 ? -1 : 1;
|
|
3389
3473
|
const ax = vx + side * -prev[1] * halfWidth, ay = vy + side * prev[0] * halfWidth;
|
|
3390
3474
|
const bx = vx + side * -next[1] * halfWidth, by = vy + side * next[0] * halfWidth;
|
|
3391
3475
|
const theta = Math.acos(Math.max(-1, Math.min(1, dot)));
|
package/dist/text-layout.d.ts
CHANGED
|
@@ -8,24 +8,30 @@ export type VerticalAlign = 'top' | 'middle' | 'bottom';
|
|
|
8
8
|
export interface TextLayoutOptions {
|
|
9
9
|
/**
|
|
10
10
|
* The image's width in pixels: lines are wrapped to fit into it (inside the outline, see
|
|
11
|
-
* {@link TextStyleOptions.strokeWidth}) and placed in it by `horizontalAlign
|
|
11
|
+
* {@link TextStyleOptions.strokeWidth}) and placed in it by `horizontalAlign`
|
|
12
|
+
* @defaultValue The widest line's width
|
|
12
13
|
*/
|
|
13
14
|
width?: number;
|
|
14
15
|
/**
|
|
15
16
|
* The image's height in pixels: lines that don't fit are left out, and the text is placed in it by `verticalAlign`.
|
|
16
|
-
*
|
|
17
|
+
* @defaultValue The height of the lines
|
|
17
18
|
*/
|
|
18
19
|
height?: number;
|
|
19
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Whether to wrap between words or at any character
|
|
22
|
+
* @defaultValue `'word'`
|
|
23
|
+
*/
|
|
20
24
|
wrapStyle?: WrapStyle;
|
|
21
25
|
/**
|
|
22
26
|
* Where the lines are placed horizontally: `'left'`, `'center'` or `'right'` in the `width`, or (without one)
|
|
23
|
-
* relative to the widest line
|
|
27
|
+
* relative to the widest line
|
|
28
|
+
* @defaultValue `'left'`
|
|
24
29
|
*/
|
|
25
30
|
horizontalAlign?: HorizontalAlign;
|
|
26
31
|
/**
|
|
27
32
|
* Where the text is placed vertically in the `height`: `'top'`, `'middle'` or `'bottom'`. When not all lines fit,
|
|
28
|
-
* these keep the first, the middle or the last lines. Without a `height`, it has no effect
|
|
33
|
+
* these keep the first, the middle or the last lines. Without a `height`, it has no effect
|
|
34
|
+
* @defaultValue `'top'`
|
|
29
35
|
*/
|
|
30
36
|
verticalAlign?: VerticalAlign;
|
|
31
37
|
}
|
package/dist/util/limits.d.ts
CHANGED
|
@@ -13,6 +13,11 @@ export declare const MAX_PIXELS: number;
|
|
|
13
13
|
* @param count the number of such images (frames)
|
|
14
14
|
*/
|
|
15
15
|
export declare function checkPixels(width: number, height: number, limit: number, count?: number): void;
|
|
16
|
+
/**
|
|
17
|
+
* Throws a {@link LimitError} naming the operation if an image it makes would have more pixels than an image can
|
|
18
|
+
* (the default `maxPixels` of the decoders): a shadow or outline of a huge size or offset would only fail allocating
|
|
19
|
+
*/
|
|
20
|
+
export declare function checkGrowth(width: number, height: number, what: string): void;
|
|
16
21
|
/** The most bytes of raw samples per pixel of the limit (4 samples of 16 bits) */
|
|
17
22
|
export declare const MAX_BYTES_PER_PIXEL = 8;
|
|
18
23
|
/**
|
package/dist/util/limits.js
CHANGED
|
@@ -6,6 +6,10 @@ export function checkPixels(width, height, limit, count = 1) {
|
|
|
6
6
|
if (!(width * height * count <= limit))
|
|
7
7
|
throw new LimitError(`Image too large: ${count > 1 ? `${count} frames of ` : ''}${width}x${height} pixels exceed the limit of ${limit} (the decode options' maxPixels)`);
|
|
8
8
|
}
|
|
9
|
+
export function checkGrowth(width, height, what) {
|
|
10
|
+
if (!(width * height <= MAX_PIXELS))
|
|
11
|
+
throw new LimitError(`${what} would make the image ${width}x${height} pixels, more than the limit of ${MAX_PIXELS}`);
|
|
12
|
+
}
|
|
9
13
|
export const MAX_BYTES_PER_PIXEL = 8;
|
|
10
14
|
export function checkBytes(bytes, limit) {
|
|
11
15
|
if (!(bytes <= limit * MAX_BYTES_PER_PIXEL))
|