pixi-silk 0.1.0

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/dist/app.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { Application, ApplicationOptions } from "pixi.js";
2
+ //#region src/app.d.ts
3
+ /** Options of {@link createSilkApp}: Pixi application options plus the element to fill, DPR limits and touch behaviour. */
4
+ export interface SilkAppOptions extends Partial<ApplicationOptions> {
5
+ /** Element the canvas fills (it must have a size). */
6
+ parent: HTMLElement;
7
+ /** Upper bound for the resolution (DPR). Default 3. */
8
+ maxResolution?: number;
9
+ /** Force a resolution instead of following devicePixelRatio. */
10
+ fixedResolution?: number;
11
+ /** Called after every size / resolution change with the size in CSS pixels. */
12
+ onResize?: (width: number, height: number, resolution: number) => void;
13
+ /**
14
+ * Pixi filters render at resolution 1 by default, which blurs everything behind a filter
15
+ * on retina screens. When true (default) new filters inherit the renderer resolution.
16
+ */
17
+ inheritFilterResolution?: boolean;
18
+ /**
19
+ * CSS touch-action for the canvas. Pixi sets `none`, which blocks page scrolling on touch
20
+ * screens. The default `pan-y pinch-zoom` lets pages scroll while taps and hovers still reach
21
+ * Pixi. Use `none` for canvases that handle drags themselves.
22
+ */
23
+ touchAction?: string;
24
+ }
25
+ /** What {@link createSilkApp} returns: the Pixi application, its CSS size and resolution, and helpers to change or destroy it. */
26
+ export interface SilkApp {
27
+ /** The Pixi application. */
28
+ app: Application;
29
+ /** Current width in CSS pixels. */
30
+ readonly width: number;
31
+ /** Current height in CSS pixels. */
32
+ readonly height: number;
33
+ /** Current renderer resolution (device pixels per CSS pixel). */
34
+ readonly resolution: number;
35
+ /** Forces a resolution, for example to compare 1x and 2x. `null` returns to devicePixelRatio. */
36
+ setResolution(resolution: number | null): void;
37
+ /** Stops observers, destroys the stage and renderer and removes the canvas. Safe with several apps on a page. */
38
+ destroy(): void;
39
+ }
40
+ /**
41
+ * Creates a Pixi application tuned for smooth vector output:
42
+ *
43
+ * - WebGL2 and no MSAA (analytic AA does the job, MSAA would only cost bandwidth),
44
+ * - backing store sized from `devicePixelContentBoxSize`, so every canvas pixel maps to
45
+ * exactly one device pixel even at fractional DPRs (1.25, 1.5, 2.625 ...) - no resampling blur,
46
+ * - follows DPR changes (moving the window between displays, browser zoom),
47
+ * - unrounded coordinates for sub-pixel smooth motion,
48
+ * - filters that render at the screen resolution instead of 1x.
49
+ */
50
+ export declare function createSilkApp(options: SilkAppOptions): Promise<SilkApp>;
51
+ //#endregion
package/dist/app.js ADDED
@@ -0,0 +1,102 @@
1
+ import { Application, Filter } from "pixi.js";
2
+ //#region src/app.ts
3
+ /**
4
+ * Creates a Pixi application tuned for smooth vector output:
5
+ *
6
+ * - WebGL2 and no MSAA (analytic AA does the job, MSAA would only cost bandwidth),
7
+ * - backing store sized from `devicePixelContentBoxSize`, so every canvas pixel maps to
8
+ * exactly one device pixel even at fractional DPRs (1.25, 1.5, 2.625 ...) - no resampling blur,
9
+ * - follows DPR changes (moving the window between displays, browser zoom),
10
+ * - unrounded coordinates for sub-pixel smooth motion,
11
+ * - filters that render at the screen resolution instead of 1x.
12
+ */
13
+ async function createSilkApp(options) {
14
+ const { parent, maxResolution = 3, fixedResolution, onResize, inheritFilterResolution = true, touchAction = "pan-y pinch-zoom", ...rest } = options;
15
+ if (inheritFilterResolution) Filter.defaultOptions.resolution = "inherit";
16
+ const app = new Application();
17
+ let forced = fixedResolution ?? null;
18
+ const dpr = () => Math.min(forced ?? window.devicePixelRatio ?? 1, forced ? 16 : maxResolution);
19
+ await app.init({
20
+ preference: "webgl",
21
+ antialias: false,
22
+ autoDensity: false,
23
+ roundPixels: false,
24
+ resolution: dpr(),
25
+ width: Math.max(1, parent.clientWidth),
26
+ height: Math.max(1, parent.clientHeight),
27
+ powerPreference: "high-performance",
28
+ ...rest
29
+ });
30
+ const canvas = app.canvas;
31
+ canvas.style.touchAction = touchAction;
32
+ canvas.style.display = "block";
33
+ canvas.style.width = "100%";
34
+ canvas.style.height = "100%";
35
+ parent.appendChild(canvas);
36
+ let devW = 0;
37
+ let devH = 0;
38
+ let lastDpr = 0;
39
+ const apply = () => {
40
+ const res = dpr();
41
+ const nativeDpr = window.devicePixelRatio || 1;
42
+ if (!devW || !devH) return;
43
+ const scale = res / nativeDpr;
44
+ const pw = Math.max(1, Math.round(devW * scale));
45
+ const ph = Math.max(1, Math.round(devH * scale));
46
+ app.renderer.resize(pw / res, ph / res, res);
47
+ lastDpr = res;
48
+ onResize?.(pw / res, ph / res, res);
49
+ };
50
+ const ro = new ResizeObserver((entries) => {
51
+ const entry = entries[entries.length - 1];
52
+ const ratio = window.devicePixelRatio || 1;
53
+ const cb = entry.contentBoxSize[0];
54
+ const box = entry.devicePixelContentBoxSize?.[0];
55
+ const exact = box && Math.abs(box.inlineSize - cb.inlineSize * ratio) <= 2 && Math.abs(box.blockSize - cb.blockSize * ratio) <= 2;
56
+ devW = exact ? box.inlineSize : Math.round(cb.inlineSize * ratio);
57
+ devH = exact ? box.blockSize : Math.round(cb.blockSize * ratio);
58
+ apply();
59
+ });
60
+ try {
61
+ ro.observe(canvas, { box: "device-pixel-content-box" });
62
+ } catch {
63
+ ro.observe(canvas);
64
+ }
65
+ let mq = null;
66
+ const watchDpr = () => {
67
+ mq?.removeEventListener("change", onDprChange);
68
+ mq = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
69
+ mq.addEventListener("change", onDprChange);
70
+ };
71
+ const onDprChange = () => {
72
+ const rect = canvas.getBoundingClientRect();
73
+ devW = Math.round(rect.width * window.devicePixelRatio);
74
+ devH = Math.round(rect.height * window.devicePixelRatio);
75
+ watchDpr();
76
+ apply();
77
+ };
78
+ watchDpr();
79
+ return {
80
+ app,
81
+ get width() {
82
+ return app.screen.width;
83
+ },
84
+ get height() {
85
+ return app.screen.height;
86
+ },
87
+ get resolution() {
88
+ return lastDpr || dpr();
89
+ },
90
+ setResolution(resolution) {
91
+ forced = resolution;
92
+ apply();
93
+ },
94
+ destroy() {
95
+ ro.disconnect();
96
+ mq?.removeEventListener("change", onDprChange);
97
+ app.destroy({ removeView: true }, { children: true });
98
+ }
99
+ };
100
+ }
101
+ //#endregion
102
+ export { createSilkApp };
@@ -0,0 +1,27 @@
1
+ import { Gradient } from "./gradient.js";
2
+ import { BufferImageSource } from "pixi.js";
3
+ //#region src/atlas.d.ts
4
+ /**
5
+ * All gradient ramps live in one RGBA16F texture (one ramp per row), shared by every
6
+ * SilkGraphics. Half floats keep ~11 bits per channel so dark and low-alpha ramps
7
+ * don't get quantised before the shader dithers them to the 8-bit framebuffer.
8
+ */
9
+ export declare class GradientAtlas {
10
+ private static _shared;
11
+ /** The atlas every SilkGraphics uses. */
12
+ static get shared(): GradientAtlas;
13
+ /** The half-float texture that holds the ramps. */
14
+ readonly source: BufferImageSource;
15
+ private readonly _data;
16
+ private readonly _rows;
17
+ private _nextRow;
18
+ private readonly _scratch;
19
+ constructor();
20
+ /** Returns the atlas row for a gradient ramp, baking it on first use. */
21
+ acquire(gradient: Gradient): number;
22
+ /** Drops one reference to a ramp. When the atlas is full, rows nobody uses are reused. */
23
+ release(key: string): void;
24
+ private _allocate;
25
+ private _write;
26
+ }
27
+ //#endregion
package/dist/atlas.js ADDED
@@ -0,0 +1,73 @@
1
+ import { toHalf } from "./color.js";
2
+ import { BufferImageSource } from "pixi.js";
3
+ //#region src/atlas.ts
4
+ /**
5
+ * All gradient ramps live in one RGBA16F texture (one ramp per row), shared by every
6
+ * SilkGraphics. Half floats keep ~11 bits per channel so dark and low-alpha ramps
7
+ * don't get quantised before the shader dithers them to the 8-bit framebuffer.
8
+ */
9
+ var GradientAtlas = class GradientAtlas {
10
+ static _shared = null;
11
+ /** The atlas every SilkGraphics uses. */
12
+ static get shared() {
13
+ GradientAtlas._shared ??= new GradientAtlas();
14
+ return GradientAtlas._shared;
15
+ }
16
+ /** The half-float texture that holds the ramps. */
17
+ source;
18
+ _data;
19
+ _rows = /* @__PURE__ */ new Map();
20
+ _nextRow = 0;
21
+ _scratch = /* @__PURE__ */ new Float32Array(1024);
22
+ constructor() {
23
+ this._data = /* @__PURE__ */ new Uint16Array(262144);
24
+ this.source = new BufferImageSource({
25
+ resource: this._data,
26
+ width: 256,
27
+ height: 256,
28
+ format: "rgba16float",
29
+ alphaMode: "premultiplied-alpha",
30
+ scaleMode: "linear",
31
+ addressMode: "clamp-to-edge",
32
+ autoGenerateMipmaps: false,
33
+ label: "silk-gradient-atlas"
34
+ });
35
+ }
36
+ /** Returns the atlas row for a gradient ramp, baking it on first use. */
37
+ acquire(gradient) {
38
+ let entry = this._rows.get(gradient.key);
39
+ if (!entry) {
40
+ entry = {
41
+ row: this._allocate(),
42
+ refs: 0
43
+ };
44
+ this._rows.set(gradient.key, entry);
45
+ this._write(gradient, entry.row);
46
+ }
47
+ entry.refs++;
48
+ return entry.row;
49
+ }
50
+ /** Drops one reference to a ramp. When the atlas is full, rows nobody uses are reused. */
51
+ release(key) {
52
+ const entry = this._rows.get(key);
53
+ if (entry && entry.refs > 0) entry.refs--;
54
+ }
55
+ _allocate() {
56
+ if (this._nextRow < 256) return this._nextRow++;
57
+ for (const [key, entry] of this._rows) if (entry.refs === 0) {
58
+ this._rows.delete(key);
59
+ return entry.row;
60
+ }
61
+ console.warn(`[pixi-silk] more than 256 gradients in use; reusing row 0`);
62
+ return 0;
63
+ }
64
+ _write(gradient, row) {
65
+ const tmp = this._scratch;
66
+ gradient.bake(tmp);
67
+ const base = row * 256 * 4;
68
+ for (let i = 0; i < tmp.length; i++) this._data[base + i] = toHalf(tmp[i]);
69
+ this.source.update();
70
+ }
71
+ };
72
+ //#endregion
73
+ export { GradientAtlas };
@@ -0,0 +1,13 @@
1
+ import { ColorSource } from "pixi.js";
2
+ //#region src/color.d.ts
3
+ /** Straight (non-premultiplied) sRGB colour with alpha, all channels 0..1, as returned by {@link parseColor}. */
4
+ export type RGBA = [number, number, number, number];
5
+ /** Any Pixi `ColorSource` as straight sRGB `[r, g, b, a]` (0..1), with `alpha` multiplied in. Memoised. */
6
+ export declare function parseColor(value: ColorSource, alpha?: number): RGBA;
7
+ /** Converts linear-light sRGB to OKLab (Björn Ottosson's perceptual colour space), used to interpolate gradients evenly. */
8
+ export declare function linearToOklab(r: number, g: number, b: number): [number, number, number];
9
+ /** Converts OKLab back to linear-light sRGB. Out-of-gamut colours fall outside 0..1, so callers clamp. */
10
+ export declare function oklabToLinear(L: number, a: number, b: number): [number, number, number];
11
+ /** Colour space gradients are interpolated in: perceptual OKLab (default), linear light, or plain sRGB. */
12
+ export type ColorSpace = "oklab" | "srgb" | "linear";
13
+ //#endregion
package/dist/color.js ADDED
@@ -0,0 +1,106 @@
1
+ import { Color } from "pixi.js";
2
+ //#region src/color.ts
3
+ let scratch;
4
+ const cache = /* @__PURE__ */ new Map();
5
+ /** Any Pixi `ColorSource` as straight sRGB `[r, g, b, a]` (0..1), with `alpha` multiplied in. Memoised. */
6
+ function parseColor(value, alpha = 1) {
7
+ const cacheable = typeof value === "number" || typeof value === "string";
8
+ let base = cacheable ? cache.get(value) : void 0;
9
+ if (!base) {
10
+ scratch ??= new Color();
11
+ const [r, g, b, a] = scratch.setValue(value).toArray();
12
+ base = [
13
+ r,
14
+ g,
15
+ b,
16
+ a ?? 1
17
+ ];
18
+ if (cacheable) {
19
+ if (cache.size > 1024) cache.clear();
20
+ cache.set(value, base);
21
+ }
22
+ }
23
+ return [
24
+ base[0],
25
+ base[1],
26
+ base[2],
27
+ base[3] * alpha
28
+ ];
29
+ }
30
+ const srgbToLinear = (c) => c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
31
+ const linearToSrgb = (c) => c <= .0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - .055;
32
+ /** Converts linear-light sRGB to OKLab (Björn Ottosson's perceptual colour space), used to interpolate gradients evenly. */
33
+ function linearToOklab(r, g, b) {
34
+ const l = Math.cbrt(.4122214708 * r + .5363325363 * g + .0514459929 * b);
35
+ const m = Math.cbrt(.2119034982 * r + .6806995451 * g + .1073969566 * b);
36
+ const s = Math.cbrt(.0883024619 * r + .2817188376 * g + .6299787005 * b);
37
+ return [
38
+ .2104542553 * l + .793617785 * m - .0040720468 * s,
39
+ 1.9779984951 * l - 2.428592205 * m + .4505937099 * s,
40
+ .0259040371 * l + .7827717662 * m - .808675766 * s
41
+ ];
42
+ }
43
+ /** Converts OKLab back to linear-light sRGB. Out-of-gamut colours fall outside 0..1, so callers clamp. */
44
+ function oklabToLinear(L, a, b) {
45
+ const l = L + .3963377774 * a + .2158037573 * b;
46
+ const m = L - .1055613458 * a - .0638541728 * b;
47
+ const s = L - .0894841775 * a - 1.291485548 * b;
48
+ const l3 = l * l * l;
49
+ const m3 = m * m * m;
50
+ const s3 = s * s * s;
51
+ return [
52
+ 4.0767416621 * l3 - 3.3077115913 * m3 + .2309699292 * s3,
53
+ -1.2684380046 * l3 + 2.6097574011 * m3 - .3413193965 * s3,
54
+ -.0041960863 * l3 - .7034186147 * m3 + 1.707614701 * s3
55
+ ];
56
+ }
57
+ /** sRGB (straight) -> working space coordinates. */
58
+ function toSpace(rgb, space) {
59
+ if (space === "srgb") return [
60
+ rgb[0],
61
+ rgb[1],
62
+ rgb[2]
63
+ ];
64
+ const lr = srgbToLinear(rgb[0]);
65
+ const lg = srgbToLinear(rgb[1]);
66
+ const lb = srgbToLinear(rgb[2]);
67
+ if (space === "linear") return [
68
+ lr,
69
+ lg,
70
+ lb
71
+ ];
72
+ return linearToOklab(lr, lg, lb);
73
+ }
74
+ /** Working space coordinates -> sRGB (straight, clamped to gamut). */
75
+ function fromSpace(c, space) {
76
+ const clamp = (v) => v < 0 ? 0 : v > 1 ? 1 : v;
77
+ if (space === "srgb") return [
78
+ clamp(c[0]),
79
+ clamp(c[1]),
80
+ clamp(c[2])
81
+ ];
82
+ const lin = space === "linear" ? c : oklabToLinear(c[0], c[1], c[2]);
83
+ return [
84
+ clamp(linearToSrgb(clamp(lin[0]))),
85
+ clamp(linearToSrgb(clamp(lin[1]))),
86
+ clamp(linearToSrgb(clamp(lin[2])))
87
+ ];
88
+ }
89
+ const f32 = /* @__PURE__ */ new Float32Array(1);
90
+ const u32 = new Uint32Array(f32.buffer);
91
+ /** Float -> IEEE 754 half float bits (round to nearest). */
92
+ function toHalf(value) {
93
+ f32[0] = value;
94
+ const x = u32[0];
95
+ const sign = x >>> 16 & 32768;
96
+ const exp = (x >>> 23 & 255) - 112;
97
+ const mant = x & 8388607;
98
+ if (exp <= 0) {
99
+ if (exp < -10) return sign;
100
+ return sign | ((mant | 8388608) >>> 1 - exp) + 4096 >>> 13;
101
+ }
102
+ if (exp >= 31) return sign | 31744;
103
+ return sign | (exp << 10) + (mant + 4096 >>> 13);
104
+ }
105
+ //#endregion
106
+ export { fromSpace, linearToOklab, linearToSrgb, oklabToLinear, parseColor, srgbToLinear, toHalf, toSpace };
@@ -0,0 +1,62 @@
1
+ //#region src/constants.ts
2
+ /** Attribute names in instance-buffer order (each is a vec4). */
3
+ const INSTANCE_ATTRIBUTES = [
4
+ "aBounds",
5
+ "aShape0",
6
+ "aShape1",
7
+ "aShape2",
8
+ "aMeta",
9
+ "aFill",
10
+ "aStroke",
11
+ "aGrad",
12
+ "aPaint",
13
+ "aDash"
14
+ ];
15
+ /** Primitive ids, one per branch of the fragment shader. */
16
+ const Prim = {
17
+ Rect: 0,
18
+ Ellipse: 1,
19
+ Arc: 2,
20
+ Sector: 3,
21
+ Segment: 4,
22
+ Area: 5,
23
+ Heart: 6,
24
+ Star: 7,
25
+ Triangle: 8
26
+ };
27
+ /** Bit flags in `aMeta.y`. */
28
+ const Flag = {
29
+ Fill: 1,
30
+ Stroke: 2,
31
+ Dither: 4,
32
+ Dash: 8,
33
+ Prev: 16,
34
+ Next: 32,
35
+ EdgeLeft: 64,
36
+ EdgeRight: 128,
37
+ GradStroke: 4096,
38
+ Closed: 8192
39
+ };
40
+ /** Line cap ids (two bits per end, see CAP0_SHIFT / CAP1_SHIFT). */
41
+ const Cap = {
42
+ Butt: 0,
43
+ Round: 1,
44
+ Square: 2
45
+ };
46
+ /** Gradient ids in `aPaint.x`. */
47
+ const GradKind = {
48
+ None: 0,
49
+ Linear: 1,
50
+ Radial: 2,
51
+ Conic: 3,
52
+ Path: 4
53
+ };
54
+ /** Gradient extend-mode ids in `aPaint.z`. */
55
+ const Extend = {
56
+ Pad: 0,
57
+ Repeat: 1,
58
+ Reflect: 2
59
+ };
60
+ const TAU = Math.PI * 2;
61
+ //#endregion
62
+ export { Cap, Extend, Flag, GradKind, INSTANCE_ATTRIBUTES, Prim, TAU };
@@ -0,0 +1,15 @@
1
+ import { PointData } from "pixi.js";
2
+ //#region src/curves.d.ts
3
+ /** Points as a flat `[x0, y0, x1, y1, ...]` array, a typed array, or an array of `{ x, y }` objects. */
4
+ export type PointsInput = number[] | Float32Array | Float64Array | PointData[];
5
+ /** Normalises `[x0, y0, x1, y1, ...]` or `[{x, y}, ...]` into a flat number array. */
6
+ export declare function toFlat(points: PointsInput): number[];
7
+ /**
8
+ * Monotone cubic interpolation in x (Steffen's method, same family as d3's monotoneX).
9
+ * Never overshoots the data: peaks stay at the data points, flat runs stay flat.
10
+ * `step` is the target spacing of the output samples in local units.
11
+ */
12
+ export declare function monotoneX(flat: number[], step?: number): number[];
13
+ /** Centripetal Catmull-Rom spline through the points (no cusps or self-loops). */
14
+ export declare function catmullRom(flat: number[], closed?: boolean, step?: number, alpha?: number): number[];
15
+ //#endregion
package/dist/curves.js ADDED
@@ -0,0 +1,117 @@
1
+ //#region src/curves.ts
2
+ /** Normalises `[x0, y0, x1, y1, ...]` or `[{x, y}, ...]` into a flat number array. */
3
+ function toFlat(points) {
4
+ if (points.length === 0) return [];
5
+ if (typeof points[0] === "number") return Array.from(points);
6
+ const out = [];
7
+ for (const p of points) out.push(p.x, p.y);
8
+ return out;
9
+ }
10
+ /**
11
+ * Monotone cubic interpolation in x (Steffen's method, same family as d3's monotoneX).
12
+ * Never overshoots the data: peaks stay at the data points, flat runs stay flat.
13
+ * `step` is the target spacing of the output samples in local units.
14
+ */
15
+ function monotoneX(flat, step = 2) {
16
+ const n = flat.length / 2;
17
+ if (n < 3) return flat.slice();
18
+ const x = (i) => flat[i * 2];
19
+ const y = (i) => flat[i * 2 + 1];
20
+ const tangents = new Array(n).fill(0);
21
+ const slope = (i) => {
22
+ const h = x(i + 1) - x(i);
23
+ return h !== 0 ? (y(i + 1) - y(i)) / h : 0;
24
+ };
25
+ for (let i = 1; i < n - 1; i++) {
26
+ const h0 = x(i) - x(i - 1);
27
+ const h1 = x(i + 1) - x(i);
28
+ const s0 = slope(i - 1);
29
+ const s1 = slope(i);
30
+ const p = (s0 * h1 + s1 * h0) / (h0 + h1 || 1);
31
+ tangents[i] = (Math.sign(s0) + Math.sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), .5 * Math.abs(p)) || 0;
32
+ }
33
+ const endTangent = (h, s, t) => h ? (3 * s - t) / 2 : t;
34
+ tangents[0] = endTangent(x(1) - x(0), slope(0), tangents[1]);
35
+ tangents[n - 1] = endTangent(x(n - 1) - x(n - 2), slope(n - 2), tangents[n - 2]);
36
+ const out = [x(0), y(0)];
37
+ for (let i = 0; i < n - 1; i++) {
38
+ const h = x(i + 1) - x(i);
39
+ const count = Math.max(1, Math.min(64, Math.ceil(Math.hypot(h, y(i + 1) - y(i)) / step)));
40
+ for (let k = 1; k <= count; k++) {
41
+ const s = k / count;
42
+ const s2 = s * s;
43
+ const s3 = s2 * s;
44
+ const yy = (2 * s3 - 3 * s2 + 1) * y(i) + (s3 - 2 * s2 + s) * h * tangents[i] + (-2 * s3 + 3 * s2) * y(i + 1) + (s3 - s2) * h * tangents[i + 1];
45
+ out.push(x(i) + h * s, yy);
46
+ }
47
+ }
48
+ return out;
49
+ }
50
+ /** Centripetal Catmull-Rom spline through the points (no cusps or self-loops). */
51
+ function catmullRom(flat, closed = false, step = 2, alpha = .5) {
52
+ const n = flat.length / 2;
53
+ if (n < 3) return flat.slice();
54
+ const px = (i) => flat[(i % n + n) % n * 2];
55
+ const py = (i) => flat[(i % n + n) % n * 2 + 1];
56
+ const get = (i) => {
57
+ if (!closed) {
58
+ if (i < 0) return [2 * px(0) - px(1), 2 * py(0) - py(1)];
59
+ if (i > n - 1) return [2 * px(n - 1) - px(n - 2), 2 * py(n - 1) - py(n - 2)];
60
+ }
61
+ return [px(i), py(i)];
62
+ };
63
+ const out = [];
64
+ const segs = closed ? n : n - 1;
65
+ out.push(px(0), py(0));
66
+ for (let i = 0; i < segs; i++) {
67
+ const p0 = get(i - 1);
68
+ const p1 = get(i);
69
+ const p2 = get(i + 1);
70
+ const p3 = get(i + 2);
71
+ const knot = (a, b) => Math.max(Math.hypot(b[0] - a[0], b[1] - a[1]) ** alpha, 1e-6);
72
+ const t1 = knot(p0, p1);
73
+ const t2 = t1 + knot(p1, p2);
74
+ const t3 = t2 + knot(p2, p3);
75
+ const count = Math.max(1, Math.min(64, Math.ceil(Math.hypot(p2[0] - p1[0], p2[1] - p1[1]) / step)));
76
+ for (let k = 1; k <= count; k++) {
77
+ const t = t1 + (t2 - t1) * (k / count);
78
+ const lerp = (a, b, ta, tb) => {
79
+ const w = (t - ta) / (tb - ta);
80
+ return [a[0] + (b[0] - a[0]) * w, a[1] + (b[1] - a[1]) * w];
81
+ };
82
+ const a1 = lerp(p0, p1, 0, t1);
83
+ const a2 = lerp(p1, p2, t1, t2);
84
+ const a3 = lerp(p2, p3, t2, t3);
85
+ const c = lerp(lerp(a1, a2, 0, t2), lerp(a2, a3, t1, t3), t1, t2);
86
+ out.push(c[0], c[1]);
87
+ }
88
+ }
89
+ if (closed) out.splice(out.length - 2, 2);
90
+ return out;
91
+ }
92
+ /** Flattens a cubic bezier (start point excluded) into `out`. */
93
+ function flattenCubic(out, x0, y0, c1x, c1y, c2x, c2y, x1, y1, step = 2) {
94
+ const len = Math.hypot(c1x - x0, c1y - y0) + Math.hypot(c2x - c1x, c2y - c1y) + Math.hypot(x1 - c2x, y1 - c2y);
95
+ const count = Math.max(2, Math.min(256, Math.ceil(len / step)));
96
+ for (let k = 1; k <= count; k++) {
97
+ const t = k / count;
98
+ const mt = 1 - t;
99
+ const a = mt * mt * mt;
100
+ const b = 3 * mt * mt * t;
101
+ const c = 3 * mt * t * t;
102
+ const d = t * t * t;
103
+ out.push(a * x0 + b * c1x + c * c2x + d * x1, a * y0 + b * c1y + c * c2y + d * y1);
104
+ }
105
+ }
106
+ /** Flattens a quadratic bezier (start point excluded) into `out`. */
107
+ function flattenQuadratic(out, x0, y0, cx, cy, x1, y1, step = 2) {
108
+ const len = Math.hypot(cx - x0, cy - y0) + Math.hypot(x1 - cx, y1 - cy);
109
+ const count = Math.max(2, Math.min(256, Math.ceil(len / step)));
110
+ for (let k = 1; k <= count; k++) {
111
+ const t = k / count;
112
+ const mt = 1 - t;
113
+ out.push(mt * mt * x0 + 2 * mt * t * cx + t * t * x1, mt * mt * y0 + 2 * mt * t * cy + t * t * y1);
114
+ }
115
+ }
116
+ //#endregion
117
+ export { catmullRom, flattenCubic, flattenQuadratic, monotoneX, toFlat };