@mark1russell7/layout-contract 0.10.2 → 0.10.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 +4 -1
- package/build/index.d.ts +181 -2
- package/build/index.d.ts.map +1 -1
- package/build/index.js +573 -9
- package/build/index.js.map +1 -1
- package/build/{measures-J0yY_JvV.d.ts → measures-B4oIewps.d.ts} +15 -2
- package/build/measures-B4oIewps.d.ts.map +1 -0
- package/build/text.d.ts +1 -1
- package/package.json +2 -1
- package/src/geometry.ts +57 -0
- package/src/index.ts +2 -0
- package/src/path.ts +300 -0
- package/src/picture.ts +277 -0
- package/build/measures-J0yY_JvV.d.ts.map +0 -1
|
@@ -133,6 +133,11 @@ declare function segmentsCross(a: Point, b: Point, c: Point, d: Point): boolean;
|
|
|
133
133
|
declare function crossingPoint(a: Point, b: Point, c: Point, d: Point): Point | undefined;
|
|
134
134
|
/** This function gives the shortest distance from `p` to the segment `ab`. A segment of length 0 is the point `a`. */
|
|
135
135
|
declare function pointSegmentDistance(p: Point, a: Point, b: Point): number;
|
|
136
|
+
/**
|
|
137
|
+
* This function gives the shortest distance from `p` to a polyline. A polyline of one point is that point, and an empty polyline gives `Infinity`.
|
|
138
|
+
* The hit test of a route uses it with the polyline of `samplePath`.
|
|
139
|
+
*/
|
|
140
|
+
declare function pointPolylineDistance(p: Point, points: readonly Point[]): number;
|
|
136
141
|
/** A ring of a polygon: its corners in order, as `[x, y]` pairs. The last corner connects to the first. */
|
|
137
142
|
type Ring = readonly (readonly [number, number])[];
|
|
138
143
|
/** This function tells if the point (`x`, `y`) is inside a ring, by the even-odd rule. A ring can be concave. The answer for a point on the border can be each value. */
|
|
@@ -142,6 +147,12 @@ declare function pointInRing(x: number, y: number, ring: Ring): boolean;
|
|
|
142
147
|
* Thus a point inside the outer ring and inside a hole is out. The answer for a point on a border can be each value.
|
|
143
148
|
*/
|
|
144
149
|
declare function pointInRings(x: number, y: number, rings: readonly Ring[]): boolean;
|
|
150
|
+
/**
|
|
151
|
+
* This function gives the distance from `p` to a region. A point in the region gives 0, so a hit test compares the value with its slack.
|
|
152
|
+
* A hole of a polygon is not in the region. A polygon with no corner gives `Infinity`.
|
|
153
|
+
* The distance to an ellipse is along the line to its center. Thus the value is the shortest distance or more, and the two are equal on the axes.
|
|
154
|
+
*/
|
|
155
|
+
declare function pointRegionDistance(p: Point, region: Region): number;
|
|
145
156
|
/**
|
|
146
157
|
* This function gives the centroid of the area of a ring, by the shoelace formula. The order of the corners can be
|
|
147
158
|
* clockwise or counterclockwise. A ring with the area 0 gives the mean of its corners. An empty ring is a `RangeError`.
|
|
@@ -154,6 +165,8 @@ declare function ringCentroid(ring: Ring): Point;
|
|
|
154
165
|
* gives an empty ring. The part of a convex ring is convex. The part of a concave ring can have sides of length 0 on the line.
|
|
155
166
|
*/
|
|
156
167
|
declare function clipRing(ring: Ring, a: number, b: number, c: number): Ring;
|
|
168
|
+
/** This function gives the middle of a rectangle. */
|
|
169
|
+
declare function rectCenter(rect: Rect): Point;
|
|
157
170
|
/** This function gives the distance between the centers of two rectangles. */
|
|
158
171
|
declare function boxCenterDistance(a: Rect, b: Rect): number;
|
|
159
172
|
/**
|
|
@@ -726,5 +739,5 @@ declare function minEffectOf(spec: Pick<MeasureSpec, "minEffect">, a?: number, b
|
|
|
726
739
|
* Two equal values are a tie, also two infinite values. A value `NaN` is an error.
|
|
727
740
|
*/
|
|
728
741
|
declare function compareMeasure(candidate: number, baseline: number, spec: Pick<MeasureSpec, "direction" | "minEffect">): Verdict;
|
|
729
|
-
export { CorpusEntry as $, shapeKindsOf as A, convexCorners as At, LayoutInput as B,
|
|
730
|
-
//# sourceMappingURL=measures-
|
|
742
|
+
export { CorpusEntry as $, shapeKindsOf as A, convexCorners as At, LayoutInput as B, pointPolylineDistance as Bt, checkShapes as C, SIDES as Ct, ruleLevel as D, boundsOf as Dt, itemShapeOf as E, SizedRect as Et, LayoutBox as F, grow as Ft, PairGap as G, regionPerimeter as Gt, PackInput as H, pointSegmentDistance as Ht, LayoutCell as I, marginSides as It, canonicalInput as J, segmentsCross as Jt, Port as K, ringCentroid as Kt, LayoutContainer as L, overlapOf as Lt, shapeSupportProblems as M, cornersInConvex as Mt, shapesOf as N, crossingPoint as Nt, shapeKindOf as O, boxCenterDistance as Ot, Item as P, dropIndex as Pt, ClaimBreak as Q, translate as Qt, LayoutEdge as R, pointInRing as Rt, boxArea as S, Ring as St, isShapeKind as T, Sides as Tt, PackInputOptions as U, rectCenter as Ut, Obstacle as V, pointRegionDistance as Vt, PackLink as W, regionArea as Wt, portPoint as X, toRect as Xt, packLinks as Y, snapRect as Yt, toPackInput as Z, toSizedRect as Zt, ShapeKind as _, splitFolds as _t, MeasureSpec as a, FamilyCell as at, ShapeLimit as b, Rect as bt, minEffectOf as c, SplitFold as ct, SHAPE_KINDS as d, corpusHashOf as dt, CorpusSplit as et, SHAPE_KIND_IDS as f, declaredClaimOf as ft, ShapeInput as g, splitFileName as gt, ShapeGeometry as h, leaveOneSeedOut as ht, JointMeasureId as i, FamilyBy as it, shapeLevel as j, convexOverlap as jt, shapeKindProblem as k, clipRing as kt, DEFAULT_SHAPES as l, checkDeclared as lt, ShapeCheck as m, familyOf as mt, JOINT_MEASURES as n, Declares as nt, Verdict as o, SPLIT_SCHEMA as ot, ShapeBound as p, declaredCounts as pt, Resize as q, scaleRect as qt, JOINT_MOVED_MIN as r, FAMILY_ANY_KIND as rt, compareMeasure as s, SplitCorpus as st, Direction as t, DeclaredClaim as tt, RuleLevel as u, checkSplit as ut, ShapeKindSpec as v, Margin as vt, inputShapeLevel as w, Side as wt, ShapeSupport as x, Region as xt, ShapeLevel as y, Point as yt, LayoutGenerator as z, pointInRings as zt };
|
|
743
|
+
//# sourceMappingURL=measures-B4oIewps.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"measures-B4oIewps.d.ts","names":[],"sources":["../src/geometry.ts","../src/corpus.ts","../src/input.ts","../src/shapes.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AOvF,aAAa,KAAK,+BAA+B,QAAQ,KAAK;;;;;iBAe1D,gBAAgB,KAAK,KAAK,sDAAsD,MAAM,WAAW,OAAO,aAAa;;;;;;;iBAWrH,qBAAqB,eAAe;;iBAwCpC,YAAY,iBAAiB,SAAS;;;;;iBAQtC,YAAY,KAAK,YAAY;;;;;;;iBAW7B,QAAQ,KAAK;;iBAQb,aAAa,OAAO,KAAK,wBAAwB;;iBAMjD,YAAY,OAAO,KAAK,wBAAwB;;iBAMhD,iBAAiB,KAAK;;iBAWtB,SAAS,KAAK,KAAK,mCAAmC;;UAKrD;;;;;;WAMN;;;;;;;;iBASK,YAAY,OAAO,YAAY,eAAe,gBAAgB,UAAS,aAAkB;;KCtQ7F;;;;;;UAOK,YAAY;WAClB,IAAI;WACJ;WACA,WAAW;;WAEX;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;aAAgC;;;WAEhC;;WAEA,kBAAkB;;;;;WAKlB,QAAQ;;;KAIP;;;;;cAqBC,yBAAyB,YAAY;;cAcrC;;KAGD;;;;;;iBAOI,YAAY,MAAM,KAAK,2BAA2B,YAAO;;;;;;;iBAezD,eAAe,mBAAmB,kBAAkB,MAAM,KAAK,0CAA0C"}
|
package/build/text.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as MeasureSpec } from "./measures-
|
|
1
|
+
import { a as MeasureSpec } from "./measures-B4oIewps.js";
|
|
2
2
|
/**
|
|
3
3
|
* The advance function of a host: the width of a run of text in a font, in pixels.
|
|
4
4
|
* A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/layout-contract",
|
|
4
|
-
"version": "0.10.
|
|
4
|
+
"version": "0.10.4",
|
|
5
5
|
"description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"layout",
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@mark1russell7/cue": "^2.1.1",
|
|
53
|
+
"@mark1russell7/rigor-bench": "^0.2.47",
|
|
53
54
|
"@types/node": "^26.6.4",
|
|
54
55
|
"@vitest/coverage-v8": "^5.0.3",
|
|
55
56
|
"esbuild": "^0.28.2",
|
package/src/geometry.ts
CHANGED
|
@@ -365,6 +365,18 @@ export function pointSegmentDistance(p: Point, a: Point, b: Point): number {
|
|
|
365
365
|
return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
|
|
366
366
|
}
|
|
367
367
|
|
|
368
|
+
/**
|
|
369
|
+
* This function gives the shortest distance from `p` to a polyline. A polyline of one point is that point, and an empty polyline gives `Infinity`.
|
|
370
|
+
* The hit test of a route uses it with the polyline of `samplePath`.
|
|
371
|
+
*/
|
|
372
|
+
export function pointPolylineDistance(p: Point, points: readonly Point[]): number {
|
|
373
|
+
const first = points[0];
|
|
374
|
+
if (first === undefined) return Infinity;
|
|
375
|
+
let best = Math.hypot(p.x - first.x, p.y - first.y);
|
|
376
|
+
for (let i = 1; i < points.length; i++) best = Math.min(best, pointSegmentDistance(p, points[i - 1]!, points[i]!));
|
|
377
|
+
return best;
|
|
378
|
+
}
|
|
379
|
+
|
|
368
380
|
/** A ring of a polygon: its corners in order, as `[x, y]` pairs. The last corner connects to the first. */
|
|
369
381
|
export type Ring = readonly (readonly [number, number])[];
|
|
370
382
|
|
|
@@ -389,6 +401,46 @@ export function pointInRings(x: number, y: number, rings: readonly Ring[]): bool
|
|
|
389
401
|
return inside;
|
|
390
402
|
}
|
|
391
403
|
|
|
404
|
+
/**
|
|
405
|
+
* This function gives the distance from `p` to a region. A point in the region gives 0, so a hit test compares the value with its slack.
|
|
406
|
+
* A hole of a polygon is not in the region. A polygon with no corner gives `Infinity`.
|
|
407
|
+
* The distance to an ellipse is along the line to its center. Thus the value is the shortest distance or more, and the two are equal on the axes.
|
|
408
|
+
*/
|
|
409
|
+
export function pointRegionDistance(p: Point, region: Region): number {
|
|
410
|
+
switch (region.kind) {
|
|
411
|
+
case "rect":
|
|
412
|
+
return Math.hypot(Math.max(region.x - p.x, 0, p.x - region.x - region.w), Math.max(region.y - p.y, 0, p.y - region.y - region.h));
|
|
413
|
+
case "circle":
|
|
414
|
+
return Math.max(0, Math.hypot(p.x - region.cx, p.y - region.cy) - region.r);
|
|
415
|
+
case "ellipse": {
|
|
416
|
+
const dx = p.x - region.cx;
|
|
417
|
+
const dy = p.y - region.cy;
|
|
418
|
+
// An ellipse with no width or no height is a segment or a point.
|
|
419
|
+
if (!(region.rx > 0) || !(region.ry > 0)) {
|
|
420
|
+
const rx = Math.max(0, region.rx);
|
|
421
|
+
const ry = Math.max(0, region.ry);
|
|
422
|
+
return pointSegmentDistance(p, { x: region.cx - rx, y: region.cy - ry }, { x: region.cx + rx, y: region.cy + ry });
|
|
423
|
+
}
|
|
424
|
+
// The line from the center to `p` leaves the ellipse at the share 1 / `far` of its length.
|
|
425
|
+
const far = Math.hypot(dx / region.rx, dy / region.ry);
|
|
426
|
+
return far <= 1 ? 0 : Math.hypot(dx, dy) * (1 - 1 / far);
|
|
427
|
+
}
|
|
428
|
+
case "polygon": {
|
|
429
|
+
const rings = region.holes === undefined ? [region.points] : [region.points, ...region.holes];
|
|
430
|
+
if (pointInRings(p.x, p.y, rings)) return 0;
|
|
431
|
+
let best = Infinity;
|
|
432
|
+
for (const ring of rings) {
|
|
433
|
+
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
|
434
|
+
const [ax, ay] = ring[j]!;
|
|
435
|
+
const [bx, by] = ring[i]!;
|
|
436
|
+
best = Math.min(best, pointSegmentDistance(p, { x: ax, y: ay }, { x: bx, y: by }));
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
return best;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
392
444
|
/**
|
|
393
445
|
* This function gives the centroid of the area of a ring, by the shoelace formula. The order of the corners can be
|
|
394
446
|
* clockwise or counterclockwise. A ring with the area 0 gives the mean of its corners. An empty ring is a `RangeError`.
|
|
@@ -440,6 +492,11 @@ export function clipRing(ring: Ring, a: number, b: number, c: number): Ring {
|
|
|
440
492
|
return out;
|
|
441
493
|
}
|
|
442
494
|
|
|
495
|
+
/** This function gives the middle of a rectangle. */
|
|
496
|
+
export function rectCenter(rect: Rect): Point {
|
|
497
|
+
return { x: rect.x + rect.w / 2, y: rect.y + rect.h / 2 };
|
|
498
|
+
}
|
|
499
|
+
|
|
443
500
|
/** This function gives the distance between the centers of two rectangles. */
|
|
444
501
|
export function boxCenterDistance(a: Rect, b: Rect): number {
|
|
445
502
|
return Math.hypot(b.x + b.w / 2 - (a.x + a.w / 2), b.y + b.h / 2 - (a.y + a.h / 2));
|
package/src/index.ts
CHANGED
|
@@ -13,6 +13,8 @@ export * from "./measures.ts";
|
|
|
13
13
|
export * from "./balance.ts";
|
|
14
14
|
export * from "./cell.ts";
|
|
15
15
|
export * from "./frame.ts";
|
|
16
|
+
export * from "./path.ts";
|
|
17
|
+
export * from "./picture.ts";
|
|
16
18
|
export * from "./strategy.ts";
|
|
17
19
|
export * from "./random.ts";
|
|
18
20
|
export * from "./edges.ts";
|
package/src/path.ts
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// The paths of a picture (`docs/PICTURE.md`): a path is a list of segments that each renderer draws in the same way.
|
|
2
|
+
// The record came from the curve model of `highways`, so a curve of `highways` is a path with no change.
|
|
3
|
+
import type { Point, Rect } from "./geometry.ts";
|
|
4
|
+
|
|
5
|
+
/** The kinds of the segments of a path. */
|
|
6
|
+
export const PATH_KINDS = ["move", "line", "cubic", "arc"] as const;
|
|
7
|
+
|
|
8
|
+
/** The start of a path: the pen goes to `to` and draws nothing. */
|
|
9
|
+
export interface PathMove {
|
|
10
|
+
readonly kind: "move";
|
|
11
|
+
readonly to: Point;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** A straight line from the end of the segment before to `to`. */
|
|
15
|
+
export interface PathLine {
|
|
16
|
+
readonly kind: "line";
|
|
17
|
+
readonly to: Point;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A cubic Bezier curve from the end of the segment before to `to`, with the control points `c1` and `c2`. */
|
|
21
|
+
export interface PathCubic {
|
|
22
|
+
readonly kind: "cubic";
|
|
23
|
+
readonly c1: Point;
|
|
24
|
+
readonly c2: Point;
|
|
25
|
+
readonly to: Point;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A circular arc from the end of the segment before to `to`. The arc has its center at `center` and the radius `radius`.
|
|
30
|
+
* It starts at the angle `start` and turns by `sweep` radians. A positive `sweep` turns from the x axis to the y axis.
|
|
31
|
+
* On a canvas, `ctx.arc(center.x, center.y, radius, start, start + sweep, sweep < 0)` draws it.
|
|
32
|
+
*/
|
|
33
|
+
export interface PathArc {
|
|
34
|
+
readonly kind: "arc";
|
|
35
|
+
readonly center: Point;
|
|
36
|
+
readonly radius: number;
|
|
37
|
+
readonly start: number;
|
|
38
|
+
readonly sweep: number;
|
|
39
|
+
readonly to: Point;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A segment of a path. A path is a list of segments: one `move` first, then lines, cubic curves and arcs.
|
|
44
|
+
* A renderer maps the list to SVG path data, to canvas commands or to the vertices of a mesh.
|
|
45
|
+
*/
|
|
46
|
+
export type PathSegment = PathMove | PathLine | PathCubic | PathArc;
|
|
47
|
+
|
|
48
|
+
/** A point of a path, with the direction of the path at that point. */
|
|
49
|
+
export interface PathTangent {
|
|
50
|
+
readonly point: Point;
|
|
51
|
+
/** A unit vector along the path, in the direction from its start to its end. A path with no length gives the vector 0, 0. */
|
|
52
|
+
readonly direction: Point;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The largest number of points that `samplePath` gives for one segment. */
|
|
56
|
+
const MAX_STEPS = 1024;
|
|
57
|
+
|
|
58
|
+
/** This function gives the path of a polyline: a `move` to the first point, then a line to each next point. A list with no point gives an empty path. */
|
|
59
|
+
export function pathOf(points: readonly Point[]): PathSegment[] {
|
|
60
|
+
return points.map((to, i) => (i === 0 ? { kind: "move", to } : { kind: "line", to }));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* This function gives a polyline that follows the path. The distance from each part of the path to the polyline is `tolerance` or less.
|
|
65
|
+
* The polyline starts at the point of the `move` and goes through the end of each segment.
|
|
66
|
+
* Hit tests, measures and renderers that draw only lines use this polyline.
|
|
67
|
+
*/
|
|
68
|
+
export function samplePath(segments: readonly PathSegment[], tolerance = 0.5): Point[] {
|
|
69
|
+
const tol = Math.max(1e-6, tolerance);
|
|
70
|
+
const out: Point[] = [];
|
|
71
|
+
let at: Point | undefined;
|
|
72
|
+
for (const s of segments) {
|
|
73
|
+
if (s.kind === "move" || at === undefined) {
|
|
74
|
+
out.push(s.to);
|
|
75
|
+
at = s.to;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (s.kind === "cubic") {
|
|
79
|
+
// The chord of a step of 1/n of the parameter is within 3·D/(4·n²) of the curve. D is the largest second difference of the control points.
|
|
80
|
+
const d = Math.max(Math.hypot(at.x - 2 * s.c1.x + s.c2.x, at.y - 2 * s.c1.y + s.c2.y), Math.hypot(s.c1.x - 2 * s.c2.x + s.to.x, s.c1.y - 2 * s.c2.y + s.to.y));
|
|
81
|
+
const n = Math.min(MAX_STEPS, Math.max(1, Math.ceil(Math.sqrt((3 * d) / (4 * tol)))));
|
|
82
|
+
for (let k = 1; k < n; k++) out.push(cubicAt(at, s.c1, s.c2, s.to, k / n));
|
|
83
|
+
} else if (s.kind === "arc") {
|
|
84
|
+
// The chord of an angle φ is within r·(1 - cos(φ/2)) of the arc.
|
|
85
|
+
const step = s.radius <= tol ? Math.PI : 2 * Math.acos(1 - tol / s.radius);
|
|
86
|
+
const n = Math.min(MAX_STEPS, Math.max(1, Math.ceil(Math.abs(s.sweep) / step)));
|
|
87
|
+
for (let k = 1; k < n; k++) {
|
|
88
|
+
const a = s.start + (s.sweep * k) / n;
|
|
89
|
+
out.push({ x: s.center.x + s.radius * Math.cos(a), y: s.center.y + s.radius * Math.sin(a) });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
out.push(s.to);
|
|
93
|
+
at = s.to;
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** This function gives the point at the parameter `t` of the cubic Bezier curve with the control points `p0`, `p1`, `p2` and `p3`. */
|
|
99
|
+
export function cubicAt(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point {
|
|
100
|
+
const u = 1 - t;
|
|
101
|
+
const a = u * u * u;
|
|
102
|
+
const b = 3 * u * u * t;
|
|
103
|
+
const c = 3 * u * t * t;
|
|
104
|
+
const d = t * t * t;
|
|
105
|
+
return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* This function writes the segments as the data of an SVG path: the commands `M`, `L`, `C` and `A`.
|
|
110
|
+
* Each number has at most `digits` digits after the point.
|
|
111
|
+
*/
|
|
112
|
+
export function toSvgPath(segments: readonly PathSegment[], digits = 2): string {
|
|
113
|
+
const n = (v: number): string => {
|
|
114
|
+
const s = String(Number(v.toFixed(digits)));
|
|
115
|
+
return s === "-0" ? "0" : s;
|
|
116
|
+
};
|
|
117
|
+
const p = (q: Point): string => `${n(q.x)} ${n(q.y)}`;
|
|
118
|
+
const parts: string[] = [];
|
|
119
|
+
for (const s of segments) {
|
|
120
|
+
if (s.kind === "move") parts.push(`M ${p(s.to)}`);
|
|
121
|
+
else if (s.kind === "line") parts.push(`L ${p(s.to)}`);
|
|
122
|
+
else if (s.kind === "cubic") parts.push(`C ${p(s.c1)} ${p(s.c2)} ${p(s.to)}`);
|
|
123
|
+
else parts.push(`A ${n(s.radius)} ${n(s.radius)} 0 ${Math.abs(s.sweep) > Math.PI ? 1 : 0} ${s.sweep > 0 ? 1 : 0} ${p(s.to)}`);
|
|
124
|
+
}
|
|
125
|
+
return parts.join(" ");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** This function gives the parameters between 0 and 1 where `a·t² + b·t + c` is 0. The stable form of the roots keeps a small `a` correct. */
|
|
129
|
+
function unitRoots(a: number, b: number, c: number): number[] {
|
|
130
|
+
const inside = (t: number): boolean => t > 0 && t < 1;
|
|
131
|
+
if (a === 0) return b !== 0 && inside(-c / b) ? [-c / b] : [];
|
|
132
|
+
const disc = b * b - 4 * a * c;
|
|
133
|
+
if (!(disc >= 0)) return [];
|
|
134
|
+
const q = -(b + (b < 0 ? -1 : 1) * Math.sqrt(disc)) / 2;
|
|
135
|
+
const roots = q === 0 ? [0] : [q / a, c / q];
|
|
136
|
+
return roots.filter(inside);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* This function gives the exact bounding box of a path. The box of a cubic curve has the points where the curve turns back on an axis.
|
|
141
|
+
* The box of an arc has the points of its circle at each quarter turn that the arc goes through.
|
|
142
|
+
* A path with no segment gives a `RangeError`.
|
|
143
|
+
*/
|
|
144
|
+
export function pathBounds(segments: readonly PathSegment[]): Rect {
|
|
145
|
+
if (segments.length === 0) throw new RangeError("layout-path: a path with no segment has no bounds.");
|
|
146
|
+
let x0 = Infinity;
|
|
147
|
+
let y0 = Infinity;
|
|
148
|
+
let x1 = -Infinity;
|
|
149
|
+
let y1 = -Infinity;
|
|
150
|
+
const add = (p: Point): void => {
|
|
151
|
+
x0 = Math.min(x0, p.x);
|
|
152
|
+
y0 = Math.min(y0, p.y);
|
|
153
|
+
x1 = Math.max(x1, p.x);
|
|
154
|
+
y1 = Math.max(y1, p.y);
|
|
155
|
+
};
|
|
156
|
+
let at: Point | undefined;
|
|
157
|
+
for (const s of segments) {
|
|
158
|
+
add(s.to);
|
|
159
|
+
const from = at;
|
|
160
|
+
at = s.to;
|
|
161
|
+
if (from === undefined) continue;
|
|
162
|
+
if (s.kind === "cubic") {
|
|
163
|
+
// The derivative of the curve on one axis is 3·(a·t² + b·t + c).
|
|
164
|
+
for (const k of ["x", "y"] as const) {
|
|
165
|
+
const a = s.to[k] - 3 * s.c2[k] + 3 * s.c1[k] - from[k];
|
|
166
|
+
const b = 2 * (s.c2[k] - 2 * s.c1[k] + from[k]);
|
|
167
|
+
const c = s.c1[k] - from[k];
|
|
168
|
+
for (const t of unitRoots(a, b, c)) add(cubicAt(from, s.c1, s.c2, s.to, t));
|
|
169
|
+
}
|
|
170
|
+
} else if (s.kind === "arc") {
|
|
171
|
+
const quarter = Math.PI / 2;
|
|
172
|
+
const lo = Math.min(s.start, s.start + s.sweep);
|
|
173
|
+
const hi = Math.max(s.start, s.start + s.sweep);
|
|
174
|
+
if (!Number.isFinite(lo) || !Number.isFinite(hi)) continue;
|
|
175
|
+
const first = hi - lo >= 2 * Math.PI ? 0 : Math.ceil(lo / quarter);
|
|
176
|
+
const last = hi - lo >= 2 * Math.PI ? 3 : Math.floor(hi / quarter);
|
|
177
|
+
for (let k = first; k <= last; k++) {
|
|
178
|
+
// The unit vector of the angle k·π/2 has whole numbers, so the box has no error of a cosine.
|
|
179
|
+
const turn = ((k % 4) + 4) % 4;
|
|
180
|
+
const ux = turn === 0 ? 1 : turn === 2 ? -1 : 0;
|
|
181
|
+
const uy = turn === 1 ? 1 : turn === 3 ? -1 : 0;
|
|
182
|
+
add({ x: s.center.x + s.radius * ux, y: s.center.y + s.radius * uy });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** This function gives the unit vector of the vector `dx`, `dy`, or `undefined` for a vector with no length. */
|
|
190
|
+
function unit(dx: number, dy: number): Point | undefined {
|
|
191
|
+
const length = Math.hypot(dx, dy);
|
|
192
|
+
return length > 0 && Number.isFinite(length) ? { x: dx / length, y: dy / length } : undefined;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* This function gives the direction of one segment at its start or at its end. `from` is the end of the segment before.
|
|
197
|
+
* A segment with no length gives `undefined`. A cubic curve with a control point on its end uses the next control point.
|
|
198
|
+
*/
|
|
199
|
+
function directionOf(from: Point, s: PathSegment, atEnd: boolean): Point | undefined {
|
|
200
|
+
if (s.kind === "move") return undefined;
|
|
201
|
+
const chord = (): Point | undefined => unit(s.to.x - from.x, s.to.y - from.y);
|
|
202
|
+
if (s.kind === "cubic") {
|
|
203
|
+
return atEnd
|
|
204
|
+
? (unit(s.to.x - s.c2.x, s.to.y - s.c2.y) ?? unit(s.to.x - s.c1.x, s.to.y - s.c1.y) ?? chord())
|
|
205
|
+
: (unit(s.c1.x - from.x, s.c1.y - from.y) ?? unit(s.c2.x - from.x, s.c2.y - from.y) ?? chord());
|
|
206
|
+
}
|
|
207
|
+
if (s.kind === "arc" && s.radius > 0 && s.sweep !== 0) {
|
|
208
|
+
const angle = atEnd ? s.start + s.sweep : s.start;
|
|
209
|
+
const sign = s.sweep > 0 ? 1 : -1;
|
|
210
|
+
return unit(-sign * Math.sin(angle), sign * Math.cos(angle));
|
|
211
|
+
}
|
|
212
|
+
return chord();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* This function gives the first point of a path and the direction in which the path leaves it.
|
|
217
|
+
* The direction comes from the first segment that has a length. A path with no segment gives a `RangeError`.
|
|
218
|
+
*/
|
|
219
|
+
export function pathStart(segments: readonly PathSegment[]): PathTangent {
|
|
220
|
+
const first = segments[0];
|
|
221
|
+
if (first === undefined) throw new RangeError("layout-path: a path with no segment has no start.");
|
|
222
|
+
for (let i = 1; i < segments.length; i++) {
|
|
223
|
+
const direction = directionOf(segments[i - 1]!.to, segments[i]!, false);
|
|
224
|
+
if (direction !== undefined) return { point: first.to, direction };
|
|
225
|
+
}
|
|
226
|
+
return { point: first.to, direction: { x: 0, y: 0 } };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* This function gives the last point of a path and the direction in which the path comes to it. An arrow head at the end points along it.
|
|
231
|
+
* The direction comes from the last segment that has a length. A path with no segment gives a `RangeError`.
|
|
232
|
+
*/
|
|
233
|
+
export function pathEnd(segments: readonly PathSegment[]): PathTangent {
|
|
234
|
+
const last = segments[segments.length - 1];
|
|
235
|
+
if (last === undefined) throw new RangeError("layout-path: a path with no segment has no end.");
|
|
236
|
+
for (let i = segments.length - 1; i >= 1; i--) {
|
|
237
|
+
const direction = directionOf(segments[i - 1]!.to, segments[i]!, true);
|
|
238
|
+
if (direction !== undefined) return { point: last.to, direction };
|
|
239
|
+
}
|
|
240
|
+
return { point: last.to, direction: { x: 0, y: 0 } };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const isFields = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
244
|
+
|
|
245
|
+
const isPoint = (v: unknown): v is Point => isFields(v) && Number.isFinite(v["x"]) && Number.isFinite(v["y"]);
|
|
246
|
+
|
|
247
|
+
/** The fields of each kind of segment that hold a point. */
|
|
248
|
+
const POINT_FIELDS = { move: ["to"], line: ["to"], cubic: ["c1", "c2", "to"], arc: ["center", "to"] } as const;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* This function gives the problems of a path. An empty list means a good path.
|
|
252
|
+
* A good path starts with its one `move`, and each number of it is finite. An arc has a radius of 0 or more.
|
|
253
|
+
* An arc starts at the end of the segment before, and it ends at its `to`, to 1e-6 of its radius plus 1.
|
|
254
|
+
*/
|
|
255
|
+
export function checkPath(value: unknown): string[] {
|
|
256
|
+
if (!Array.isArray(value)) return ["the path is not a list"];
|
|
257
|
+
if (value.length === 0) return ["the path has no segment"];
|
|
258
|
+
const out: string[] = [];
|
|
259
|
+
let at: Point | undefined;
|
|
260
|
+
value.forEach((s: unknown, i) => {
|
|
261
|
+
const from = at;
|
|
262
|
+
at = undefined;
|
|
263
|
+
if (!isFields(s)) {
|
|
264
|
+
out.push(`segment ${i} is not an object`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const kind = PATH_KINDS.find((k) => k === s["kind"]);
|
|
268
|
+
if (kind === undefined) {
|
|
269
|
+
out.push(`segment ${i}: the kind is not one of ${PATH_KINDS.join(", ")}`);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (i === 0 && kind !== "move") out.push("segment 0 is not a move");
|
|
273
|
+
if (i > 0 && kind === "move") out.push(`segment ${i} is a second move`);
|
|
274
|
+
let good = true;
|
|
275
|
+
for (const key of POINT_FIELDS[kind]) {
|
|
276
|
+
if (isPoint(s[key])) continue;
|
|
277
|
+
out.push(`segment ${i}: ${key} is not a point of two finite numbers`);
|
|
278
|
+
good = false;
|
|
279
|
+
}
|
|
280
|
+
const to = s["to"];
|
|
281
|
+
if (isPoint(to)) at = to;
|
|
282
|
+
if (kind !== "arc") return;
|
|
283
|
+
for (const key of ["radius", "start", "sweep"] as const) {
|
|
284
|
+
if (Number.isFinite(s[key])) continue;
|
|
285
|
+
out.push(`segment ${i}: ${key} is not a finite number`);
|
|
286
|
+
good = false;
|
|
287
|
+
}
|
|
288
|
+
if (!good) return;
|
|
289
|
+
const arc = s as unknown as PathArc;
|
|
290
|
+
if (arc.radius < 0) {
|
|
291
|
+
out.push(`segment ${i}: the radius is less than 0`);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const slack = 1e-6 * (arc.radius + 1);
|
|
295
|
+
const on = (angle: number, p: Point): boolean => Math.hypot(arc.center.x + arc.radius * Math.cos(angle) - p.x, arc.center.y + arc.radius * Math.sin(angle) - p.y) <= slack;
|
|
296
|
+
if (from !== undefined && !on(arc.start, from)) out.push(`segment ${i}: the arc does not start at the end of the segment before`);
|
|
297
|
+
if (!on(arc.start + arc.sweep, arc.to)) out.push(`segment ${i}: the arc does not end at its point to`);
|
|
298
|
+
});
|
|
299
|
+
return out;
|
|
300
|
+
}
|