@altnovatrail/picture-kit 0.0.0-stage → 0.1.1

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.
Files changed (122) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +7 -0
  3. package/README.md +28 -2
  4. package/lib/emoji.d.ts +16 -0
  5. package/lib/emoji.js +64 -0
  6. package/lib/index.d.ts +9 -0
  7. package/lib/index.js +10 -0
  8. package/lib/kind.d.ts +22 -0
  9. package/lib/kind.js +2 -0
  10. package/lib/kinds/balance.d.ts +34 -0
  11. package/lib/kinds/balance.js +217 -0
  12. package/lib/kinds/branches.d.ts +33 -0
  13. package/lib/kinds/branches.js +473 -0
  14. package/lib/kinds/calendar.d.ts +55 -0
  15. package/lib/kinds/calendar.js +532 -0
  16. package/lib/kinds/chart.d.ts +48 -0
  17. package/lib/kinds/chart.js +645 -0
  18. package/lib/kinds/choices.d.ts +14 -0
  19. package/lib/kinds/choices.js +53 -0
  20. package/lib/kinds/clock.d.ts +36 -0
  21. package/lib/kinds/clock.js +219 -0
  22. package/lib/kinds/coins.d.ts +37 -0
  23. package/lib/kinds/coins.js +550 -0
  24. package/lib/kinds/column.d.ts +37 -0
  25. package/lib/kinds/column.js +410 -0
  26. package/lib/kinds/commands-parts.d.ts +12 -0
  27. package/lib/kinds/commands-parts.js +24 -0
  28. package/lib/kinds/commands.d.ts +66 -0
  29. package/lib/kinds/commands.js +789 -0
  30. package/lib/kinds/containers.d.ts +52 -0
  31. package/lib/kinds/containers.js +758 -0
  32. package/lib/kinds/countfig.d.ts +41 -0
  33. package/lib/kinds/countfig.js +372 -0
  34. package/lib/kinds/cubes.d.ts +70 -0
  35. package/lib/kinds/cubes.js +371 -0
  36. package/lib/kinds/die.d.ts +32 -0
  37. package/lib/kinds/die.js +301 -0
  38. package/lib/kinds/domino.d.ts +37 -0
  39. package/lib/kinds/domino.js +450 -0
  40. package/lib/kinds/dotgrid.d.ts +38 -0
  41. package/lib/kinds/dotgrid.js +411 -0
  42. package/lib/kinds/figure.d.ts +62 -0
  43. package/lib/kinds/figure.js +687 -0
  44. package/lib/kinds/fold-parts.d.ts +73 -0
  45. package/lib/kinds/fold-parts.js +315 -0
  46. package/lib/kinds/fold.d.ts +52 -0
  47. package/lib/kinds/fold.js +650 -0
  48. package/lib/kinds/fraction.d.ts +50 -0
  49. package/lib/kinds/fraction.js +568 -0
  50. package/lib/kinds/gauges.d.ts +53 -0
  51. package/lib/kinds/gauges.js +880 -0
  52. package/lib/kinds/gears.d.ts +40 -0
  53. package/lib/kinds/gears.js +787 -0
  54. package/lib/kinds/grid.d.ts +45 -0
  55. package/lib/kinds/grid.js +591 -0
  56. package/lib/kinds/groups.d.ts +23 -0
  57. package/lib/kinds/groups.js +335 -0
  58. package/lib/kinds/index.d.ts +3 -0
  59. package/lib/kinds/index.js +87 -0
  60. package/lib/kinds/lanes.d.ts +36 -0
  61. package/lib/kinds/lanes.js +220 -0
  62. package/lib/kinds/layers.d.ts +31 -0
  63. package/lib/kinds/layers.js +419 -0
  64. package/lib/kinds/line.d.ts +38 -0
  65. package/lib/kinds/line.js +739 -0
  66. package/lib/kinds/magic-parts.d.ts +72 -0
  67. package/lib/kinds/magic-parts.js +186 -0
  68. package/lib/kinds/magic.d.ts +66 -0
  69. package/lib/kinds/magic.js +664 -0
  70. package/lib/kinds/map.d.ts +32 -0
  71. package/lib/kinds/map.js +370 -0
  72. package/lib/kinds/matchsticks.d.ts +26 -0
  73. package/lib/kinds/matchsticks.js +434 -0
  74. package/lib/kinds/necklace.d.ts +27 -0
  75. package/lib/kinds/necklace.js +342 -0
  76. package/lib/kinds/net.d.ts +47 -0
  77. package/lib/kinds/net.js +241 -0
  78. package/lib/kinds/overlay.d.ts +50 -0
  79. package/lib/kinds/overlay.js +519 -0
  80. package/lib/kinds/pieces.d.ts +41 -0
  81. package/lib/kinds/pieces.js +420 -0
  82. package/lib/kinds/pipes.d.ts +46 -0
  83. package/lib/kinds/pipes.js +657 -0
  84. package/lib/kinds/plane-parts.d.ts +105 -0
  85. package/lib/kinds/plane-parts.js +372 -0
  86. package/lib/kinds/plane.d.ts +35 -0
  87. package/lib/kinds/plane.js +755 -0
  88. package/lib/kinds/pyramid.d.ts +26 -0
  89. package/lib/kinds/pyramid.js +228 -0
  90. package/lib/kinds/ropes.d.ts +30 -0
  91. package/lib/kinds/ropes.js +571 -0
  92. package/lib/kinds/shapes.d.ts +59 -0
  93. package/lib/kinds/shapes.js +490 -0
  94. package/lib/kinds/solids.d.ts +78 -0
  95. package/lib/kinds/solids.js +1058 -0
  96. package/lib/kinds/tangram.d.ts +52 -0
  97. package/lib/kinds/tangram.js +713 -0
  98. package/lib/kinds/target.d.ts +39 -0
  99. package/lib/kinds/target.js +761 -0
  100. package/lib/kinds/tiles.d.ts +55 -0
  101. package/lib/kinds/tiles.js +606 -0
  102. package/lib/kinds/venn.d.ts +38 -0
  103. package/lib/kinds/venn.js +710 -0
  104. package/lib/noto.d.ts +2 -0
  105. package/lib/noto.js +212 -0
  106. package/lib/objects.d.ts +7 -0
  107. package/lib/objects.js +226 -0
  108. package/lib/pen.d.ts +32 -0
  109. package/lib/pen.js +60 -0
  110. package/lib/read.d.ts +9 -0
  111. package/lib/read.js +49 -0
  112. package/lib/render.d.ts +24 -0
  113. package/lib/render.js +68 -0
  114. package/lib/solve/balance.d.ts +46 -0
  115. package/lib/solve/balance.js +118 -0
  116. package/lib/style.d.ts +70 -0
  117. package/lib/style.js +39 -0
  118. package/lib/svg.d.ts +22 -0
  119. package/lib/svg.js +48 -0
  120. package/lib/things.d.ts +40 -0
  121. package/lib/things.js +269 -0
  122. package/package.json +28 -4
@@ -0,0 +1,755 @@
1
+ import { margin } from "../kind.js";
2
+ import { textWidth } from "../pen.js";
3
+ import { int, isObj, list, only, text } from "../read.js";
4
+ import { colorNames, colors, ink, isColor, outline, textOn } from "../style.js";
5
+ import { n, poly } from "../svg.js";
6
+ import { area, around, boxAt, boxToSegment, capital, centroid, crossing, distance, label as drawLabel, edgesOf, gap, inside, labelSize, lerp, listOf, meet, overlap, pointOf, say, } from "./plane-parts.js";
7
+ const span = 40;
8
+ const sideSize = 18;
9
+ const angleSize = 16;
10
+ const letterSize = 18;
11
+ const insideSize = 18;
12
+ const arcFirst = 17;
13
+ const arcStep = 5;
14
+ const rightSize = 12;
15
+ const tickHalf = 7;
16
+ const names = /^[A-Z][0-9]?$/;
17
+ const lengthUnits = { mm: 1, cm: 10, dm: 100, m: 1000, km: 1000000 };
18
+ /** A length a label says: a number and a unit, or a bare number. */
19
+ function lengthOf(label) {
20
+ const m = /^(\d+(?:[.,]\d+)?)\s*(mm|cm|dm|m|km)?$/.exec(label);
21
+ return m ? { value: Number(m[1].replace(",", ".")), unit: m[2] ?? "" } : undefined;
22
+ }
23
+ /** The size in degrees an angle's label says, as "40°". */
24
+ function degreesOf(label) {
25
+ const m = /^(\d+(?:[.,]\d+)?)°$/.exec(label);
26
+ return m ? Number(m[1].replace(",", ".")) : undefined;
27
+ }
28
+ const unitVector = (a, b) => {
29
+ const d = distance(a, b);
30
+ return { x: (b.x - a.x) / d, y: (b.y - a.y) / d };
31
+ };
32
+ /** cornerOf is the corner k of a polygon: its two sides as unit vectors and its inside angle. */
33
+ function cornerOf(polygon, k) {
34
+ const K = polygon.length;
35
+ const c = polygon[k];
36
+ const u = unitVector(c, polygon[(k + K - 1) % K]);
37
+ const v = unitVector(c, polygon[(k + 1) % K]);
38
+ const sum = { x: u.x + v.x, y: u.y + v.y };
39
+ const len = Math.hypot(sum.x, sum.y);
40
+ const small = (Math.acos(Math.max(-1, Math.min(1, u.x * v.x + u.y * v.y))) * 180) / Math.PI;
41
+ if (len < 1e-9)
42
+ return { c, u, v, theta: 180, convex: false, bisector: { x: -u.y, y: u.x } };
43
+ const b = { x: sum.x / len, y: sum.y / len };
44
+ const probe = { x: c.x + b.x * 0.5, y: c.y + b.y * 0.5 };
45
+ const convex = inside(probe, polygon);
46
+ return {
47
+ c,
48
+ u,
49
+ v,
50
+ theta: convex ? small : 360 - small,
51
+ convex,
52
+ bisector: convex ? b : { x: -b.x, y: -b.y },
53
+ };
54
+ }
55
+ /** unitOf is how many pixels a unit of the scene takes: the figure fits 500 × 330. */
56
+ function unitOf(s) {
57
+ const all = s.shapes.flatMap((sh) => sh.corners);
58
+ const xs = all.map((c) => c[0]);
59
+ const ys = all.map((c) => c[1]);
60
+ const w = Math.max(...xs) - Math.min(...xs);
61
+ const h = Math.max(...ys) - Math.min(...ys);
62
+ const unit = Math.min(48, w > 0 ? 500 / w : 48, h > 0 ? 330 / h : 48);
63
+ return { unit, x0: Math.min(...xs), y0: Math.min(...ys) };
64
+ }
65
+ /**
66
+ * layout places every mark and label of a checked scene, each where it
67
+ * covers nothing drawn before it: the angle marks, the ticks, the sides'
68
+ * labels, the angles' labels, the letters and the texts inside. What finds
69
+ * no place is a problem, with its path.
70
+ */
71
+ function layout(s) {
72
+ const { unit, x0, y0 } = unitOf(s);
73
+ const polys = s.shapes.map((sh) => sh.corners.map(([x, y]) => ({ x: (x - x0) * unit, y: (y - y0) * unit })));
74
+ const out = {
75
+ unit,
76
+ polys,
77
+ ticks: [],
78
+ arcs: [],
79
+ rights: [],
80
+ labels: [],
81
+ problems: [],
82
+ box: { x0: 0, y0: 0, x1: 0, y1: 0 },
83
+ };
84
+ const lines = polys.flatMap((p) => edgesOf(p));
85
+ // The marks of angles, as short straight pieces, and how far each reaches from its corner.
86
+ const marks = [];
87
+ const reachOf = new Map();
88
+ const taken = [];
89
+ const clear = (box) => Math.min(...lines.map(([a, b]) => boxToSegment(box, a, b) - outline / 2), ...out.ticks.map(([a, b]) => boxToSegment(box, a, b) - 1), ...marks.map(([a, b]) => boxToSegment(box, a, b) - 1), ...taken.map((t) => gap(box, t)));
90
+ const put = (path, words, at, size, fill = ink) => {
91
+ if (!at) {
92
+ out.problems.push(path);
93
+ return;
94
+ }
95
+ const { w, h } = labelSize(words, size);
96
+ taken.push(boxAt(at, w, h));
97
+ out.labels.push({ text: words, at, size, fill });
98
+ };
99
+ // Angle marks first: they sit tight in their corners.
100
+ s.shapes.forEach((sh, i) => {
101
+ sh.angles?.forEach((m, k) => {
102
+ if (!m)
103
+ return;
104
+ const { c, u, v } = cornerOf(polys[i], k);
105
+ if (m.right) {
106
+ const a = { x: c.x + u.x * rightSize, y: c.y + u.y * rightSize };
107
+ const b = { x: a.x + v.x * rightSize, y: a.y + v.y * rightSize };
108
+ const e = { x: c.x + v.x * rightSize, y: c.y + v.y * rightSize };
109
+ out.rights.push(poly([a, b, e], false));
110
+ marks.push([a, b], [b, e]);
111
+ reachOf.set(`${i},${k}`, rightSize * Math.SQRT2);
112
+ return;
113
+ }
114
+ const count = m.arcs ?? 1;
115
+ const sweep = u.x * v.y - u.y * v.x > 0 ? 1 : 0;
116
+ for (let j = 0; j < count; j++) {
117
+ const r = arcFirst + j * arcStep;
118
+ const a = { x: c.x + u.x * r, y: c.y + u.y * r };
119
+ const b = { x: c.x + v.x * r, y: c.y + v.y * r };
120
+ out.arcs.push(`M${n(a.x)} ${n(a.y)}A${n(r)} ${n(r)} 0 0 ${sweep} ${n(b.x)} ${n(b.y)}`);
121
+ // The arc, for what must keep clear of it: pieces of a tenth of it each.
122
+ const turn = Math.acos(Math.max(-1, Math.min(1, u.x * v.x + u.y * v.y)));
123
+ const from = Math.atan2(u.y, u.x);
124
+ const dir = sweep === 1 ? 1 : -1;
125
+ for (let t = 0; t < 10; t++) {
126
+ const a0 = from + (dir * turn * t) / 10;
127
+ const a1 = from + (dir * turn * (t + 1)) / 10;
128
+ marks.push([
129
+ { x: c.x + r * Math.cos(a0), y: c.y + r * Math.sin(a0) },
130
+ { x: c.x + r * Math.cos(a1), y: c.y + r * Math.sin(a1) },
131
+ ]);
132
+ }
133
+ }
134
+ reachOf.set(`${i},${k}`, arcFirst + (count - 1) * arcStep);
135
+ });
136
+ });
137
+ s.shapes.forEach((sh, i) => {
138
+ const p = polys[i];
139
+ sh.sides?.forEach((m, k) => {
140
+ if (!m?.ticks)
141
+ return;
142
+ const a = p[k];
143
+ const b = p[(k + 1) % p.length];
144
+ const d = unitVector(a, b);
145
+ const mid = lerp(a, b, 0.5);
146
+ for (let j = 0; j < m.ticks; j++) {
147
+ const t = (j - (m.ticks - 1) / 2) * 5;
148
+ const at = { x: mid.x + d.x * t, y: mid.y + d.y * t };
149
+ out.ticks.push([
150
+ { x: at.x - d.y * tickHalf, y: at.y + d.x * tickHalf },
151
+ { x: at.x + d.y * tickHalf, y: at.y - d.x * tickHalf },
152
+ ]);
153
+ }
154
+ });
155
+ });
156
+ s.shapes.forEach((sh, i) => {
157
+ const p = polys[i];
158
+ sh.sides?.forEach((m, k) => {
159
+ if (!m?.label)
160
+ return;
161
+ const a = p[k];
162
+ const b = p[(k + 1) % p.length];
163
+ const d = unitVector(a, b);
164
+ const mid = lerp(a, b, 0.5);
165
+ let normal = { x: d.y, y: -d.x };
166
+ if (inside({ x: mid.x + normal.x, y: mid.y + normal.y }, p))
167
+ normal = { x: -normal.x, y: -normal.y };
168
+ const { w, h } = labelSize(m.label, sideSize);
169
+ const reach = (m.ticks ? 10 : 6) + Math.abs(normal.x) * (w / 2) + Math.abs(normal.y) * (h / 2);
170
+ let at;
171
+ for (const side of [1, -1]) {
172
+ const spot = { x: mid.x + normal.x * side * reach, y: mid.y + normal.y * side * reach };
173
+ if (clear(boxAt(spot, w, h)) >= 3) {
174
+ at = spot;
175
+ break;
176
+ }
177
+ }
178
+ put(`shapes[${i}].sides[${k}].label: no room for "${m.label}" beside its side; make the side longer or move what crowds it`, m.label, at, sideSize);
179
+ });
180
+ });
181
+ s.shapes.forEach((sh, i) => {
182
+ const p = polys[i];
183
+ sh.angles?.forEach((m, k) => {
184
+ if (!m?.label)
185
+ return;
186
+ const { c, bisector } = cornerOf(p, k);
187
+ const { w, h } = labelSize(m.label, angleSize);
188
+ const reach = Math.min(Math.abs(bisector.x) > 1e-9 ? w / 2 / Math.abs(bisector.x) : 1e9, Math.abs(bisector.y) > 1e-9 ? h / 2 / Math.abs(bisector.y) : 1e9);
189
+ let at;
190
+ for (let d = (reachOf.get(`${i},${k}`) ?? 0) + 4; d <= 100 && !at; d += 2) {
191
+ const spot = { x: c.x + bisector.x * (d + reach), y: c.y + bisector.y * (d + reach) };
192
+ if (inside(spot, p) && clear(boxAt(spot, w, h)) >= 2.5)
193
+ at = spot;
194
+ }
195
+ put(`shapes[${i}].angles[${k}].label: no room for "${m.label}" inside its angle; make the sides near it longer`, m.label, at, angleSize);
196
+ });
197
+ });
198
+ const lettered = new Map();
199
+ s.shapes.forEach((sh, i) => {
200
+ const p = polys[i];
201
+ sh.letters?.forEach((letter, k) => {
202
+ const key = `${n(p[k].x)},${n(p[k].y)}`;
203
+ if (lettered.get(key) === letter)
204
+ return;
205
+ lettered.set(key, letter);
206
+ const { c, bisector } = cornerOf(p, k);
207
+ const w = textWidth(letter, letterSize) + 2;
208
+ const h = letterSize * 0.78;
209
+ const prefer = Math.atan2(-bisector.y, -bisector.x);
210
+ const outside = (box) => {
211
+ const mid = { x: (box.x0 + box.x1) / 2, y: (box.y0 + box.y1) / 2 };
212
+ return polys.some((q) => inside(mid, q)) ? -1 : clear(box);
213
+ };
214
+ let spot = around(c, w, h, prefer, outside, 5, [4, 7, 11]);
215
+ if (spot.clear < 3)
216
+ spot = around(c, w, h, prefer, clear, 5, [4, 7, 11]);
217
+ // At a corner that shapes close all round, as the centre of a hexagon
218
+ // cut into triangles, the letter stands further into the clearest angle.
219
+ if (spot.clear < 2)
220
+ spot = around(c, w, h, prefer, clear, 4, [16, 21, 26]);
221
+ put(`shapes[${i}].letters[${k}]: no room for the letter ${letter} beside its corner; move the marks near it`, letter, spot.clear >= 2 ? spot.at : undefined, letterSize);
222
+ });
223
+ });
224
+ s.shapes.forEach((sh, i) => {
225
+ if (!sh.label)
226
+ return;
227
+ const p = polys[i];
228
+ const { w, h } = labelSize(sh.label, insideSize);
229
+ const bw = w + 8;
230
+ const bh = h + 6;
231
+ const middle = centroid(p);
232
+ const xs = p.map((q) => q.x);
233
+ const ys = p.map((q) => q.y);
234
+ let best;
235
+ for (let y = Math.min(...ys) + bh / 2; y <= Math.max(...ys) - bh / 2; y += 3)
236
+ for (let x = Math.min(...xs) + bw / 2; x <= Math.max(...xs) - bw / 2; x += 3) {
237
+ const at = { x, y };
238
+ const box = boxAt(at, bw, bh);
239
+ const corners = [
240
+ { x: box.x0, y: box.y0 },
241
+ { x: box.x1, y: box.y0 },
242
+ { x: box.x1, y: box.y1 },
243
+ { x: box.x0, y: box.y1 },
244
+ ];
245
+ if (!corners.every((q) => inside(q, p)))
246
+ continue;
247
+ const score = Math.round(clear(box) * 10) / 10;
248
+ if (score < 1)
249
+ continue;
250
+ const far = Math.round(distance(at, middle) * 10) / 10;
251
+ if (!best || score > best.score + 4 || (score > best.score - 4 && far < best.far))
252
+ best = { at, score, far };
253
+ }
254
+ put(`shapes[${i}].label: no room for "${sh.label}" inside the shape; make it shorter or the shape larger`, sh.label, best?.at, insideSize, textOn(sh.color ?? "white"));
255
+ });
256
+ const box = {
257
+ x0: Math.min(...polys.flat().map((q) => q.x)) - outline,
258
+ y0: Math.min(...polys.flat().map((q) => q.y)) - outline,
259
+ x1: Math.max(...polys.flat().map((q) => q.x)) + outline,
260
+ y1: Math.max(...polys.flat().map((q) => q.y)) + outline,
261
+ };
262
+ for (const t of taken) {
263
+ box.x0 = Math.min(box.x0, t.x0);
264
+ box.y0 = Math.min(box.y0, t.y0);
265
+ box.x1 = Math.max(box.x1, t.x1);
266
+ box.y1 = Math.max(box.y1, t.y1);
267
+ }
268
+ out.box = box;
269
+ return out;
270
+ }
271
+ /** heading says which way a side goes on the picture. */
272
+ function heading(a, b) {
273
+ const angle = (Math.atan2(a.y - b.y, b.x - a.x) * 180) / Math.PI;
274
+ const near = (to) => Math.abs(angle - to) <= 7.5;
275
+ if (near(0))
276
+ return "right";
277
+ if (near(90))
278
+ return "up";
279
+ if (near(-90))
280
+ return "down";
281
+ if (near(180) || near(-180))
282
+ return "left";
283
+ if (angle > 0)
284
+ return angle < 90 ? "up and to the right" : "up and to the left";
285
+ return angle > -90 ? "down and to the right" : "down and to the left";
286
+ }
287
+ /** where says where a point lies in a box: "top left", "bottom", "middle". */
288
+ function where(p, box) {
289
+ const col = (p.x - box.x0) / Math.max(1e-9, box.x1 - box.x0);
290
+ const row = (p.y - box.y0) / Math.max(1e-9, box.y1 - box.y0);
291
+ const v = row < 0.34 ? "top" : row > 0.66 ? "bottom" : "";
292
+ const h = col < 0.34 ? "left" : col > 0.66 ? "right" : "";
293
+ return [v, h].filter(Boolean).join(" ") || "middle";
294
+ }
295
+ function corners(sh) {
296
+ return sh.corners.map(([x, y]) => ({ x, y }));
297
+ }
298
+ function boxOf(points) {
299
+ return {
300
+ x0: Math.min(...points.map((q) => q.x)),
301
+ y0: Math.min(...points.map((q) => q.y)),
302
+ x1: Math.max(...points.map((q) => q.x)),
303
+ y1: Math.max(...points.map((q) => q.y)),
304
+ };
305
+ }
306
+ /** isRectangle tells a shape of four sides that run across and up and down. */
307
+ function isRectangle(p) {
308
+ return (p.length === 4 && p.every((a, k) => a.x === p[(k + 1) % 4].x || a.y === p[(k + 1) % 4].y));
309
+ }
310
+ /** kindOf names a shape as it is drawn: a triangle, a rectangle, a square, a shape with k sides. */
311
+ function kindOf(sh, p) {
312
+ if (p.length === 3)
313
+ return "triangle";
314
+ if (!isRectangle(p))
315
+ return `shape with ${p.length} sides`;
316
+ const w = Math.abs(p[0].x - p[2].x);
317
+ const h = Math.abs(p[0].y - p[2].y);
318
+ // A square as drawn, unless its labels say two different lengths.
319
+ const lengths = (sh.sides ?? [])
320
+ .map((m) => (m?.label === undefined ? undefined : lengthOf(m.label)))
321
+ .filter((l) => l !== undefined)
322
+ .map((l) => l.value * (lengthUnits[l.unit] ?? 1));
323
+ const differ = lengths.some((v) => Math.abs(v - lengths[0]) > 1e-9);
324
+ return Math.abs(w - h) < 1e-9 && !differ ? "square" : "rectangle";
325
+ }
326
+ const counts = ["no", "one", "two", "three"];
327
+ const countWord = (k) => counts[k] ?? String(k);
328
+ const article = (word) => (/^[aeiou]/.test(word) ? "an" : "a");
329
+ const placeWords = (at) => (at === "middle" ? "in the middle" : `at the ${at}`);
330
+ export const plane = {
331
+ kind: "plane",
332
+ members: ["kind", "shapes"],
333
+ check(scene, problems) {
334
+ only(scene, this.members, "scene", problems);
335
+ const before = problems.length;
336
+ list(scene.shapes, "shapes", problems, 1, 6).forEach((sh, i) => {
337
+ const path = `shapes[${i}]`;
338
+ if (!isObj(sh)) {
339
+ problems.push(`${path}: must be a shape, as {"corners": [[0, 0], [4, 0], [0, 3]]}`);
340
+ return;
341
+ }
342
+ only(sh, ["corners", "color", "letters", "sides", "angles", "label"], path, problems);
343
+ const cs = list(sh.corners, `${path}.corners`, problems, 3, 12);
344
+ cs.forEach((c, k) => {
345
+ pointOf(c, `${path}.corners[${k}]`, problems, [span, span], 2);
346
+ });
347
+ const K = cs.length;
348
+ if (sh.color !== undefined && !isColor(sh.color))
349
+ problems.push(`${path}.color: must be a colour: ${colorNames.join(", ")}`);
350
+ const each = (member, what, read) => {
351
+ const v = sh[member];
352
+ if (v === undefined)
353
+ return;
354
+ const items = list(v, `${path}.${member}`, problems, 0);
355
+ if (Array.isArray(v) && items.length !== K)
356
+ problems.push(`${path}.${member}: must hold one entry for each ${what}, ${K}: null for one with no marks`);
357
+ items.forEach((m, k) => {
358
+ const at = `${path}.${member}[${k}]`;
359
+ if (m === null)
360
+ return;
361
+ if (!isObj(m)) {
362
+ problems.push(`${at}: must be null or the marks of the ${what}`);
363
+ return;
364
+ }
365
+ read(m, at);
366
+ });
367
+ };
368
+ each("sides", "side", (m, at) => {
369
+ only(m, ["label", "ticks"], at, problems);
370
+ if (m.label === undefined && m.ticks === undefined)
371
+ problems.push(`${at}: give a label, ticks or both; null for a side with no marks`);
372
+ if (m.label !== undefined)
373
+ text(m.label, `${at}.label`, problems, 8);
374
+ if (m.ticks !== undefined)
375
+ int(m.ticks, `${at}.ticks`, problems, 1, 3);
376
+ });
377
+ each("angles", "corner", (m, at) => {
378
+ only(m, ["right", "arcs", "label"], at, problems);
379
+ if (m.right !== undefined && m.right !== true)
380
+ problems.push(`${at}.right: must be true`);
381
+ if (m.right !== undefined && m.arcs !== undefined)
382
+ problems.push(`${at}: a right angle has its square mark, not arcs`);
383
+ if (m.right === undefined && m.arcs === undefined && m.label === undefined)
384
+ problems.push(`${at}: give right, arcs or a label; null for a corner with no marks`);
385
+ if (m.arcs !== undefined)
386
+ int(m.arcs, `${at}.arcs`, problems, 1, 3);
387
+ if (m.label !== undefined)
388
+ text(m.label, `${at}.label`, problems, 5);
389
+ });
390
+ if (sh.letters !== undefined) {
391
+ const letters = list(sh.letters, `${path}.letters`, problems, 0);
392
+ if (Array.isArray(sh.letters) && letters.length !== K)
393
+ problems.push(`${path}.letters: must hold one letter for each corner, ${K}`);
394
+ letters.forEach((l, k) => {
395
+ if (typeof l !== "string" || !names.test(l))
396
+ problems.push(`${path}.letters[${k}]: must be a capital letter, maybe with one digit after it`);
397
+ });
398
+ }
399
+ if (sh.label !== undefined)
400
+ text(sh.label, `${path}.label`, problems, 10);
401
+ });
402
+ if (problems.length > before)
403
+ return;
404
+ const s = scene;
405
+ const { unit } = unitOf(s);
406
+ const shapes = s.shapes.map(corners);
407
+ s.shapes.forEach((_, i) => {
408
+ const p = shapes[i];
409
+ const K = p.length;
410
+ for (let k = 0; k < K; k++) {
411
+ const len = distance(p[k], p[(k + 1) % K]) * unit;
412
+ if (len < 24)
413
+ problems.push(`shapes[${i}].corners[${(k + 1) % K}]: the side from corners[${k}] is too short to draw; make it at least ${say(24 / unit)} long`);
414
+ }
415
+ if (problems.length > before)
416
+ return;
417
+ const cross = crossing(p, 1e-6);
418
+ if (cross)
419
+ problems.push(`shapes[${i}].corners: the side from corners[${cross[0]}] and the side from corners[${cross[1]}] cross or touch; list the corners in order round the shape`);
420
+ else if (area(p) * unit * unit < 400)
421
+ problems.push(`shapes[${i}].corners: the shape is too thin to draw`);
422
+ });
423
+ if (problems.length > before)
424
+ return;
425
+ shapes.forEach((p, i) => {
426
+ for (let j = 0; j < i; j++)
427
+ if (overlap(p, shapes[j]))
428
+ problems.push(`shapes[${i}]: overlaps shapes[${j}]; shapes of a figure may touch along their sides, not cover each other`);
429
+ });
430
+ const letterAt = new Map();
431
+ const placeOf = new Map();
432
+ s.shapes.forEach((sh, i) => {
433
+ sh.letters?.forEach((l, k) => {
434
+ const key = `${sh.corners[k][0]},${sh.corners[k][1]}`;
435
+ const had = letterAt.get(key);
436
+ if (had !== undefined && had !== l)
437
+ problems.push(`shapes[${i}].letters[${k}]: the corner is lettered ${had} already`);
438
+ const where_ = placeOf.get(l);
439
+ if (where_ !== undefined && where_ !== key)
440
+ problems.push(`shapes[${i}].letters[${k}]: ${l} names another corner already`);
441
+ letterAt.set(key, l);
442
+ placeOf.set(l, key);
443
+ });
444
+ });
445
+ if (problems.length > before)
446
+ return;
447
+ // Marks of angles stand on the angles they name.
448
+ const sizes = [];
449
+ s.shapes.forEach((sh, i) => {
450
+ sh.angles?.forEach((m, k) => {
451
+ if (!m)
452
+ return;
453
+ const at = `shapes[${i}].angles[${k}]`;
454
+ const { theta } = cornerOf(shapes[i], k);
455
+ if (theta >= 179.5) {
456
+ problems.push(`${at}: the angle there is ${say(theta)}°, not less than a straight angle; mark only angles under 180°`);
457
+ return;
458
+ }
459
+ if (m.right && Math.abs(theta - 90) > 1)
460
+ problems.push(`${at}.right: the angle is drawn ${say(theta)}°, not a right angle`);
461
+ const degrees = m.label === undefined ? undefined : degreesOf(m.label);
462
+ if (degrees !== undefined && Math.abs(degrees - theta) > 20)
463
+ problems.push(`${at}.label: says ${m.label}, but the angle is drawn ${say(theta)}°; draw it closer to its size`);
464
+ if (m.arcs !== undefined && m.arcs > 1)
465
+ sizes.push({ at, theta, arcs: m.arcs });
466
+ });
467
+ });
468
+ for (const a of sizes)
469
+ for (const b of sizes)
470
+ if (a.at < b.at && a.arcs === b.arcs && Math.abs(a.theta - b.theta) > 2)
471
+ problems.push(`${b.at}.arcs: angles with ${a.arcs} arcs are equal, but this one is drawn ${say(b.theta)}° and ${a.at} ${say(a.theta)}°`);
472
+ // The angles of a shape add up as they must.
473
+ s.shapes.forEach((sh, i) => {
474
+ if (!sh.angles)
475
+ return;
476
+ const K = sh.corners.length;
477
+ const total = (K - 2) * 180;
478
+ let known = 0;
479
+ let unknown = 0;
480
+ sh.angles.forEach((m) => {
481
+ const d = m?.right ? 90 : m?.label === undefined ? undefined : degreesOf(m.label);
482
+ if (d === undefined)
483
+ unknown++;
484
+ else
485
+ known += d;
486
+ });
487
+ if (unknown === 0 && Math.abs(known - total) > 0.5)
488
+ problems.push(`shapes[${i}].angles: they add up to ${say(known)}°, but the angles of a shape with ${K} corners add up to ${total}°`);
489
+ else if (unknown > 0 && known >= total)
490
+ problems.push(`shapes[${i}].angles: the marked ones add up to ${say(known)}° already, and all ${K} angles add up to ${total}°`);
491
+ });
492
+ const sides = [];
493
+ s.shapes.forEach((sh, i) => {
494
+ const p = shapes[i];
495
+ p.forEach((a, k) => {
496
+ const b = p[(k + 1) % p.length];
497
+ const m = sh.sides?.[k] ?? undefined;
498
+ const side = { at: `shapes[${i}].sides[${k}]`, len: distance(a, b), from: a, to: b };
499
+ if (m?.label !== undefined)
500
+ side.label = m.label;
501
+ if (m?.ticks !== undefined)
502
+ side.ticks = m.ticks;
503
+ sides.push(side);
504
+ });
505
+ });
506
+ const lengths = sides.flatMap((x) => {
507
+ const l = x.label === undefined ? undefined : lengthOf(x.label);
508
+ return l ? [{ side: x, ...l }] : [];
509
+ });
510
+ const withUnits = lengths.filter((l) => l.unit !== "").length;
511
+ const comparable = withUnits === 0 || withUnits === lengths.length;
512
+ if (!comparable) {
513
+ const bare = lengths.find((l) => l.unit === "");
514
+ const unit = lengths.find((l) => l.unit !== "");
515
+ problems.push(`${bare.side.at}.label: says ${bare.side.label} with no unit, but ${unit.side.at} says ${unit.side.label}; give every length its unit, or none`);
516
+ }
517
+ const mm = (l) => l.value * (lengthUnits[l.unit] ?? 1);
518
+ for (const a of sides)
519
+ for (const b of sides) {
520
+ if (a.at >= b.at || a.ticks === undefined || a.ticks !== b.ticks)
521
+ continue;
522
+ if (Math.abs(a.len - b.len) > 0.02 * Math.max(a.len, b.len))
523
+ problems.push(`${b.at}.ticks: sides with ${a.ticks} tick${a.ticks === 1 ? "" : "s"} are equal, but this one is drawn ${say(b.len)} long and ${a.at} ${say(a.len)}`);
524
+ const la = lengths.find((l) => l.side === a);
525
+ const lb = lengths.find((l) => l.side === b);
526
+ if (comparable && la && lb && Math.abs(mm(la) - mm(lb)) > 1e-9)
527
+ problems.push(`${b.at}.label: says ${b.label}, but its ticks make it equal to ${a.at}, ${a.label}`);
528
+ }
529
+ if (comparable && lengths.length >= 2) {
530
+ const ratios = lengths.map((l) => ({ l, r: l.side.len / mm(l) }));
531
+ const lo = ratios.reduce((x, y) => (y.r < x.r ? y : x), ratios[0]);
532
+ const hi = ratios.reduce((x, y) => (y.r > x.r ? y : x), ratios[0]);
533
+ if (hi.r > 1.75 * lo.r)
534
+ problems.push(`${hi.l.side.at}.label: says ${hi.l.side.label} and is drawn ${say(hi.l.side.len)} long, but ${lo.l.side.at} says ${lo.l.side.label} and is drawn ${say(lo.l.side.len)}; draw the sides closer to the scale of their labels`);
535
+ }
536
+ // In a shape whose sides all run across or up and down, the lengths going
537
+ // one way add up to those going back.
538
+ if (comparable)
539
+ s.shapes.forEach((_, i) => {
540
+ const p = shapes[i];
541
+ const ways = new Map();
542
+ let straight = true;
543
+ p.forEach((a, k) => {
544
+ const way = heading(a, p[(k + 1) % p.length]);
545
+ if (!["right", "left", "up", "down"].includes(way) ||
546
+ (a.x !== p[(k + 1) % p.length].x && a.y !== p[(k + 1) % p.length].y))
547
+ straight = false;
548
+ const l = lengths.find((x) => x.side.at === `shapes[${i}].sides[${k}]`);
549
+ const w = ways.get(way) ?? { sum: 0, open: 0 };
550
+ if (l)
551
+ w.sum += mm(l);
552
+ else
553
+ w.open++;
554
+ ways.set(way, w);
555
+ });
556
+ if (!straight)
557
+ return;
558
+ for (const [one, other] of [
559
+ ["right", "left"],
560
+ ["down", "up"],
561
+ ]) {
562
+ const a = ways.get(one) ?? { sum: 0, open: 0 };
563
+ const b = ways.get(other) ?? { sum: 0, open: 0 };
564
+ const say_ = (v) => say(withUnits > 0 ? v / 10 : v) + (withUnits > 0 ? " cm" : "");
565
+ if (a.open === 0 && b.open === 0 && Math.abs(a.sum - b.sum) > 1e-9)
566
+ problems.push(`shapes[${i}].sides: the sides going ${one} add up to ${say_(a.sum)} and those going ${other} to ${say_(b.sum)}; in a closed shape they are equal`);
567
+ else if (a.open === 0 && b.open > 0 && b.sum >= a.sum - 1e-9)
568
+ problems.push(`shapes[${i}].sides: the labelled sides going ${other} add up to ${say_(b.sum)} already, as much as all the sides going ${one}, ${say_(a.sum)}`);
569
+ else if (b.open === 0 && a.open > 0 && a.sum >= b.sum - 1e-9)
570
+ problems.push(`shapes[${i}].sides: the labelled sides going ${one} add up to ${say_(a.sum)} already, as much as all the sides going ${other}, ${say_(b.sum)}`);
571
+ }
572
+ });
573
+ if (problems.length > before)
574
+ return;
575
+ for (const p of layout(s).problems)
576
+ problems.push(p);
577
+ },
578
+ draw(scene, pen) {
579
+ const s = scene;
580
+ const l = layout(s);
581
+ const dx = margin - l.box.x0;
582
+ const dy = margin - l.box.y0;
583
+ const at = (q) => ({ x: q.x + dx, y: q.y + dy });
584
+ s.shapes.forEach((sh, i) => {
585
+ pen.el("path", {
586
+ class: "shape",
587
+ d: poly(l.polys[i].map(at)),
588
+ fill: colors[sh.color ?? "white"].fill,
589
+ stroke: ink,
590
+ "stroke-width": outline,
591
+ "stroke-linejoin": "round",
592
+ });
593
+ });
594
+ const move = `translate(${n(dx)} ${n(dy)})`;
595
+ for (const d of l.rights)
596
+ pen.el("path", {
597
+ class: "right",
598
+ d,
599
+ transform: move,
600
+ fill: "none",
601
+ stroke: ink,
602
+ "stroke-width": 2,
603
+ "stroke-linejoin": "round",
604
+ });
605
+ for (const d of l.arcs)
606
+ pen.el("path", {
607
+ class: "arc",
608
+ d,
609
+ transform: move,
610
+ fill: "none",
611
+ stroke: ink,
612
+ "stroke-width": 2,
613
+ });
614
+ for (const [a, b] of l.ticks)
615
+ pen.el("path", {
616
+ class: "tick",
617
+ d: poly([at(a), at(b)], false),
618
+ stroke: ink,
619
+ "stroke-width": 2.2,
620
+ "stroke-linecap": "round",
621
+ });
622
+ for (const t of l.labels) {
623
+ const q = at(t.at);
624
+ drawLabel(pen, q.x, q.y, t.text, t.size, t.fill);
625
+ }
626
+ return { width: l.box.x1 - l.box.x0 + 2 * margin, height: l.box.y1 - l.box.y0 + 2 * margin };
627
+ },
628
+ describe(scene) {
629
+ const s = scene;
630
+ const shapes = s.shapes.map(corners);
631
+ const all = shapes.flat();
632
+ const whole = boxOf(all);
633
+ const several = s.shapes.length > 1;
634
+ const out = [];
635
+ if (several)
636
+ out.push(`A figure made of ${s.shapes.length} shapes that touch along their sides.`);
637
+ s.shapes.forEach((sh, i) => {
638
+ const p = shapes[i];
639
+ const K = p.length;
640
+ const name = (k) => sh.letters?.[k % K] ?? `corner ${(k % K) + 1}`;
641
+ const box = boxOf(p);
642
+ const color = colors[sh.color ?? "white"].word;
643
+ const what = kindOf(sh, p);
644
+ const head = several
645
+ ? `Shape ${i + 1}, ${placeWords(where(centroid(p), whole))} of the figure, is ${article(color)} ${color} ${what}`
646
+ : `${capital(article(color))} ${color} ${what}`;
647
+ const square = p.every((a, k) => a.x === p[(k + 1) % K].x || a.y === p[(k + 1) % K].y);
648
+ let shape = head;
649
+ if (square && K > 4) {
650
+ const turns = p.map((_, k) => cornerOf(p, k).theta);
651
+ const outward = turns.filter((t) => Math.abs(t - 90) < 1).length;
652
+ const inward = turns.filter((t) => Math.abs(t - 270) < 1).length;
653
+ shape += `; all its sides run straight across or straight up and down, so its corners are right angles: ${outward} pointing outwards and ${inward} pointing inwards`;
654
+ }
655
+ out.push(`${shape}.`);
656
+ const sideWords = (k) => {
657
+ const m = sh.sides?.[k] ?? undefined;
658
+ return [
659
+ m?.label === undefined
660
+ ? ""
661
+ : m.label === "?"
662
+ ? "labelled with a question mark"
663
+ : `labelled ${m.label}`,
664
+ m?.ticks ? `marked with ${countWord(m.ticks)} tick${m.ticks === 1 ? "" : "s"}` : "",
665
+ ].filter(Boolean);
666
+ };
667
+ if (isRectangle(p)) {
668
+ const at = (k) => {
669
+ const a = p[k];
670
+ const b = p[(k + 1) % K];
671
+ if (a.y === b.y)
672
+ return a.y === box.y0 ? "top" : "bottom";
673
+ return a.x === box.x0 ? "left" : "right";
674
+ };
675
+ if (sh.letters)
676
+ out.push(`Its corners: ${listOf(p.map((q, k) => `${name(k)} at the ${where(q, box)}`))}.`);
677
+ const marked = p.map((_, k) => ({ k, words: sideWords(k) })).filter((x) => x.words.length);
678
+ if (marked.length === 0)
679
+ out.push("Its sides carry no marks.");
680
+ else
681
+ out.push(`${capital(marked.map((x) => `its ${at(x.k)} side is ${x.words.join(" and ")}`).join("; "))}${marked.length < 4 ? "; the other sides carry no marks" : ""}.`);
682
+ }
683
+ else {
684
+ const marked = p.some((_, k) => sideWords(k).length > 0);
685
+ const steps = p.map((a, k) => {
686
+ const words = sideWords(k);
687
+ const to = k + 1 === K ? `back to ${name(0)}` : `to ${name(k + 1)}`;
688
+ const way = `${to} going ${heading(a, p[(k + 1) % K])}`;
689
+ if (!marked)
690
+ return way;
691
+ return `${way}, ${words.length ? words.join(" and ") : "unlabelled"}`;
692
+ });
693
+ out.push(`Going round from ${name(0)} at the ${where(p[0], box)}: ${steps.join("; ")}.${marked ? "" : " Its sides carry no marks."}`);
694
+ }
695
+ const angles = (sh.angles ?? []).flatMap((m, k) => {
696
+ if (!m)
697
+ return [];
698
+ const label = m.label === undefined
699
+ ? ""
700
+ : m.label === "?"
701
+ ? ", labelled with a question mark"
702
+ : `, labelled ${m.label}`;
703
+ if (m.right)
704
+ return [`at ${name(k)} a right-angle mark${label}`];
705
+ const arcs = m.arcs ?? 1;
706
+ return [`at ${name(k)} ${countWord(arcs)} arc${arcs === 1 ? "" : "s"}${label}`];
707
+ });
708
+ if (angles.length > 0)
709
+ out.push(`Angles marked: ${angles.join("; ")}.`);
710
+ if (sh.label)
711
+ out.push(`Written inside it: ${sh.label === "?" ? "a question mark" : `"${sh.label}"`}.`);
712
+ });
713
+ if (s.shapes.some((sh) => sh.sides?.some((m) => m?.ticks)))
714
+ out.push("Sides with the same number of ticks are equal.");
715
+ if (s.shapes.some((sh) => sh.angles?.some((m) => (m?.arcs ?? 1) > 1)))
716
+ out.push("Angles with the same number of arcs, two or more, are equal.");
717
+ shapes.forEach((p, i) => {
718
+ for (let j = 0; j < i; j++) {
719
+ const q = shapes[j];
720
+ const box = boxOf(q);
721
+ edgesOf(q).forEach(([c, d], l) => {
722
+ const along = edgesOf(p)
723
+ .map(([a, b]) => meet(c, d, a, b, 1e-6))
724
+ .filter((m) => m.how === "along");
725
+ if (along.length === 0)
726
+ return;
727
+ const part = along.reduce((sum, m) => sum + (m.how === "along" ? m.to - m.from : 0), 0) < 1 - 1e-6;
728
+ const sh = s.shapes[j];
729
+ const K = q.length;
730
+ const named = (k) => sh.letters?.[k % K] ?? `corner ${(k % K) + 1}`;
731
+ const side = c.y === d.y
732
+ ? c.y === box.y0
733
+ ? "top side"
734
+ : c.y === box.y1
735
+ ? "bottom side"
736
+ : `side from ${named(l)} to ${named(l + 1)}`
737
+ : c.x === d.x
738
+ ? c.x === box.x0
739
+ ? "left side"
740
+ : c.x === box.x1
741
+ ? "right side"
742
+ : `side from ${named(l)} to ${named(l + 1)}`
743
+ : `side from ${named(l)} to ${named(l + 1)}`;
744
+ out.push(`Shape ${i + 1} lies against ${part ? "part of " : ""}shape ${j + 1}'s ${side}.`);
745
+ });
746
+ }
747
+ });
748
+ // Corners are named "corner 1", "corner 2" only where the picture gives no letter.
749
+ if (/\bcorner \d/.test(out.join(" ")))
750
+ out.splice(several ? 1 : 0, 0, several
751
+ ? "Corners that carry no letter in the picture are numbered here from 1, going round each shape."
752
+ : "The corners are not lettered in the picture; here they are numbered from 1, going round the shape.");
753
+ return out.join(" ");
754
+ },
755
+ };