@mark1russell7/layout-contract 0.9.9 → 0.10.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/README.md +12 -7
- package/build/index.d.ts +314 -11
- package/build/index.d.ts.map +1 -1
- package/build/index.js +784 -24
- package/build/index.js.map +1 -1
- package/build/{measures-CJZw-Y3H.d.ts → measures-J0yY_JvV.d.ts} +32 -2
- package/build/measures-J0yY_JvV.d.ts.map +1 -0
- package/build/text.d.ts +1 -1
- package/build/text.js +3 -3
- package/build/text.js.map +1 -1
- package/package.json +1 -1
- package/src/balance.ts +11 -4
- package/src/cell.ts +104 -0
- package/src/curves.ts +200 -0
- package/src/geometry.ts +136 -0
- package/src/hash.ts +2 -2
- package/src/index.ts +4 -0
- package/src/input.ts +5 -0
- package/src/measure-registry.ts +192 -0
- package/src/measure-survey.ts +149 -0
- package/src/measures.ts +4 -4
- package/src/output.ts +15 -3
- package/src/resize.ts +13 -1
- package/src/rules.ts +82 -18
- package/src/text.ts +3 -3
- package/build/measures-CJZw-Y3H.d.ts.map +0 -1
package/src/curves.ts
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// Curves through the cells of a square grid: Hilbert, Moore and Morton (Z order). `docs/CURVES.md` gives the rules.
|
|
2
|
+
//
|
|
3
|
+
// A curve of side 2h has four parts. Part k fills the quadrant `order[k]` with a curve of side h, and the
|
|
4
|
+
// symmetry of part k maps that curve onto its quadrant. The top level uses the symmetries `root`, and each level
|
|
5
|
+
// below it uses the symmetries `child`. A curve of side 1 is the one cell (0, 0).
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A symmetry of a square: one of its 8 rotations and reflections. The names tell where a point `(s, t)` goes in a square
|
|
9
|
+
* of side `size`.
|
|
10
|
+
*/
|
|
11
|
+
export type CurveSymmetry =
|
|
12
|
+
/** The point stays: `(s, t)`. */
|
|
13
|
+
| "same"
|
|
14
|
+
/** The reflection in the diagonal from `(0, 0)`: `(t, s)`. */
|
|
15
|
+
| "swap"
|
|
16
|
+
/** The reflection in the other diagonal: `(size - t, size - s)`. */
|
|
17
|
+
| "back"
|
|
18
|
+
/** The turn by a half circle: `(size - s, size - t)`. */
|
|
19
|
+
| "half"
|
|
20
|
+
/** The quarter turn from the axis `s` to the axis `t`: `(size - t, s)`. */
|
|
21
|
+
| "rise"
|
|
22
|
+
/** The quarter turn from the axis `t` to the axis `s`: `(t, size - s)`. */
|
|
23
|
+
| "fall"
|
|
24
|
+
/** The reflection that changes `s`: `(size - s, t)`. */
|
|
25
|
+
| "flip-s"
|
|
26
|
+
/** The reflection that changes `t`: `(s, size - t)`. */
|
|
27
|
+
| "flip-t";
|
|
28
|
+
|
|
29
|
+
/** The 8 symmetries of a square, in a fixed order. */
|
|
30
|
+
export const CURVE_SYMMETRIES: readonly CurveSymmetry[] = Object.freeze(["same", "swap", "back", "half", "rise", "fall", "flip-s", "flip-t"]);
|
|
31
|
+
|
|
32
|
+
/** A quadrant of a square: `[0, 0]` is the low left quadrant, and `[1, 0]` is the quadrant with the high `s` and the low `t`. */
|
|
33
|
+
export type CurveQuadrant = readonly [0 | 1, 0 | 1];
|
|
34
|
+
|
|
35
|
+
/** The symmetries of the four parts of one level of a curve, in the order of the parts. */
|
|
36
|
+
export type CurvePattern = readonly [CurveSymmetry, CurveSymmetry, CurveSymmetry, CurveSymmetry];
|
|
37
|
+
|
|
38
|
+
/** A curve as data. It has the quadrant of each part in the order of the curve, and the symmetry of each part. */
|
|
39
|
+
export interface CurveSpec {
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly order: readonly [CurveQuadrant, CurveQuadrant, CurveQuadrant, CurveQuadrant];
|
|
42
|
+
readonly root: CurvePattern;
|
|
43
|
+
readonly child: CurvePattern;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The order of the parts of the Hilbert and Moore curves: low left, high left, high right and low right. */
|
|
47
|
+
const LOOP_ORDER: CurveSpec["order"] = Object.freeze([
|
|
48
|
+
Object.freeze([0, 0] as const),
|
|
49
|
+
Object.freeze([0, 1] as const),
|
|
50
|
+
Object.freeze([1, 1] as const),
|
|
51
|
+
Object.freeze([1, 0] as const),
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
/** The parts of the Hilbert curve. The curve goes in at the corner `(0, 0)` and out at the corner `(size, 0)`. */
|
|
55
|
+
export const HILBERT_PATTERN: CurvePattern = Object.freeze(["swap", "same", "same", "back"] as const);
|
|
56
|
+
|
|
57
|
+
/** The top level of the Moore curve: four Hilbert curves in a loop. The loop goes in and out at the middle of the side `t = 0`. */
|
|
58
|
+
export const MOORE_PATTERN: CurvePattern = Object.freeze(["rise", "rise", "fall", "fall"] as const);
|
|
59
|
+
|
|
60
|
+
/** The Hilbert curve. Two cells in a row along the curve share a side. */
|
|
61
|
+
export const HILBERT_CURVE: CurveSpec = Object.freeze({ name: "hilbert", order: LOOP_ORDER, root: HILBERT_PATTERN, child: HILBERT_PATTERN });
|
|
62
|
+
|
|
63
|
+
/** The Moore curve. Two cells in a row share a side, and the last cell shares a side with the first cell. */
|
|
64
|
+
export const MOORE_CURVE: CurveSpec = Object.freeze({ name: "moore", order: LOOP_ORDER, root: MOORE_PATTERN, child: HILBERT_PATTERN });
|
|
65
|
+
|
|
66
|
+
/** The Morton curve (the Z order). The index of a cell has the bits of `x` at the even places and the bits of `y` at the odd places. */
|
|
67
|
+
export const MORTON_CURVE: CurveSpec = Object.freeze({
|
|
68
|
+
name: "morton",
|
|
69
|
+
order: Object.freeze([Object.freeze([0, 0] as const), Object.freeze([1, 0] as const), Object.freeze([0, 1] as const), Object.freeze([1, 1] as const)] as const),
|
|
70
|
+
root: Object.freeze(["same", "same", "same", "same"] as const),
|
|
71
|
+
child: Object.freeze(["same", "same", "same", "same"] as const),
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
/** The largest side of a curve grid: 2 to the power 26. Thus each index is less than 2 to the power 52, and is exact. */
|
|
75
|
+
export const CURVE_MAX_SIDE: number = 2 ** 26;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* This function gives a point of the square `[0, size] x [0, size]` after a symmetry. The cell `(x, y)` of a grid of
|
|
79
|
+
* side `n` goes to a cell of the same grid with `size = n - 1`.
|
|
80
|
+
*/
|
|
81
|
+
export function applySymmetry(symmetry: CurveSymmetry, s: number, t: number, size = 1): [number, number] {
|
|
82
|
+
switch (symmetry) {
|
|
83
|
+
case "same":
|
|
84
|
+
return [s, t];
|
|
85
|
+
case "swap":
|
|
86
|
+
return [t, s];
|
|
87
|
+
case "back":
|
|
88
|
+
return [size - t, size - s];
|
|
89
|
+
case "half":
|
|
90
|
+
return [size - s, size - t];
|
|
91
|
+
case "rise":
|
|
92
|
+
return [size - t, s];
|
|
93
|
+
case "fall":
|
|
94
|
+
return [t, size - s];
|
|
95
|
+
case "flip-s":
|
|
96
|
+
return [size - s, t];
|
|
97
|
+
case "flip-t":
|
|
98
|
+
return [s, size - t];
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** This function gives the symmetry that undoes `symmetry`. Each symmetry undoes itself, but `rise` and `fall` undo each other. */
|
|
103
|
+
export function inverseSymmetry(symmetry: CurveSymmetry): CurveSymmetry {
|
|
104
|
+
return symmetry === "rise" ? "fall" : symmetry === "fall" ? "rise" : symmetry;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** This function gives the count of levels of a side. A side that is not a power of 2 from 1 to `CURVE_MAX_SIDE` is a `RangeError`. */
|
|
108
|
+
function levelsOf(side: number): number {
|
|
109
|
+
if (!Number.isInteger(side) || side < 1 || side > CURVE_MAX_SIDE || (side & (side - 1)) !== 0) {
|
|
110
|
+
throw new RangeError(`The side of a curve grid must be a power of 2 from 1 to ${CURVE_MAX_SIDE}, not ${side}.`);
|
|
111
|
+
}
|
|
112
|
+
return Math.round(Math.log2(side));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* This function gives the cell `[x, y]` at the place `index` along a curve on a grid of `side` cells on each side.
|
|
117
|
+
* The side is a power of 2, and the index is a whole number from 0 to `side * side - 1`. Other values are a `RangeError`.
|
|
118
|
+
* The cost is `O(log side)`.
|
|
119
|
+
*/
|
|
120
|
+
export function curveCell(curve: CurveSpec, index: number, side: number): [number, number] {
|
|
121
|
+
const levels = levelsOf(side);
|
|
122
|
+
if (!Number.isInteger(index) || index < 0 || index >= side * side) throw new RangeError(`The index ${index} is not a cell of a grid of side ${side}.`);
|
|
123
|
+
let x = 0;
|
|
124
|
+
let y = 0;
|
|
125
|
+
let rest = index;
|
|
126
|
+
// From the lowest level up: the cell in the part of side h goes to its quadrant of the part of side 2h.
|
|
127
|
+
for (let level = 0, h = 1; level < levels; level += 1, h *= 2) {
|
|
128
|
+
const part = rest % 4;
|
|
129
|
+
rest = Math.floor(rest / 4);
|
|
130
|
+
const pattern = level === levels - 1 ? curve.root : curve.child;
|
|
131
|
+
[x, y] = applySymmetry(pattern[part]!, x, y, h - 1);
|
|
132
|
+
const [qx, qy] = curve.order[part]!;
|
|
133
|
+
x += qx * h;
|
|
134
|
+
y += qy * h;
|
|
135
|
+
}
|
|
136
|
+
return [x, y];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* This function gives the place along a curve of the cell `(x, y)` of a grid of `side` cells on each side. It is the inverse
|
|
141
|
+
* of `curveCell`. A side that is not a power of 2, or a cell outside the grid, is a `RangeError`. The cost is `O(log side)`.
|
|
142
|
+
*/
|
|
143
|
+
export function curveIndex(curve: CurveSpec, x: number, y: number, side: number): number {
|
|
144
|
+
const levels = levelsOf(side);
|
|
145
|
+
for (const value of [x, y]) {
|
|
146
|
+
if (!Number.isInteger(value) || value < 0 || value >= side) throw new RangeError(`The cell (${x}, ${y}) is not in a grid of side ${side}.`);
|
|
147
|
+
}
|
|
148
|
+
let index = 0;
|
|
149
|
+
let s = x;
|
|
150
|
+
let t = y;
|
|
151
|
+
// From the top level down: find the quadrant, then undo the symmetry of its part.
|
|
152
|
+
for (let level = levels - 1, h = side / 2; level >= 0; level -= 1, h /= 2) {
|
|
153
|
+
const qx = s >= h ? 1 : 0;
|
|
154
|
+
const qy = t >= h ? 1 : 0;
|
|
155
|
+
const part = curve.order.findIndex(([ox, oy]) => ox === qx && oy === qy);
|
|
156
|
+
const pattern = level === levels - 1 ? curve.root : curve.child;
|
|
157
|
+
[s, t] = applySymmetry(inverseSymmetry(pattern[part]!), s - qx * h, t - qy * h, h - 1);
|
|
158
|
+
index += part * h * h;
|
|
159
|
+
}
|
|
160
|
+
return index;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** This function gives the place along the Hilbert curve of the cell `(x, y)` of a grid of side `side`. */
|
|
164
|
+
export function hilbertIndex(x: number, y: number, side: number): number {
|
|
165
|
+
return curveIndex(HILBERT_CURVE, x, y, side);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** This function gives the cell at the place `index` along the Hilbert curve on a grid of side `side`. */
|
|
169
|
+
export function hilbertCell(index: number, side: number): [number, number] {
|
|
170
|
+
return curveCell(HILBERT_CURVE, index, side);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** This function gives the place along the Moore curve of the cell `(x, y)` of a grid of side `side`. */
|
|
174
|
+
export function mooreIndex(x: number, y: number, side: number): number {
|
|
175
|
+
return curveIndex(MOORE_CURVE, x, y, side);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** This function gives the cell at the place `index` along the Moore curve on a grid of side `side`. */
|
|
179
|
+
export function mooreCell(index: number, side: number): [number, number] {
|
|
180
|
+
return curveCell(MOORE_CURVE, index, side);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** This function gives the place along the Morton curve of the cell `(x, y)` of a grid of side `side`. */
|
|
184
|
+
export function mortonIndex(x: number, y: number, side: number): number {
|
|
185
|
+
return curveIndex(MORTON_CURVE, x, y, side);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** This function gives the cell at the place `index` along the Morton curve on a grid of side `side`. */
|
|
189
|
+
export function mortonCell(index: number, side: number): [number, number] {
|
|
190
|
+
return curveCell(MORTON_CURVE, index, side);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* This function gives each cell of a grid of side `side` in the order of a curve. The cost is `O(side^2 log side)`.
|
|
195
|
+
* A side that is not a power of 2 is a `RangeError`.
|
|
196
|
+
*/
|
|
197
|
+
export function curveCells(curve: CurveSpec, side: number): [number, number][] {
|
|
198
|
+
levelsOf(side);
|
|
199
|
+
return Array.from({ length: side * side }, (_, index) => curveCell(curve, index, side));
|
|
200
|
+
}
|
package/src/geometry.ts
CHANGED
|
@@ -154,6 +154,42 @@ function ringArea(ring: readonly (readonly [number, number])[]): number {
|
|
|
154
154
|
return Math.abs(twice) / 2;
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
+
/**
|
|
158
|
+
* This function gives the perimeter of a region. A `rect` gives `2 * (w + h)`, and a circle gives `2 * PI * r`.
|
|
159
|
+
* A polygon gives the length of its outer ring plus the length of each hole. A ring with fewer than 2 points has the length 0.
|
|
160
|
+
*
|
|
161
|
+
* An ellipse has no closed form. It gives the second formula of Ramanujan, with a relative error below 5e-4 of the true perimeter. The error is largest for a flat ellipse.
|
|
162
|
+
*/
|
|
163
|
+
export function regionPerimeter(region: Region): number {
|
|
164
|
+
switch (region.kind) {
|
|
165
|
+
case "rect":
|
|
166
|
+
return 2 * (region.w + region.h);
|
|
167
|
+
case "circle":
|
|
168
|
+
return 2 * Math.PI * region.r;
|
|
169
|
+
case "ellipse": {
|
|
170
|
+
const a = Math.abs(region.rx);
|
|
171
|
+
const b = Math.abs(region.ry);
|
|
172
|
+
if (a + b === 0) return 0;
|
|
173
|
+
const t = ((a - b) / (a + b)) ** 2;
|
|
174
|
+
return Math.PI * (a + b) * (1 + (3 * t) / (10 + Math.sqrt(4 - 3 * t)));
|
|
175
|
+
}
|
|
176
|
+
case "polygon":
|
|
177
|
+
return (region.holes ?? []).reduce((length, hole) => length + ringLength(hole), ringLength(region.points));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** This function gives the length of the closed ring of a polygon. */
|
|
182
|
+
function ringLength(ring: readonly (readonly [number, number])[]): number {
|
|
183
|
+
if (ring.length < 2) return 0;
|
|
184
|
+
let length = 0;
|
|
185
|
+
for (let i = 0; i < ring.length; i++) {
|
|
186
|
+
const [ax, ay] = ring[i]!;
|
|
187
|
+
const [bx, by] = ring[(i + 1) % ring.length]!;
|
|
188
|
+
length += Math.hypot(bx - ax, by - ay);
|
|
189
|
+
}
|
|
190
|
+
return length;
|
|
191
|
+
}
|
|
192
|
+
|
|
157
193
|
/** This function gives the region moved by `dx` and `dy`. */
|
|
158
194
|
export function translate(region: Region, dx: number, dy: number): Region {
|
|
159
195
|
switch (region.kind) {
|
|
@@ -182,6 +218,106 @@ export function overlapOf(a: Rect, b: Rect): { readonly x: number; readonly y: n
|
|
|
182
218
|
};
|
|
183
219
|
}
|
|
184
220
|
|
|
221
|
+
/**
|
|
222
|
+
* This function gives the corners of a convex region, or `undefined` for each other region.
|
|
223
|
+
* A `rect` gives its 4 corners. A `polygon` without holes gives its points when it has 3 or more corners, an area over 0, and each turn to the same side.
|
|
224
|
+
* The turns use exact signs. A corner on a straight side is permitted. A circle and an ellipse give `undefined`.
|
|
225
|
+
*/
|
|
226
|
+
export function convexCorners(region: Region): Ring | undefined {
|
|
227
|
+
if (region.kind === "rect") {
|
|
228
|
+
const { x, y, w, h } = region;
|
|
229
|
+
return [
|
|
230
|
+
[x, y],
|
|
231
|
+
[x + w, y],
|
|
232
|
+
[x + w, y + h],
|
|
233
|
+
[x, y + h],
|
|
234
|
+
];
|
|
235
|
+
}
|
|
236
|
+
if (region.kind !== "polygon" || (region.holes !== undefined && region.holes.length > 0)) return undefined;
|
|
237
|
+
const ring = region.points;
|
|
238
|
+
if (ring.length < 3 || !ring.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y))) return undefined;
|
|
239
|
+
let turn = 0;
|
|
240
|
+
for (let i = 0; i < ring.length; i++) {
|
|
241
|
+
const [ax, ay] = ring[i]!;
|
|
242
|
+
const [bx, by] = ring[(i + 1) % ring.length]!;
|
|
243
|
+
const [cx, cy] = ring[(i + 2) % ring.length]!;
|
|
244
|
+
const s = orient2dSign(ax, ay, bx, by, cx, cy);
|
|
245
|
+
if (s === 0) continue;
|
|
246
|
+
if (turn !== 0 && s !== turn) return undefined;
|
|
247
|
+
turn = s;
|
|
248
|
+
}
|
|
249
|
+
return turn === 0 ? undefined : ring;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* This function gives the least overlap of two convex rings over the normals of their sides, in the units of the corners.
|
|
254
|
+
* By the separating axis theorem, a value of 0 or less tells that a line separates the rings. For two rectangles, the value is the lesser axis of `overlapOf`.
|
|
255
|
+
* A side of length 0 gives no normal. The rings come from `convexCorners`.
|
|
256
|
+
*/
|
|
257
|
+
export function convexOverlap(a: Ring, b: Ring): number {
|
|
258
|
+
let least = Infinity;
|
|
259
|
+
for (const ring of [a, b]) {
|
|
260
|
+
for (let i = 0; i < ring.length; i++) {
|
|
261
|
+
const [px, py] = ring[i]!;
|
|
262
|
+
const [qx, qy] = ring[(i + 1) % ring.length]!;
|
|
263
|
+
const length = Math.hypot(qx - px, qy - py);
|
|
264
|
+
if (length === 0) continue;
|
|
265
|
+
const nx = (py - qy) / length;
|
|
266
|
+
const ny = (qx - px) / length;
|
|
267
|
+
const [aLow, aHigh] = project(a, nx, ny);
|
|
268
|
+
const [bLow, bHigh] = project(b, nx, ny);
|
|
269
|
+
least = Math.min(least, Math.min(aHigh, bHigh) - Math.max(aLow, bLow));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return least;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** This function gives the least and the greatest projection of the corners of a ring on the direction (`nx`, `ny`). */
|
|
276
|
+
function project(ring: Ring, nx: number, ny: number): readonly [number, number] {
|
|
277
|
+
let low = Infinity;
|
|
278
|
+
let high = -Infinity;
|
|
279
|
+
for (const [x, y] of ring) {
|
|
280
|
+
const v = x * nx + y * ny;
|
|
281
|
+
if (v < low) low = v;
|
|
282
|
+
if (v > high) high = v;
|
|
283
|
+
}
|
|
284
|
+
return [low, high];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* This function tells if each corner of the ring `inner` is inside the convex ring `outer` made smaller by `inset`, with the tolerance `tolerance`.
|
|
289
|
+
* For a convex `outer`, this test is exact: a polygon is inside a convex region when each of its corners is inside.
|
|
290
|
+
* The ring `outer` comes from `convexCorners`, in either direction of its corners.
|
|
291
|
+
*/
|
|
292
|
+
export function cornersInConvex(inner: Ring, outer: Ring, inset = 0, tolerance = 0): boolean {
|
|
293
|
+
const turn = Math.sign(ringTwiceArea(outer));
|
|
294
|
+
for (let i = 0; i < outer.length; i++) {
|
|
295
|
+
const [px, py] = outer[i]!;
|
|
296
|
+
const [qx, qy] = outer[(i + 1) % outer.length]!;
|
|
297
|
+
const length = Math.hypot(qx - px, qy - py);
|
|
298
|
+
if (length === 0) continue;
|
|
299
|
+
// The left normal of a side points inside when the signed area is over 0. The sign of the area chooses the inward normal.
|
|
300
|
+
const nx = (turn * (py - qy)) / length;
|
|
301
|
+
const ny = (turn * (qx - px)) / length;
|
|
302
|
+
const edge = px * nx + py * ny;
|
|
303
|
+
for (const [x, y] of inner) if (x * nx + y * ny - edge < inset - tolerance) return false;
|
|
304
|
+
}
|
|
305
|
+
return true;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** This function gives two times the signed area of a ring, by the shoelace formula, relative to its first corner. */
|
|
309
|
+
function ringTwiceArea(ring: Ring): number {
|
|
310
|
+
if (ring.length === 0) return 0;
|
|
311
|
+
const [ox, oy] = ring[0]!;
|
|
312
|
+
let twice = 0;
|
|
313
|
+
for (let i = 0; i < ring.length; i++) {
|
|
314
|
+
const [ax, ay] = ring[i]!;
|
|
315
|
+
const [bx, by] = ring[(i + 1) % ring.length]!;
|
|
316
|
+
twice += (ax - ox) * (by - oy) - (bx - ox) * (ay - oy);
|
|
317
|
+
}
|
|
318
|
+
return twice;
|
|
319
|
+
}
|
|
320
|
+
|
|
185
321
|
/** This function gives the cross product of `ab` and `ac`. The sign tells the side of `ab` that has `c`. */
|
|
186
322
|
function orient(a: Point, b: Point, c: Point): number {
|
|
187
323
|
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
|
package/src/hash.ts
CHANGED
|
@@ -96,7 +96,7 @@ function byId(a: { readonly id: string }, b: { readonly id: string }): number {
|
|
|
96
96
|
* Thus two packers with the same result in a different order have the same form.
|
|
97
97
|
* The function throws a `RangeError` when `placements`, `overflow` or `moved` has an id two times.
|
|
98
98
|
*
|
|
99
|
-
* A placement has `w` and `
|
|
99
|
+
* A placement has `w`, `h` and `shape` only when the packer set them, so the form of an output without a resize does not change.
|
|
100
100
|
*/
|
|
101
101
|
export function packOutputForm(output: PackOutput): unknown {
|
|
102
102
|
uniqueIds("placements", output.placements.map((p) => p.id));
|
|
@@ -104,7 +104,7 @@ export function packOutputForm(output: PackOutput): unknown {
|
|
|
104
104
|
uniqueIds("moved", output.moved.map((m) => m.id));
|
|
105
105
|
return {
|
|
106
106
|
placements: output.placements
|
|
107
|
-
.map((p) => ({ id: p.id, x: p.x, y: p.y, turn: p.turn ?? 0, ...(p.w === undefined ? {} : { w: p.w }), ...(p.h === undefined ? {} : { h: p.h }) }))
|
|
107
|
+
.map((p) => ({ id: p.id, x: p.x, y: p.y, turn: p.turn ?? 0, ...(p.w === undefined ? {} : { w: p.w }), ...(p.h === undefined ? {} : { h: p.h }), ...(p.shape === undefined ? {} : { shape: p.shape }) }))
|
|
108
108
|
.sort(byId),
|
|
109
109
|
overflow: [...output.overflow].sort(),
|
|
110
110
|
size: { w: output.size.w, h: output.size.h },
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export * from "./geometry.ts";
|
|
2
|
+
export * from "./curves.ts";
|
|
2
3
|
export * from "./shapes.ts";
|
|
3
4
|
export * from "./tolerance.ts";
|
|
4
5
|
export * from "./input.ts";
|
|
@@ -9,6 +10,7 @@ export * from "./turn.ts";
|
|
|
9
10
|
export * from "./resize.ts";
|
|
10
11
|
export * from "./measures.ts";
|
|
11
12
|
export * from "./balance.ts";
|
|
13
|
+
export * from "./cell.ts";
|
|
12
14
|
export * from "./frame.ts";
|
|
13
15
|
export * from "./strategy.ts";
|
|
14
16
|
export * from "./random.ts";
|
|
@@ -21,3 +23,5 @@ export * from "./strategy-space.ts";
|
|
|
21
23
|
export * from "./strategy-catalog.ts";
|
|
22
24
|
export * from "./verdict.ts";
|
|
23
25
|
export * from "./families.ts";
|
|
26
|
+
export * from "./measure-registry.ts";
|
|
27
|
+
export * from "./measure-survey.ts";
|
package/src/input.ts
CHANGED
|
@@ -51,6 +51,11 @@ export interface Resize {
|
|
|
51
51
|
readonly minH?: number;
|
|
52
52
|
readonly maxH?: number;
|
|
53
53
|
readonly aspect?: "keep" | "free";
|
|
54
|
+
/**
|
|
55
|
+
* With `true`, the placement can give the box a shape (`Placement.shape`), for example the polygon cell of a Voronoi treemap.
|
|
56
|
+
* The bounds of the size also limit the bounds of that shape.
|
|
57
|
+
*/
|
|
58
|
+
readonly reshape?: boolean;
|
|
54
59
|
}
|
|
55
60
|
|
|
56
61
|
/** A box of an input. In the packer, its name is item. */
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { JOINT_MEASURES, type JointMeasureId, type MeasureSpec } from "./measures.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The noise of a measure: the cause of a change of its value when the layout does not change.
|
|
5
|
+
*
|
|
6
|
+
* - `exact`: the value is a function of the layout. Two reads of one layout give the same value.
|
|
7
|
+
* - `sampled`: the value is an estimate from a seeded sample. Another seed gives another value.
|
|
8
|
+
* - `timed`: the value is a time of the machine. Each read gives another value.
|
|
9
|
+
*/
|
|
10
|
+
export type NoiseKind = "exact" | "sampled" | "timed";
|
|
11
|
+
|
|
12
|
+
/** The ids of the noise kinds, in the order of `NoiseKind`. */
|
|
13
|
+
export const NOISE_KINDS: readonly NoiseKind[] = /* @__PURE__ */ Object.freeze(["exact", "sampled", "timed"] as const);
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The rule that maps a value of a measure to a loss from 0 to 1. The loss 0 is the best value. `docs/MEASURE-REGISTRY.md` gives the formulas.
|
|
17
|
+
*
|
|
18
|
+
* - `range`: the share of the range `min` to `max`. Only a measure with a finite `max` has this rule.
|
|
19
|
+
* - `scale`: `d / (d + half)` for the distance `d` from `min`. The loss is 0.5 at `min + half`. A measure with no upper limit uses it.
|
|
20
|
+
* - `none`: no agreed scale. An objective compares two values with `compareMeasure`, or ranks the values of a set. The reason tells why the measure has no scale.
|
|
21
|
+
*
|
|
22
|
+
* The rule `range` needs a finite `min` and `max`. The rule `scale` needs a finite `min`. A measure with no finite range gets the rule `none`, not a guess.
|
|
23
|
+
*/
|
|
24
|
+
export type MeasureNormalize =
|
|
25
|
+
| { readonly kind: "range" }
|
|
26
|
+
| { readonly kind: "scale"; readonly half: number; readonly reason: string }
|
|
27
|
+
| { readonly kind: "none"; readonly reason: string };
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The one unit word of a value from 0 to 1: a share, or a flag of 0 or 1 that a record averages.
|
|
31
|
+
* `checkRegistry` refuses a unit text that names a range, for example `0 to 1`, `0 or 1` or `-1 to 1`. The range goes in `min` and `max`.
|
|
32
|
+
*/
|
|
33
|
+
export const SHARE_UNIT = "share";
|
|
34
|
+
|
|
35
|
+
/** The unit word of a measure with no other unit and a range that is not 0 to 1. An example is a correlation from -1 to 1. */
|
|
36
|
+
export const NO_UNIT = "no unit";
|
|
37
|
+
|
|
38
|
+
/** A unit text that names a range, for example `0 to 1` or `-0.5 to 1`. */
|
|
39
|
+
const RANGE_UNIT = /^-?\d+(?:\.\d+)? (?:to|or) -?\d+(?:\.\d+)?$/;
|
|
40
|
+
/** The other words of a share. */
|
|
41
|
+
const SHARE_WORDS: ReadonlySet<string> = /* @__PURE__ */ new Set(["boolean", "fraction", "proportion"]);
|
|
42
|
+
|
|
43
|
+
/** This function gives the fault of a unit text, or `undefined` for a good unit. */
|
|
44
|
+
export function unitFault(spec: Pick<MeasureSpec, "unit" | "min" | "max">): string | undefined {
|
|
45
|
+
const u = spec.unit;
|
|
46
|
+
if (typeof u !== "string" || u.length === 0) return "the unit is empty";
|
|
47
|
+
if (RANGE_UNIT.test(u)) return `the unit ${JSON.stringify(u)} names a range: use ${JSON.stringify(SHARE_UNIT)} for the range 0 to 1, else ${JSON.stringify(NO_UNIT)}, with the range in min and max`;
|
|
48
|
+
if (SHARE_WORDS.has(u)) return `the unit ${JSON.stringify(u)} is a share: use ${JSON.stringify(SHARE_UNIT)}`;
|
|
49
|
+
if (u === SHARE_UNIT && !(spec.min === 0 && spec.max === 1)) return `the unit ${JSON.stringify(SHARE_UNIT)} needs the range 0 to 1`;
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The cost of one read of a measure, as an order of growth. The text is a sum of terms, for example `n + e^2` or `e log e`.
|
|
55
|
+
* The variables are `n` (the boxes), `e` (the edges) and `p` (the points of the routes). The value `1` is a constant cost.
|
|
56
|
+
*/
|
|
57
|
+
export type CostOrder = string;
|
|
58
|
+
|
|
59
|
+
/** The pattern of a `CostOrder`: terms of `1`, `n`, `e` or `p`, each with an optional `^2`, `^3` or `log`, joined by ` + `. */
|
|
60
|
+
const COST_TERM = "(?:1|[nep](?:\\^[23])?(?: log [nep])?)";
|
|
61
|
+
const COST_ORDER = /* @__PURE__ */ new RegExp(`^${COST_TERM}(?: \\+ ${COST_TERM})*$`);
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* One entry of the measure registry: the spec of the measure, its source package, its noise, its normalization and its cost.
|
|
65
|
+
* The registry extends `MeasureSpec`. Thus a spec of an engine becomes an entry with `measureEntry`.
|
|
66
|
+
*/
|
|
67
|
+
export interface MeasureEntry<Id extends string = string> extends MeasureSpec<Id> {
|
|
68
|
+
/** The npm name of the package that computes the measure. */
|
|
69
|
+
readonly source: string;
|
|
70
|
+
readonly noise: NoiseKind;
|
|
71
|
+
readonly normalize: MeasureNormalize;
|
|
72
|
+
/** The cost of one read of the measure. Without it, the cost is not known. */
|
|
73
|
+
readonly cost?: CostOrder;
|
|
74
|
+
/**
|
|
75
|
+
* The reason that no code computes the measure yet. A planned measure has a spec and no value.
|
|
76
|
+
* An objective refuses a planned measure, and `normalizeMeasure` throws an error for it.
|
|
77
|
+
*/
|
|
78
|
+
readonly planned?: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The facts that `measureEntry` adds to a spec. Without `normalize`, the rule is `range` for a finite range and `none` for the other ranges. */
|
|
82
|
+
export interface EntryFacts {
|
|
83
|
+
readonly source: string;
|
|
84
|
+
readonly noise?: NoiseKind;
|
|
85
|
+
readonly normalize?: MeasureNormalize;
|
|
86
|
+
readonly cost?: CostOrder;
|
|
87
|
+
readonly planned?: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The reason of the default rule `none`. */
|
|
91
|
+
export const NO_FINITE_RANGE = "The range is not finite, and the registry has no agreed scale for the measure.";
|
|
92
|
+
|
|
93
|
+
/** This function gives the default normalization of a spec: `range` when `min` and `max` are finite, else `none` with the reason `NO_FINITE_RANGE`. */
|
|
94
|
+
export function defaultNormalize(spec: Pick<MeasureSpec, "min" | "max">): MeasureNormalize {
|
|
95
|
+
return Number.isFinite(spec.min) && Number.isFinite(spec.max) ? { kind: "range" } : { kind: "none", reason: NO_FINITE_RANGE };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** This function makes a registry entry from a spec and the added facts. The noise is `exact` by default. */
|
|
99
|
+
export function measureEntry<Id extends string>(spec: MeasureSpec<Id>, facts: EntryFacts): MeasureEntry<Id> {
|
|
100
|
+
return Object.freeze({
|
|
101
|
+
...spec,
|
|
102
|
+
source: facts.source,
|
|
103
|
+
noise: facts.noise ?? "exact",
|
|
104
|
+
normalize: facts.normalize ?? defaultNormalize(spec),
|
|
105
|
+
...(facts.cost === undefined ? {} : { cost: facts.cost }),
|
|
106
|
+
...(facts.planned === undefined ? {} : { planned: facts.planned }),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* This function gives the loss of the value `value` of a measure: a number from 0 to 1, where 0 is the best value.
|
|
112
|
+
* A value outside the range of the spec gives a `RangeError`. A value `NaN` also gives a `RangeError`.
|
|
113
|
+
* The rule `none` gives `undefined`: the measure has no agreed scale.
|
|
114
|
+
* A planned measure gives an `Error`: no code computes it, so it has no value.
|
|
115
|
+
*/
|
|
116
|
+
export function normalizeMeasure(value: number, entry: Pick<MeasureEntry, "id" | "direction" | "min" | "max" | "normalize" | "planned">): number | undefined {
|
|
117
|
+
if (entry.planned !== undefined) throw new Error(`normalizeMeasure: ${entry.id} is planned, and no code computes it: ${entry.planned}`);
|
|
118
|
+
if (Number.isNaN(value) || value < entry.min || value > entry.max) throw new RangeError(`normalizeMeasure: the value ${value} of ${entry.id} is not in [${entry.min}, ${entry.max}].`);
|
|
119
|
+
const rule = entry.normalize;
|
|
120
|
+
if (rule.kind === "none") return undefined;
|
|
121
|
+
let worse: number;
|
|
122
|
+
if (rule.kind === "range") {
|
|
123
|
+
const t = entry.max === entry.min ? 0 : (value - entry.min) / (entry.max - entry.min);
|
|
124
|
+
worse = entry.direction === "lower" ? t : 1 - t;
|
|
125
|
+
} else {
|
|
126
|
+
const d = value - entry.min;
|
|
127
|
+
if (d === Infinity) worse = entry.direction === "lower" ? 1 : 0;
|
|
128
|
+
else worse = entry.direction === "lower" ? d / (d + rule.half) : rule.half / (d + rule.half);
|
|
129
|
+
}
|
|
130
|
+
return worse === 0 ? 0 : worse;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* This function gives the faults of a list of registry entries, as plain text. An empty list tells that the entries are good.
|
|
135
|
+
* It examines the unique ids, the unit, the range, the floor, the noise, the normalization, the cost, the source and the planned reason.
|
|
136
|
+
*/
|
|
137
|
+
export function checkRegistry(entries: readonly MeasureEntry[]): string[] {
|
|
138
|
+
const out: string[] = [];
|
|
139
|
+
const seen = new Set<string>();
|
|
140
|
+
for (const e of entries) {
|
|
141
|
+
const at = `measure ${JSON.stringify(e.id)}`;
|
|
142
|
+
if (typeof e.id !== "string" || e.id.length === 0) out.push(`${at}: the id is empty`);
|
|
143
|
+
if (seen.has(e.id)) out.push(`${at}: the id is not unique`);
|
|
144
|
+
seen.add(e.id);
|
|
145
|
+
const unit = unitFault(e);
|
|
146
|
+
if (unit !== undefined) out.push(`${at}: ${unit}`);
|
|
147
|
+
if (e.direction !== "lower" && e.direction !== "higher") out.push(`${at}: the direction is not lower or higher`);
|
|
148
|
+
if (typeof e.min !== "number" || Number.isNaN(e.min) || e.min === Infinity) out.push(`${at}: min is not a number below Infinity`);
|
|
149
|
+
if (!(e.max > e.min)) out.push(`${at}: max is not above min`);
|
|
150
|
+
if (e.floor !== undefined && !(e.floor >= e.min && e.floor <= e.max)) out.push(`${at}: the floor is not in the range`);
|
|
151
|
+
if (typeof e.source !== "string" || e.source.length === 0) out.push(`${at}: the source is empty`);
|
|
152
|
+
if (!NOISE_KINDS.includes(e.noise)) out.push(`${at}: the noise is not one of ${NOISE_KINDS.join(", ")}`);
|
|
153
|
+
if (e.cost !== undefined && !COST_ORDER.test(e.cost)) out.push(`${at}: the cost ${JSON.stringify(e.cost)} is not an order of growth`);
|
|
154
|
+
if (e.planned !== undefined && !(typeof e.planned === "string" && e.planned.length > 0)) out.push(`${at}: the planned reason is empty`);
|
|
155
|
+
if (e.planned !== undefined && e.cost !== undefined) out.push(`${at}: a planned measure has no code, so it has no cost`);
|
|
156
|
+
const n = e.normalize;
|
|
157
|
+
if (n === undefined || (n.kind !== "range" && n.kind !== "scale" && n.kind !== "none")) out.push(`${at}: the normalization is not range, scale or none`);
|
|
158
|
+
else if (n.kind === "range" && !(Number.isFinite(e.min) && Number.isFinite(e.max))) out.push(`${at}: the normalization range needs a finite min and max`);
|
|
159
|
+
else if (n.kind === "scale" && !Number.isFinite(e.min)) out.push(`${at}: the normalization scale needs a finite min`);
|
|
160
|
+
else if (n.kind === "scale" && !(Number.isFinite(n.half) && n.half > 0)) out.push(`${at}: the half of the normalization scale is not above 0`);
|
|
161
|
+
else if (n.kind === "scale" && !(typeof n.reason === "string" && n.reason.length > 0)) out.push(`${at}: the normalization scale has no reason`);
|
|
162
|
+
else if (n.kind === "none" && !(typeof n.reason === "string" && n.reason.length > 0)) out.push(`${at}: the normalization none has no reason`);
|
|
163
|
+
}
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The package of the joint bench. It is private, so the joint measures have no npm version. */
|
|
168
|
+
export const JOINT_SOURCE = "@layout-contract/joint";
|
|
169
|
+
|
|
170
|
+
/** The planned reason of the two joint stability measures. */
|
|
171
|
+
const NO_CHANGE_PAIRS = "The joint bench has no pairs of a base input and a changed input, so no code computes the measure.";
|
|
172
|
+
|
|
173
|
+
const JOINT_FACTS: Readonly<Record<JointMeasureId, Omit<EntryFacts, "source">>> = {
|
|
174
|
+
"joint.fill": { cost: "n + p" },
|
|
175
|
+
"joint.aspectError": { cost: "n + p", normalize: { kind: "scale", half: Math.LN2, reason: "An aspect at a factor of 2 from the target has the loss 0.5." } },
|
|
176
|
+
"joint.spill": { cost: "n + p" },
|
|
177
|
+
"joint.straight.crossings": { cost: "n + e^2", normalize: { kind: "none", reason: "A count of crossings has no agreed scale." } },
|
|
178
|
+
"joint.straight.length": { cost: "n + e", normalize: { kind: "scale", half: 1, reason: "An edge as long as the side S of the square of the box area has the loss 0.5." } },
|
|
179
|
+
"joint.stability.mean": { planned: NO_CHANGE_PAIRS },
|
|
180
|
+
"joint.stability.moved": { planned: NO_CHANGE_PAIRS },
|
|
181
|
+
"joint.proxy.rank": { cost: "n + p + e log e" },
|
|
182
|
+
"joint.route.length": { cost: "p", normalize: { kind: "none", reason: "A length in layout units has no agreed scale." } },
|
|
183
|
+
"joint.ms": { noise: "timed", normalize: { kind: "none", reason: "A time of the machine has no agreed scale, and each read gives another value." } },
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The registry entries of the joint measures, in the order of `JOINT_MEASURES`. `docs/MEASURE-REGISTRY.md` gives the reason of each cost and scale.
|
|
188
|
+
* The engines keep the specs of their own measures. `docs/measure-survey.json` lists them, and an engine adopts the registry with `measureEntry`.
|
|
189
|
+
*/
|
|
190
|
+
export const MEASURE_REGISTRY: readonly MeasureEntry<JointMeasureId>[] = /* @__PURE__ */ Object.freeze(
|
|
191
|
+
JOINT_MEASURES.map((spec) => measureEntry(spec, { source: JOINT_SOURCE, ...JOINT_FACTS[spec.id] })),
|
|
192
|
+
);
|